text:
Q: Cost complexity pruning decision trees I am trying to understand cost complexity pruning in classification trees.
I found that DecisionTree in sklearn has a function called cost_complexity_pruning_path, which gives the effective alphas of subtrees during pruning.
What does effective alpas means? I though alpha, that ranges between 0 And 1, is the parameter in an optimization problem. So I thought that all possible alpha values should be tested to find the min value of the objective function. Why in python specific effective alpha values are produced and not all possible values are not tested?
Thanks,
Andreas


text:
Q: Java Reflect/AOP override supertype private Method Is it at all possible to "override" a private method of a super class in Java?
The class whose method I wish to override is a third party class so I cannot modify the source. It would be ideal if there were some way to reflectively set a method on a class.
Alternatively, if it is possible to intercept a private method of a third party class then this would be suitable.

A: YES. You can do it with AspectJ. It is not a true override but result will be so.
Here your super class;
public class MySuperClass {

    private void content(String text) {
       System.out.print("I'm super " + text);
    }

    public void echo() {
       content("!");
    }
}

Create an interface which contains similar method;
public interface Content {
    void safeContent(String text);
}

Create an aspect that forces super class to implement that interface and add an around adviser to call it.
public privileged aspect SuperClassAspect {

    void around(MySuperClass obj)
            : execution(* content(String)) && target(obj) {

        Object[] args = thisJoinPoint.getArgs();
        ((Content) obj).safeContent((String) args[0]);
    }

    // compiler requires
    public void MySuperClass.safeContent(String text) {}

    declare parents :MySuperClass implements Content;
}

Create your child class that extends super and implements that interface.
public class Overrider extends MySuperClass implements Content {

    public void safeContent(String text) {
        System.out.print("Not that super " + text);
    }
}

Now if you construct a Overrider object and invoke echo method, you will have an output of Overriders safeContent's method.

A:
Is it at all possible to "override" a private method of a super class in Java?

No
I don't think using Reflection there would be a tweak , it will break OOP there

A: You do not have a legal way to do this. But I can suggest you the following solutions.

*

*Do you really wish to override this method? Try to think about other solution.

*Java checks access permissions during compilation only. Are you surprised? I was surprised very much to find out this fact. So you can create skeleton of the third party class (even with empty implementations.). The interesting method should be protected instead of private. Now write your subclass and compile it against your stub. Then package only your subclass and try to run it with the "real" class. It should work. I have not tried this trick with inheritance but I have tried it when I had to access private method or field and it worked fine for me.

*Try to use dynamic proxy that wraps your class and changes its implementation. I do not know what are you doing exactly, so I am not sure you can really use this method. But I hope you can. If not go back to #1 or #2.

A: yes it's possible ,but you should not do it, because it contradicts one of the SOLID principles. More exactly it contradicts Liskov substitution principle.

Note:
  Let q(x) be a property provable about objects x of type T. Then q(y)
  should be provable for objects y of type S, where S is a subtype of T.

So in other words , private method is property of object, so your object of inherited type must have the same property. The same with throws for methods.
Java restricts it because of it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove `tns` prefix from elements in xsd schema inserted into wsdl? I have wsdl where xsd inserted. It looks like:

The question is quite simple, but i can not find decision:
How to remove tns profix from the login and password elements?
When i tried to remove tns appears automatically.

A: I just remove elementFormDefault="qualified" from
<xsi:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema" xmlns:altova="http://www.altova.com/xml-schema-extensions" targetNamespace="http://new.webservice.namespace" elementFormDefault="qualified">

in WSDL and now there is no tns prefix.
Or change "qualified" to "unqualified".


text:
Q: How can I improve cardinality estimates on staging tables? I support a process that runs every night and looks at various clients that have invoices with unpaid line items. The process starts with deleting all records from a staging table and then inserting a number of invoices line items into the staging table.  The process run on a per-client basis, so some clients may have 200 line items, some clients may have 50,000.  We are constantly having issues with the process running an exorbitant amount of time. The issue seems to stem from an inability for SQL server to estimate the correct number of rows that are in the staging table at the time and therefore is generating a bad execution plan.  My question is, is there a way to manually set the estimated number of rows to improve cardinality estimates for the stored procedures involved? Perhaps this could be done through a select count(primaryKey) at the beginning of the run, right after the current runs staging table is populated?

A: You are executing big batch processes on this table. It's a good approach to delete all indexes before your batch and create them again after the batch.
If you do this, your statistics will be updated and won't be the cause of your problem.
Pay heed also to more generic information about statistics: The update statistics changed a lot between SQL Server 2014 and SQL Server 2016. If you are running SQL Server 2016, you need to check if your database is using the new cardinality estimator created for SQL Server 2016. Just check if your database is running with SQL Server 2016 compatibility level.
If you are running SQL Server 2014, a good option is to enable the trace flag 2371. This trace flag improves the criteria SQL Server uses to automatic update statistics. You should use SQL Server Configuration Manager to enable this trace flag.
However, if you follow the first suggestion, deleting and creating the indexes, the other two suggestion will have low or none impact.


text:
Q: How to protect media directory with .htaccess? I am trying to protect the uploads directory with .htacess.
But when I browse media section in admin panel, I see user/pass popup.
My guess is, WordPress use fopen to find if the file exists. I found mod_rewrite rule allowing fopen but I can't figure out how to use those rules with basic HTTP authentication. Any help is highly appreciated.
following is the rewrite rules for allowing fopen:
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^.+$ [NC]
RewriteRule .* - [F,L]

A: # Only allow access to this directory if they are coming from your domain; excluding you, your server, Google and any other IPs
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^(xxx\.xxx\.xxx\.xxx|xxx\.xxx\xxx\.xxx|66\.249\.)
RewriteCond %{HTTP_HOST} !^(127\.0\.0\.0|localhost) [NC]
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?yourdomain\.com/ [NC]
RewriteRule .* http://yourdomain.com/ [L]

That should help, I think

A: See this popular answer, it works and is easy to use.
You find the source als oin a Gist.


text:
Q: How to handle static fields that vary by implementing class I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).

*

*I define an interface ICommand

*I create an abstract base class CommandBase which implements ICommand, to contain common code.

*I create several implementation classes, each extending the base class (and by extension the interface).

Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...
For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:
public abstract static const string Name;
However (sadly) you cannot define static members in an interface.
I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.

UPDATE:

*

*I can't get the code formatting to work properly (Safari/Mac?). Apologies.

*The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).

*I forgot to mention - ideally I want to be able to query this information statically:
string name = CommandHelp.Name;
2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.

A: You may consider to use attributes instead of fields.
[Command("HELP")]
class HelpCommand : ICommand
{
}

A: As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you can do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:
public abstract class MyBaseClass
{
  public abstract string Name { get; protected set; }
}

public class MyClass : MyBaseClass
{
  public override string Name
  {
    get { return "CommandName"; }
    protected set { }
  }
}

(Note that the protected set prevents outside code changing the name.)
This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields do not vary; you simply can't have a member that is both static and overridable for a given class.

A: public interface ICommand {
      String getName();
}

public class RealCommand implements ICommand {
     public String getName() {
           return "name";
     }
}

Simple as that. Why bother having a static field?

Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like David B suggestion). What if someone extends the abstract class and forget to initiate the field?

A: [Suggested solution #1 of 3]

*

*Define an abstract property Name in the interface to force all implementing classes to implement the name property.

*(in c#) Add this property as abstract in the base class.

*In the implementations implement like this:
public string Name
{
  get {return COMMAND_NAME;}
}

Where name is a constant defined in that class.
Advantages:

*

*Name itself defined as a constant.

*Interface mandates the property be created.

Disadvantages:

*

*Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?

A: just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name

A: What I usually do (in pseudo):
abstract class:

private const string nameConstant = "ABSTRACT";

public string Name
{
   get {return this.GetName();}
}

protected virtual string GetName()
{
   return MyAbstractClass.nameConstant;
}

----

class ChildClass : MyAbstractClass
{
   private const string nameConstant = "ChildClass";

   protected override string GetName()
   {
      return ChildClass.nameConstant;
   }
}

Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".

A: [Suggested solution #2 of 3]

*

*Make a private member variable name.

*Define an abstract property Name in the interface.

*Implement the property in the base class like this:
public string Name
{
  get {return Name;}
}

*Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:
public abstract class CommandBase(string commandName) : ICommand
{
  name = commandName;
}

*Now all my implementations set the name in the constructor:
public class CommandHelp : CommandBase(COMMAND_NAME) {}

Advantages:

*

*My accessor code is centralised in the base class.

*The name is defined as a constant

Disadvantages

*

*Name is now an instance variable -
every instance of my Command classes
makes a new reference rather than
sharing a static variable.

A: My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:
interface A { abstract static NAME }
class B { NAME = "HELP" }
class C { NAME = "PRINT" }

Then how could this code know which NAME to link to:
void test(A a) {
    a.NAME;
}

How I would suggest to implement this, is one of the following ways:

*

*Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.

*The base class has a constructor which takes name

*Use annotations and enforce their presence through the base class.

However, a much better solution is proabably to use enums:
public enum Command {
    HELP { execute() }, PRINT { execute() };
    abstract void execute();
}

This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.

A: [Suggested answer # 3 of 3]
I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:
[CammandAttribute(Name="HELP")]
Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.

A: From a design perspective, I think it is wrong to require a static implementation member...  The relative deference between performance and memory usage between static and not for the example string is minimal.  That aside, I understand that in implementation the object in question could have a significantly larger foot print...
The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited...  Only properties and methods are available at the interface level.
The next design challenge is whether the code will be base or implementation specific.  With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations.  With base your valdiation will occur at run time but logic would be centralized in one place.  Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.
So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing.  Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization.  I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time.  All IDE's I work with make this very quick any easy.  For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.
Circling back to the very specific nature of the question and ignoring many of the other design problems...  If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem...  Definately go with a method over properties, as there are way to many side effects to make go use of properties.  Use a static member on the base class and use a static constructor on the implementations to set the name.  Now keep in mind that you have to valdiate the name at run-time and not compile time.  Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name.  It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user.  Or you could use reflection to get the implementation name and try to generate a name...  The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...
For that matter you could always generate the name from the class name thru reflection...  Though in the long term this could be a nightmare to maintain...  It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns.  Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.

A: What about something like this:
abstract class Command {
   abstract CommandInfo getInfo();
}

class CommandInfo {
  string Name;
  string Description;
  Foo Bar;
}

class RunCommand {
  static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42)  };

  override commandInfo getInfo() { return Info; }
}

Now you can access the information statically:
RunCommand.Info.Name;

And from you base class:
getInfo().Name;


text:
Q: How to ship or distribute a matplotlib stylesheet I want to distribute a custom matplotlib style sheet, but right now the only way I can think of is uploading it to Gist or some other website and tell my users to manually download it to some configuration directory.
Is there a way to distribute a style sheet as if it were a Python package, or as part of a module? Something easy like pip install mpl_fancy.

A: After reading the link from @aloctavodia and consulting the massmutual/mmviz-python GitHub repo, this is what I came up with.
setup.py
from setuptools import setup
from setuptools.command.install import install
import os
import shutil
import atexit

import matplotlib

def install_mplstyle():
    stylefile = "mystyle.mplstyle"

    mpl_stylelib_dir = os.path.join(matplotlib.get_configdir() ,"stylelib")
    if not os.path.exists(mpl_stylelib_dir):
        os.makedirs(mpl_stylelib_dir)

    print("Installing style into", mpl_stylelib_dir)
    shutil.copy(
        os.path.join(os.path.dirname(__file__), stylefile),
        os.path.join(mpl_stylelib_dir, stylefile))

class PostInstallMoveFile(install):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        atexit.register(install_mplstyle)

setup(
    name='my-style',
    version='0.1.0',
    py_modules=['my_style'],
    install_requires=[
        'matplotlib',
    ],
    cmdclass={
        'install': PostInstallMoveFile,
    }
)

Into my_style.py I just put a basic example script. Now, my users can install this style with pip install git+https://github.com/me/my-style!


text:
Q: Is there a method or something i can use to make a button press himself? Is there a way I can make the program itself press a button for me? I need to make a chess like game that the player plays vs the program. I made a 2d array of buttons for this. This is why i need a way for the program to press a button for me. im using swing JButton. What i mean is that, Is there a method or something i can use to make a button press himself?
my program works but is player vs player. here it is:
    package ratsuk;

    import javax.swing.JFrame;
    import javax.swing.JButton;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.AbstractButton;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JPanel;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;

    /**
     *
     * @author Melvin
     */
    public class Tablero {

        private static final int HEIGHT = 8;
        private static final int WIDTH = 8;
        private JButton[][] mesa;
        private Icon image;
        private JPanel panel;
        private JFrame ventana;

        public Tablero() {
            ventana = new JFrame();
            mesa = new JButton[HEIGHT][WIDTH];
            panel = new JPanel(new GridLayout(HEIGHT, WIDTH));
            image = new ImageIcon(getClass().getResource("redKnight.gif"));

            crearventana();

            crearmesa();

            pintarmesa();
        }

        private void crearventana() {
            Menu men =new Menu();
            setVentana(new JFrame("Juego de Ratsuk"));
            getVentana().setVisible(true);
            getVentana().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getVentana().setLayout(new BorderLayout());
            getVentana().setSize(375, 500);
            getVentana().add(panel , BorderLayout.NORTH);
            getVentana().add(men.getPanel1(),BorderLayout.SOUTH);

            getVentana().setVisible(true);
        }

        private void crearmesa() {

            for (int row = 0; row < HEIGHT; row++) {
                for (int column = 0; column < WIDTH; column++) {
                    JButton button = new JButton();
                    button.setPreferredSize(new Dimension(40, 40));

                    mesa[row][column] = button;
                    panel.add(button);

                }
            }
        }

        private void pintarmesa() {
            Color fondo;
            for (int r = 0; r < HEIGHT; r++) {
                for (int t = 0; t < WIDTH; t++) {
                    fondo = getBackgroundColor(r, t);

                    mesa[r][t].setBackground(fondo);
                }
            }
        }

        private Color getBackgroundColor(int r, int t) {
            Color fondo;
            if (r % 2 == 0 || r == 0) {
                if (t % 2 == 0 || t == 0) {
                    fondo = Color.BLACK;
                } else {
                    fondo = Color.WHITE;
                }
            } else {
                if (t % 2 == 0 || t == 0) {
                    fondo = Color.WHITE;
                } else {
                    fondo = Color.BLACK;
                }
            }
            return fondo;
        }

        public void caballo(final int row, final int column) {
            if (conclucion(row, column)) {
                JOptionPane.showMessageDialog(null, "The game End");
            } else {
                final JButton current = mesa[row][column];

                current.setIcon(image);
              //  panel.repaint();

                acciones(row, column, current);
            }
        }

        public void acciones(final int row, final int column, final JButton current) {
            ActionListener[] bu;

            for (int i = 0; i < HEIGHT; i++) {
                for (int j = 0; j < WIDTH; j++) {
                    bu = mesa[i][j].getActionListeners();
                    for (int k = 0; k < bu.length; k++) {
                        bu = mesa[i][j].getActionListeners();
                        mesa[i][j].removeActionListener(bu[k]);
                    }
                }
            }
            for (int i = 0; i < HEIGHT; i++) {
                for (int j = 0; j < WIDTH; j++) {
                    mesa[i][j].addActionListener(e(row, column, current));

                    ((AbstractButton) current).setEnabled(false);
                    current.setBackground(Color.RED);
                }
            }
        }

        public ActionListener e(final int row, final int column,
                final JButton current) {
            return new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    if (tienebotton(row + 2, column + 1)) {
                        if (e.getSource() == mesa[row + 2][column + 1]) {

                            current.setIcon(null);
                            caballo(row + 2, column + 1);

                        }
                    }
                    if (tienebotton(row + 2, column - 1)) {
                        if (e.getSource() == mesa[row + 2][column - 1]) {

                            current.setIcon(null);
                            caballo(row + 2, column - 1);

                        }
                    }
                    if (tienebotton(row - 2, column - 1)) {
                        if (e.getSource() == mesa[row - 2][column - 1]) {

                            current.setIcon(null);
                            caballo(row - 2, column - 1);

                        }
                    }
                    if (tienebotton(row - 2, column + 1)) {
                        if (e.getSource() == mesa[row - 2][column + 1]) {

                            current.setIcon(null);
                            caballo(row - 2, column + 1);

                        }
                    }

                    if (tienebotton(row + 1, column + 2)) {
                        if (e.getSource() == mesa[row + 1][column + 2]) {

                            current.setIcon(null);
                            caballo(row + 1, column + 2);

                        }
                    }
                    if (tienebotton(row - 1, column + 2)) {
                        if (e.getSource() == mesa[row - 1][column + 2]) {

                            current.setIcon(null);
                            caballo(row - 1, column + 2);

                            ((AbstractButton) e.getSource()).setEnabled(false);

                        }
                    }
                    if (tienebotton(row + 1, column - 2)) {
                        if (e.getSource() == mesa[row + 1][column - 2]) {

                            current.setIcon(null);
                            caballo(row + 1, column - 2);

                        }
                    }
                    if (tienebotton(row - 1, column - 2)) {
                        if (e.getSource() == mesa[row - 1][column - 2]) {

                            current.setIcon(null);
                            caballo(row - 1, column - 2);

                        }
                    }
                }
            };
        }

        public boolean tienebotton(int row, int column) {
            return (row >= 0 && row < HEIGHT && column >= 0 && column < WIDTH);

        }

        public boolean conclucion(int row, int column) {
            boolean estado, estado1, estado2, estado3, estado4, estado5, estado6, estado7;

            if (tienebotton(row + 2, column + 1)) {
                estado = mesa[row + 2][column + 1].isEnabled();
            } else {
                estado = false;
            }
            if (tienebotton(row + 2, column - 1)) {
                estado1 = mesa[row + 2][column - 1].isEnabled();
            } else {
                estado1 = false;
            }
            if (tienebotton(row - 2, column + 1)) {
                estado2 = mesa[row - 2][column + 1].isEnabled();
            } else {
                estado2 = false;
            }
            if (tienebotton(row - 2, column - 1)) {
                estado3 = mesa[row - 2][column - 1].isEnabled();
            } else {
                estado3 = false;
            }
            if (tienebotton(row + 1, column + 2)) {
                estado4 = mesa[row + 1][column + 2].isEnabled();
            } else {
                estado4 = false;
            }
            if (tienebotton(row - 1, column + 2)) {
                estado5 = mesa[row - 1][column + 2].isEnabled();
            } else {
                estado5 = false;
            }
            if (tienebotton(row + 1, column - 2)) {
                estado6 = mesa[row + 1][column - 2].isEnabled();
            } else {
                estado6 = false;
            }
            if (tienebotton(row - 1, column - 2)) {
                estado7 = mesa[row - 1][column - 2].isEnabled();
            } else {
                estado7 = false;
            }
            return (estado == false && estado1 == false && estado2 == false && estado3 == false && estado4 == false && estado5 == false && estado6 == false && estado7 == false);
        }

        /**
         * @return the ventana
         */
        public JFrame getVentana() {
            return ventana;
        }

        /**
         * @param ventana the ventana to set
         */
        public void setVentana(JFrame ventana) {
            this.ventana = ventana;
        }
    }

package ratsuk;

import java.util.Random;
import javax.swing.JFrame;

/**
 * import javax.swing.JFrame; import javax.swing.SwingUtilities; import
 * javax.swing.UIManager;
 */
public class Ratsuk extends JFrame {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Random rad;
        rad = new Random();
        int row = rad.nextInt(8);
        int column = rad.nextInt(8);

      Tablero newtablero = new Tablero();

        newtablero.caballo(row, column);

    }
}

A: Based on the structure of your code, the easiest way to do this is:
button.doClick();

Another option is to have your ActionListener invoke a method when the button is clicked. Then in your program you can manually invoke the same method.


text:
Q: Android OnItemSelected of a Spinner is triggered after several other methods finish executing I have been going through the threads regarding the spinners and when the onItemSelected is triggered. I concluded that it is triggered whether you manually select a spinner item or your programmatically select an item through the spinner.setSelection(position) method.
My problem is that OnItemSelected callback method is called first within my code, but it is executed after several other methods finish executing. This is an undesired behavior because my code logic depends on certain steps being executed in sequence.
if(conition is true)
  fillSpecialtySpinner();

if(another condition is true)
  fillSubSpecialtySpinner();

The fillSpecialtySpinner() method contains the spinner.setSelection(position) line of code. But somehow it is executed after the second if is checked and the fillSubSpecialtySpinner finishes executing.
Any help would be appreciated. Thank you in advance!

A: If I understand correctly, you are wanting to make sure that fillSubSpecialtySpinner() method is only called after specialitySpinner.onItemSelected().
Can you just call fillSubSpecialtySpinner() from within specialitySpinner.onItemSelected()?

A: The callback doesn't happen until every other function is executed, yes, ad Baqueta said.
So you can't do something like set a boolean to false, make the change to the spinner, (execute code in onItemSelected if boolean is true), then set it to true, because the function will get called AFTER your boolean becomes true.
However, I have an easy and generic solution to the problem (Refer the accepted answer to the question):
Undesired onItemSelected calls


text:
Q: Ввод данных и вывод в разных потоках C# Хочу написать змейку в консоли, и реализовать это следующим способом: существуют два потока: один принимает ввод с клавиатуры, второй - отрисовывает игру и делает какие-то проверки. Первый поток будет принимать ввод и записывать нажатые символы в поток команд, а второй поток будет считывать данные из этого буфера и реализовывать эти команды.
Не могу понять, как запустить эти две задачи в разных потоках (ранее не сталкивался с конкурентностью в C#).

A: Покажу сразу перечисление, которое будет использовать во всех примерах.
public enum Direction
{
    Right,
    Down,
    Left,
    Up,
    Stop
}

Для начала, вашу задачу можно реализовать вообще без дополнительных потоков. Есть конечно кое-какие ограничения, связанные с этим, но для начала этот способ является наиболее предпочтительным, если вы только начинаете учиться писать код.
class Program
{
    static void Main(string[] args)
    {
        ConsoleKey key = default;
        Direction direction = Direction.Right;
        while (true)
        {
            Thread.Sleep(1000);
            if (Console.KeyAvailable)
                key = Console.ReadKey(true).Key;
            switch (key)
            {
                case ConsoleKey.DownArrow:
                    direction = Direction.Down;
                    break;
                case ConsoleKey.UpArrow:
                    direction = Direction.Up;
                    break;
                case ConsoleKey.RightArrow:
                    direction = Direction.Right;
                    break;
                case ConsoleKey.LeftArrow:
                    direction = Direction.Left;
                    break;
                case ConsoleKey.Escape:
                    direction = Direction.Stop;
                    break;
            }
            if (direction == Direction.Stop)
                break;

            Console.WriteLine(direction);
        }
    }
}

Собственно, вот весь движок для змейки готов. Вместо Console.WriteLine(direction) делаете вызов своего метода выполенния обновления игровой логики, передавая ему тот же direction, и готово.
Теперь многопоточные варианты. Многопоточность в C# давно развивается, начну с самого древнего способа делать потоки.
class Program
{
    private static Direction direction = Direction.Right;

    static void Main(string[] args)
    {
        Thread thread = new Thread(Loop);
        thread.Start();
        while (true)
        {
            switch (Console.ReadKey(true).Key)
            {
                case ConsoleKey.DownArrow:
                    direction = Direction.Down;
                    break;
                case ConsoleKey.UpArrow:
                    direction = Direction.Up;
                    break;
                case ConsoleKey.RightArrow:
                    direction = Direction.Right;
                    break;
                case ConsoleKey.LeftArrow:
                    direction = Direction.Left;
                    break;
                case ConsoleKey.Escape:
                    direction = Direction.Stop;
                    break;
            }
            if (direction == Direction.Stop)
                break;
        }
        Console.WriteLine("Exit program");
    }

    private static void Loop()
    {
        while (true)
        {
            Thread.Sleep(1000);
            if (direction == Direction.Stop)
                break;
            Console.WriteLine(direction);
        }
        Console.WriteLine("Exit thread");
    }
}

Работает точно так же, как и первый пример. Обратите внимание, что при нажатии Esc сначала в консоль напишется Exit program, и только потом Exit thread. Это не создает проблем, пока поток не является фоновым Thread.IsBackground = true, так как приложение при выходе убивает только фоновые потоки. Основные потоки должны завершиться самостоятельно, иначе приложение не завершится. Подводный камень здесь именно как раз в том, что приложение может зависнуть в процессах системы, пока вы его не убьете, если хотя-бы один основной поток не будет нормально завершен.
Кстати, потоки можно запускать более современным способ используя пул потоков. За это отвечает класс System.Threading.Tasks.Task.
То есть строчки
Thread thread = new Thread(Loop);
thread.Start();

Можно заменить на просто
Task.Run(() => Loop());

Но все потоки из пула являются фоновыми, то есть при выходе из приложения ожидания завершения фонового потока не произойдет, он будет просто убит, а это еще одна проблема. Нам ведь хочется, чтобы весь наш код нормально завершался. Другими словами Task.Run здесь только усугубляет ситуацию.
Сразу отмечу разницу между первым и вторым примером. Второй пример - неправильный. Дело в том, что цикл чтения с клавиатуры не закончится, пока не нажмете Esc. А если вы закроете окно консоли, то в окне Output в Visual Studio, получите вот такой вывод.
The program '[5712] ConsoleApp1.exe' has exited with code -1073741510 (0xc000013a).

Это означает, что приложение завершилось принудительно Ctrl+C Exit. При нормальном завершении приложения эта строчка выглядит так.
The program '[8224] ConsoleApp1.exe' has exited with code 0 (0x0).

Но эту ошибку не побороть (во всяком случае, на данный момент, я не знаю как), можно побороть только проблему ненормального выхода из приложения. То есть сделать так, чтобы Main успел завершиться полностью прежде чем приложения закроется.
То есть надо возвращаться к способу, который использует Console.KeyAvailable. В противном случае Console.ReadKey будет "висеть" до тех пор, пока не будет нажата клавиша, и эту проблему без постоянного опрашивания Console.KeyAvailable в консоли объехать не просто. А как выше было показано, дополнительный поток при таком подходе не нужен.
Возвращаемя к тому, с чего начали, только теперь делаем нормальное завершение приложения при закрытии окна консоли. Чтобы отслеживать что код приложения завершился я буду использовать вывод в отладочную консоль Visual Studio. Такую возможность дает специальный класс Debug.
Подключим пространство имен
using System.Diagnostics;

Получится вот такой код
class Program
{
    private static Direction direction = Direction.Right;
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        ConsoleKey key = default;

        while (true)
        {
            Thread.Sleep(1000);
            if (Console.KeyAvailable)
                key = Console.ReadKey(true).Key;
            switch (key)
            {
                case ConsoleKey.DownArrow:
                    direction = Direction.Down;
                    break;
                case ConsoleKey.UpArrow:
                    direction = Direction.Up;
                    break;
                case ConsoleKey.RightArrow:
                    direction = Direction.Right;
                    break;
                case ConsoleKey.LeftArrow:
                    direction = Direction.Left;
                    break;
                case ConsoleKey.Escape:
                    direction = Direction.Stop;
                    break;
            }
            if (direction == Direction.Stop)
                break;

            Console.WriteLine(direction);
        }
        Debug.WriteLine("Program exit");
    }

    private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        direction = Direction.Stop;
        Thread.Sleep(1000);
    }
}

Вывод в окно Output Visual Studio теперь выглядит так
Program exit
The program '[5188] ConsoleApp1.exe' has exited with code -1073741510 (0xc000013a).

То есть приложение завершается нормально. Но есть проблема, обратите внимание на Thread.Sleep, который я использую чтобы дождаться завершения работы основного потока метода Main. Дело в том, что Thread.Sleep, как и Console.ReadKey просто так не прервать. Все это выливается в то, что окно приложения закрывается с задержкой в 1 секунду. Это некрасиво и выглядит как подвисание приложния. К счастью, этого можно избежать.
Есть удобная альтернатива Thread.Sleep, которую можно прерывать - Task.Delay (с помощью CancellationToken). Но Task.Delay асинхронный, следоательно здесь начинается асинхронное программирование с использование ключевых слов async/await. С самого начала поста я вас вел именно к этому.
class Program
{
    private static Direction direction = Direction.Right;
    private static readonly CancellationTokenSource cts = new CancellationTokenSource();
    static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        ConsoleKey key = default;
        try
        {
            while (true)
            {
                await Task.Delay(1000, cts.Token);
                if (Console.KeyAvailable)
                {
                    while (Console.KeyAvailable)
                    {
                        key = Console.ReadKey(true).Key;
                    }
                }
                switch (key)
                {
                    case ConsoleKey.DownArrow:
                        direction = Direction.Down;
                        break;
                    case ConsoleKey.UpArrow:
                        direction = Direction.Up;
                        break;
                    case ConsoleKey.RightArrow:
                        direction = Direction.Right;
                        break;
                    case ConsoleKey.LeftArrow:
                        direction = Direction.Left;
                        break;
                    case ConsoleKey.Escape:
                        direction = Direction.Stop;
                        break;
                }
                if (direction == Direction.Stop)
                    break;

                Console.WriteLine(direction);
            }
        }
        catch (OperationCanceledException) { }
        Debug.WriteLine("Program exit");
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        cts.Cancel();
    }
}

Теперь окно закрывается немедленно, при этом надпись в отладочкном окне Program exit все еще присутствует. С принудительным завершением приложения системой разобрались.
Теперь, как я писал в примере для WPF, хочется, чтобы Змейка реагировала на нажатия клавиш немедленно, а не с задержкой до секунды. Для этого опрос клавиатуры надо делать чаще, а не раз в секунду. Например 10 раз в секунду, при этом хочется, чтобы змейка так же двигалась раз в секунду, или с любой другой нужной скоростью, которая не зависит от частоты опроса клавиатуры. Вот здесь асинхронность разворачивается на полную и показывает свою суть.
class Program
{
    private static Direction direction = Direction.Right;
    private static readonly CancellationTokenSource cts = new CancellationTokenSource();
    private const int speedDelay = 1000;
    private static bool addDelay;

    private static Direction Direction
    {
        get => direction;
        set
        {
            if (value != direction)
            {
                direction = value;
                addDelay = true;
                Update();
            }
        }
    }

    static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        ConsoleKey key = default;
        Task snakeTask = SnakeLoop(cts.Token);
        try
        {
            while (true)
            {
                await Task.Delay(100, cts.Token);
                while (Console.KeyAvailable)
                {
                    key = Console.ReadKey(true).Key;
                }

                switch (key)
                {
                    case ConsoleKey.DownArrow:
                        Direction = Direction.Down;
                        break;
                    case ConsoleKey.UpArrow:
                        Direction = Direction.Up;
                        break;
                    case ConsoleKey.RightArrow:
                        Direction = Direction.Right;
                        break;
                    case ConsoleKey.LeftArrow:
                        Direction = Direction.Left;
                        break;
                    case ConsoleKey.Escape:
                        Direction = Direction.Stop;
                        break;
                }
                if (Direction == Direction.Stop)
                    break;
            }
            cts.Cancel();
            await snakeTask;
        }
        catch (OperationCanceledException) { }
        Debug.WriteLine("Program exit");
    }

    private static async Task SnakeLoop(CancellationToken token)
    {
        while (true)
        {
            await Task.Delay(speedDelay, token);
            if (addDelay)
            {
                addDelay = false;
                await Task.Delay(speedDelay / 2, token);
            }
            Update();
        }
    }

    private static void Update()
    {
        Console.WriteLine(Direction);
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        cts.Cancel();
    }
}

Вот теперь получется то что нужно. Движок что надо. Не спорю, можно сделать еще лучше, так чтобы после нажатии на кнопку следующая итерация движения происходила ровно через speedDelay, это бы сделало поведение змейки плавнее.
Кстати, добавил свойство Direction, оно как раз содержит логику немедленной реакции на нажатие клавиши.
Все что вам осталось сделать - это реализовать метод Update(). Еще что сдесь не сделано - нет запрета на обратный ход. То есть если змейка ползла вниз, должно быть нельзя сразу же ползти вверх, то же самое для влево и вправо. Реализуйте это сами или подсмотрите в примере для WPF, ссылку на который я дал выше.
Кстати, в обработчике события CurrentDomain_ProcessExit вы можете сделать что-то полезное. Например записать количество набранных игроком очков на диск или вообще сохранить полное состояние игры, чтобы после перезапуска приложения все началось с того же места, на котором приложение было закрыто ранее.
Да, кстати, почитайте вот это - Асинхронное программирование.


text:
Q: Gio copy all files from shared folder I want to copy all files from shared windows folder to my local folder In Ubuntu. I am using gio and following row:
gio copy smb://computerName/FoldName/* ~/localFolder/

but the result is gio: smb://...../*: Invalid argument
How to copy all files from share folder in local folder with GIO?

A: The only thing I can suggest is to use a standard copy ( cp ) command to transfer the files.
When you did your original mount:
gio mount smb://computerName/FoldName

It created a mount point at:
/run/user/$UID/gvfs/smb-share:server=computerName,share=FolderName

You can use cp to copy the contents to your local folder:
cp -r /run/user/$UID/gvfs/smb-share:server=computerName,share=FolderName/* ~/localFolder/


text:
Q: PHP Connection Timeout Issue In one of my application, users can upload CSV file (| separated fields), after uploading I am storing all the content of file in temporary table (I truncate this table every time for new upload so that it contains the current file data). After that I am iterating over each and every row of that table, and performs some database operation as per the business logic.
The following code will illustrate this:
if(isset($_POST['btn_uploadcsv']))
{
$filename = $_FILES["csvupload"]["name"];
$uploads_dir = 'csvs'; //csv files...
$tmp_name = $_FILES["csvupload"]["tmp_name"];
$name =  time();
move_uploaded_file($tmp_name, "$uploads_dir/$name");

$csvpath = "$uploads_dir/$name";

$row = 0;
$emptysql = "TRUNCATE TABLE `temp`";
$connector->query($emptysql);

if (($handle = fopen($csvpath, "r")) !== FALSE) {
    $str_ins = "";
    while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
                    /*
                     *     Here I am getting the column values to be store in the
                     *     the table, using INSERT command
                     */
                    unset($data);
    }
            fclose($handle);
}

    /*Here I am selecting above stored data using SELECT statement */

for($j=0;$j<count($allrecords);$j++)
{
        echo "In the loop";
         /*If I use echo statement for debugging it is working fine*/

        //set_time_limit(300);
        /* I have tried this also but it is not working*/

        if(!empty($allrecords[$j]['catid']))
        {
         // Here is my business logic which mailny deals with
         // conditional DB operation
        }

        echo "Iteration done.";
        /*If I use echo statement for debugging it is working fine*/
}
}

The problem is when I execute aboe script on server it is giving server timeout error. But when I test above script on my localhost, is is working fine.
Also as mentioned in the code, if I use echo statements for debugging, then it is working fine, and when I remove that it starts giving connection timeout problem.
I have tried set_time_limit(300), set_time_limit(0), but none of them seems to work.
Any idea, how can I resolve the above problem.
-- Many thanks for your time.
Edit:
I have checked that, files are uploading on the server.

A: set_time_limit

change to
ini_set("max_execution_time",300);

When max_execution_time is not set in php.ini set_time_limit valid.

A: I have resolved the issue using flush, to send intermediate output to the browser, while the query is executing in the background.
This is how I modified the code:
for($j=0;$j<count($allrecords);$j++)
{

  /*At the end of each iteration, I have added the following code*/
   echo " ";
   flush();
}

Thanks to the contributors over this link PHP: Possible to trickle-output to browser while waiting for database query to execute?, from where I got inspiration.


text: Q: Is it possible to create a Django model from csv input with non-standardized column names/number of columns I'm working on a project where the end user will provide a semi-standardized csv input to my program. By semi-standardized, I mean that most columns will always be present, but each csv has the potential to have an extra column or two that is unique to that csv alone. Because of this I don't think it's possible to pre-define an all encompassing Django model (I may be wrong, and would love to be shown otherwise), so my question is: is it possible to update/change the Django model's structure from views.py (or in some other way), based on the csv input file, to capture these non-standard columns and store the uploaded CSV to my db? If not, is there another way to go about solving this problem?


text:
Q: Restriction maps in an integral scheme are injective (Ayman Hourieh's proof) I have some questions concerning Ayman Hourieh's proof of the fact that restriction maps in an integral scheme are injective:

Let $X$ be an integral scheme. Let $\xi$ be its generic point. If we show that the canonical map $\mathcal O_X(U) \to \mathcal O_\xi$ is injective, we're done. Since $U$ can be covered by affine open subsets, we can assume that $U = \operatorname{Spec} A$ is affine. Now the map $\mathcal O_X(U) \to \mathcal O_\xi$ corresponds to the canonical map $A \to \operatorname{Frac}(A)$, where $\operatorname{Frac}(A)$ is the quotient field of $A$. This map is clearly injective as desired.

(1) Since $U$ can be covered by affine open subsets, we can assume that $U = \operatorname{Spec} A$ is affine.
I understand the case when $U$ is affine, but I don't know how to generalize it to an arbitrary open subset.
(2) I don't know how it follows from his proof that $\operatorname{res}_{U,V} : \mathcal O_X(U) \rightarrow \mathcal O_X(V)$ is injective for arbitrary open subsets $U \supset V$.
If you know another proof of this fact, please also feel free to share it in here or the linked post. Thank you!

A: (1) Follows from the definition of a sheaf - specifically, the locality axiom. Let $s$ be a section over $U$ which has image 0 under restriction to $V$. We want to show $s$ is 0. For an open cover $U_i$ of $U$, it suffices to verify that $s|_{U_i}$ is $0$ on each $U_i$. Since every scheme has a covering by open affines, this shows us that it is enough to verify the statement that restriction is injective in the case that $U$ is affine.
(2) Consider the directed system of rings indexed over all open subsets $Y$ of $U$ with objects $\mathcal{O}_X(Y)$ and morphisms the appropriate restriction maps. By definition, the limit of this system is $\mathcal{O}_\xi$, the generic point of $U$, since $\xi$ is the only point contained in every open subset of $U$. By construction of the limit, the image of a section under some restriction map being zero is equivalent to the image of that same section being zero in the limit. So it suffices to show that the map from $\mathcal{O}_X(U)\to\mathcal{O}_\xi$ is injective, which is what the original author proves.

A: For (2) say the injective maps $\mathcal{O}_X(U)\to\mathcal{O}_\eta$ are called $f_U$. Then, $f_V\circ\operatorname{res}_{U,V}=f_U$, so the restriction map is injective as well. Thus, all you need to show is that for any open set $U$ the map $f_U$ is injective.
Cover $U$ by open affines $\{U_i\}$ and take $a\in\ker f_U$. Then, by the same argument as above $f_U(a)=f_{U_i}(a|_{U_i})=0$ and since each $f_{U_i}$ is injective you're done.


text:
Q: graph database physical distribution and indexing My question is not on the query language but on the physical distribution of data in a graph database.

Let's assume a simple user/friendship model. In RDBs you would create a table storing IDUserA/IDUserB for a representation of a friendship.

If we assume a bunch of IT-Girls for example with the Facebook limit of 5k friends, we quickly get to huge amounts of data. If GirlA(ID 1) simply likes GirlB(ID 2). It would be an entry wir [1][2] in the table.
With this model it is not possible to get over data redundancy in friendship, because then we have to do either two queries (is there an entry in IDUserA or an entry in IDUserB with ID = 1, what means physically searching both columns) or to store [1][2] and [2][1], what ends up in data redundancy. For a heavy user this means checks against 5000/10000 entries containing an indexed column, which is astronomically big.

So ok, use GraphDBs. We assume the Girls as Nodes. GirlA is the first one ever entered into the DB, so her ID is simply 0. The Entry contains a isUsed - flag for the data chunk of a byte, and is 1 if it is in use. The next 4 bytes are a flag for the filename where her node is stored in (what leads to nearly 4.3 Billion possible files and we assume the file size of 16.7MB so we could use 3 more bytes to declare the offset inside.

Lets assume we define the username datatype as a chunk of 256 (and be for the example so ridgid).
For GirlA it is [1]0.0.0.0-0.0.0
= Her User ID 0 times 256 = 0
For GirlB it is [1]0.0.0.0-0.1.0
= Her User ID 1 times 256 = 256,

so her Usernamedata starts on file 0_0_0_0.dat on offset 256 from start. We don't have to search for her data, we could simply calculate them. A User 100 would be stored in the same file on offset 25600 and so forth and so on. User 65537 would be stored in file 0_0_0_1.dat on offset 0. Loaded in RAM this is only a pointer and pretty fast.
So we could store with this method more nodes than humans ever lived.
BUT: How to find relationships? Ok, with edges. But how to store them? All in one "column" is stupid, because then we are back on relationship models. In a hashtable? Ok, we could store the 0_0_0_0.frds as a hashtable containing all friends of User0, kick off a new instance of a User-Class Object, add the Friends to a binary list or tree that could be found by the pointer cUser.pFriendlist and we would be done. But I think that I make a mistake.
Shouldn't GraphDatabases be something different than mathematical nodes connected with hash tables filled with edges?
The use of nodes and edges is clear, because it allows to connect everything with relationships of anything. But whats about the queries and their speed?

Keeping different edges in different type of files seems somekind of wrong, even if the accessibility is really fast on SSDs.
Sure, I could use a simple relational table to store a edgetype/dataending pair, but please help me: where do I get it wrong!


text:
Q: HtmlAgilityPack c# taking several images and links Please help-me with this question:
private void DownLoadCompleted(object sender, HtmlDocumentLoadCompleted e)
{
    var doc = new HtmlDocument();
    doc.LoadHtml("http://www.unnu.com/popular-music-videos");
    //var query = doc.DocumentNode.Descendants("img");
    MessageBox.Show("chegou");
    foreach (HtmlNode linkNode in doc.DocumentNode.SelectNodes("@//img[@src]"))
    {
        HtmlAttribute link = linkNode.Attributes[@"href"];
        HtmlNode imageNode = linkNode.SelectSingleNode(@"//.php?src");
        HtmlAttribute src = imageNode.Attributes[@"src"];

        string Link = link.Value;
        Uri imageUrl = new Uri(src.Value);
        MessageBox.Show("chegou");
    }
}

I need to get the all images and titles with your respective urls. I'm Using windows phone 7.5. The dll is the same.

A: doc.LoadHtml expects html, not the url. Are you looking for something like this?
var web = new HtmlAgilityPack.HtmlWeb();
var doc = web.Load("http://www.unnu.com/popular-music-videos");

var imgs = doc.DocumentNode.SelectNodes(@"//img[@src]")
            .Select(img => new
            {
                Link = img.Attributes["src"].Value,
                Title = img.Attributes["alt"].Value
            })
            .ToList();

If HtmlAgilityPack's WP7 version doesn't support HtmlWeb you can also use WebClient to get the html string and it can be used as parameter to doc.LoadHtml


text:
Q: How to change the width and height of ZoomRect from the user side? g.DrawRectangle(pen, x , y, width + 30, height +30);
Shows the effect if you change this bold text in the bold place given below. which is statically done in the EvfPictuerBox.CS file.
int cx = iWidth;
int cy = iHeight;
int iw = evfDataSet.sizeJpegLarge.width;
int ih = evfDataSet.sizeJpegLarge.height;
long left = evfDataSet.zoomRect.x;
long top = evfDataSet.zoomRect.y;
long x = left * cx / iw;
long y = top * cy / ih;
long width = evfDataSet.zoomRect.width * cx / iw;
long height = evfDataSet.zoomRect.height * cy / ih;
// Draw.
Pen pen = new Pen(Color.FromArgb(255, 255, 255));
pen.Width = 3; g.DrawRectangle(pen, x , y,width, height);
How to change the width and height of ZoomRect from the user side?
So why make this change dynamically.
The click of the button that has to be plused is to be made from the event.
How to change the width and height of ZoomRect from the user side


text:
Q: Laravel Homestead and Access Denied I thought this would be easy but apparently it is not, at least for me. After following the documentation (or thinking I have) I have created a homstead vagrant box following the instructions for such and now have a homestead app where I can do:
app-response.tracking:8080

But I get:
Forbidden

You don't have permission to access /public on this server.

Apache/2.4.7 (Ubuntu) Server at app-response.tracking Port 8080

When do vagrant ssh and go look at app-response-tracking/public:
drwxr-xr-x 1 vagrant vagrant  204 Sep  3 16:59 public

So then I think ok maybe its the .htaccess file like laravel suggests it might be.
So first I try and throw a five hundred and I throw in some garbage I replace everything in the .htaccess file with sjdfhgs reload and expect to see my broken 500, nope still the same error.
So then I replace the content back to what they were knowing this wont change a thing.
My Homestead.yml looks like, which on my mac is stored at ~/.homestead/Homestead.yml
$ cat ~/.homestead/Homestead.yaml
---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Documents/laravel-projects/app-response-tracking
      to: /home/vagrant/app-response-tracking

sites:
    - map: app-response.tracking
      to: /home/vagrant/app-tesponse-tracking/public

databases:
    - app_response_tracking

variables:
    - key: APP_ENV
      value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 93000
#       to: 9300
#     - send: 7777
#       to: 777
#       protocol: udp

I access the site via app-response.tracking:8080 Even doing app-response.tracking:8080/public fails. I still get the same error.
On vagrant, when I do la -lah I see:
$ ls -lah
total 156K
drwxr-xr-x 1 vagrant vagrant  816 Sep  3 16:52 .
drwxr-xr-x 6 vagrant vagrant 4.0K Sep  3 16:59 ..
drwxr-xr-x 1 vagrant vagrant  374 Sep  3 16:50 app
-rw-r--r-- 1 vagrant vagrant 1.7K Sep  3 16:50 artisan
drwxr-xr-x 1 vagrant vagrant  170 Sep  3 16:50 bootstrap
-rw-r--r-- 1 vagrant vagrant 1.2K Sep  3 16:50 composer.json
-rw-r--r-- 1 vagrant vagrant 103K Sep  3 16:52 composer.lock
drwxr-xr-x 1 vagrant vagrant  476 Sep  3 16:50 config
drwxr-xr-x 1 vagrant vagrant  204 Sep  3 16:50 database
-rw-r--r-- 1 vagrant vagrant  323 Sep  3 16:53 .env
-rw-r--r-- 1 vagrant vagrant  307 Sep  3 16:50 .env.example
-rw-r--r-- 1 vagrant vagrant   61 Sep  3 16:50 .gitattributes
-rw-r--r-- 1 vagrant vagrant   57 Sep  3 16:50 .gitignore
-rw-r--r-- 1 vagrant vagrant  503 Sep  3 16:50 gulpfile.js
-rw-r--r-- 1 vagrant vagrant  159 Sep  3 16:50 package.json
-rw-r--r-- 1 vagrant vagrant   87 Sep  3 16:50 phpspec.yml
-rw-r--r-- 1 vagrant vagrant  899 Sep  3 16:50 phpunit.xml
drwxr-xr-x 1 vagrant vagrant  204 Sep  3 16:59 public
-rw-r--r-- 1 vagrant vagrant 1.9K Sep  3 16:50 readme.md
drwxr-xr-x 1 vagrant vagrant  170 Sep  3 16:50 resources
-rw-r--r-- 1 vagrant vagrant  567 Sep  3 16:50 server.php
drwxr-xr-x 1 vagrant vagrant  170 Sep  3 16:50 storage
drwxr-xr-x 1 vagrant vagrant  136 Sep  3 16:50 tests
drwxr-xr-x 1 vagrant vagrant  986 Sep  3 16:53 vendor

What is going on?

A: Try to create a virtual host in /etc/hosts just add the next line at the end of the file
192.168.10.10   app-response.tracking

Next try to visit that site on your browser without the port, this will take you to your project's directory
http://app-response.tracking/
I you don't want to create a virtual host you should only type localhost:8000 on your browser or 127.0.0.1:8000


text:
Q: Is this a normal load for Apache? Load average: 0.05 0.13 0.15
Uptime: 28 days
Not sure what those mean or if there is a script that will help me figure that out.

A: Quote:
In short it is the average sum of the number of processes waiting in the run-queue plus the number currently executing over 1, 5, and 15 minute time periods
So the number of actual running processes -- plus the number of "ready to run" processes i.e. active programs which are not waiting for IO or timers or are otherwise blocked.
So you have a four processor machine and you load average is 3.5 then nothing is waiting. On the other hand if the load average was 5.2 there would be one process waiting for resources at any given time. If you get up to 8 or 9 on the third number (15 minute average) then you have  a problem!

A: That looks pretty low to me (that's good).  Here's what Wikipedia has to say:
"For single-CPU systems that are CPU-bound, one can think of load average as a percentage of system utilization during the respective time period. For systems with multiple CPUs, one must divide the number by the number of processors in order to get a comparable percentage."
So, if you have a single-core system, thats 5% (last minute) 13% (5 minute) and 15% (15 minute).
(from http://en.wikipedia.org/wiki/Load_(computing))


text:
Q: Akka Persistence: java.sql.SQLSyntaxErrorException: ORA-04043: object "SOME_SCHEMA" does not exist I am trying to use Akka Persistence JDBC ("com.lightbend.akka" %% "akka-persistence-jdbc" % "5.0.1") with Oracle and have created the schema and tables as mentioned at oracle-create-schema.sql. In my akka-persistence-jdbc.conf I have added the overriddes as mentioned in oracle-schema-overrides.conf.
But when I run the Akka app I am getting error while trying to persist the events.
java.sql.SQLSyntaxErrorException: ORA-04043: object "SOME_SCHEMA" does not exist

I have tried the query that gets printed in the logs and it works fine in SQL Developer.
[DEBUG] 2021-07-23 14:57:17.684+0000 [sample-akka.actor.default-dispatcher-12] s.b.B.action - #1: StartTransaction
[DEBUG] 2021-07-23 14:57:17.685+0000 [slick.db-5] s.b.B.action - #2: MultiInsertAction [insert into "SOME_SCHEMA"."EVENT_JOURNAL" ("DELETED","PERSISTENCE_ID","SEQUENCE_NUMBER","WRITER","WRITE_TIMESTAMP","ADAPTER_MANIFEST","EVENT_PAYLOAD","EVENT_SER_ID","EVENT_SER_MANIFEST","META_PAYLOAD","META_SER_ID","META_SER_MANIFEST")  values (?,?,?,?,?,?,?,?,?,?,?,?)]
[DEBUG] 2021-07-23 14:57:17.685+0000 [slick.db-5] s.j.J.statement - Preparing insert statement (returning: ORDERING): insert into "SOME_SCHEMA"."EVENT_JOURNAL" ("DELETED","PERSISTENCE_ID","SEQUENCE_NUMBER","WRITER","WRITE_TIMESTAMP","ADAPTER_MANIFEST","EVENT_PAYLOAD","EVENT_SER_ID","EVENT_SER_MANIFEST","META_PAYLOAD","META_SER_ID","META_SER_MANIFEST")  values (?,?,?,?,?,?,?,?,?,?,?,?)
[DEBUG] 2021-07-23 14:57:17.687+0000 [sample-akka.persistence.dispatchers.default-plugin-dispatcher-134] s.b.B.action - #3: Rollback

Also, the read queries before this seems to be working fine.
My akka-persistence-jdbc.conf looks like:
akka {
    persistence {
        journal {
            plugin = "jdbc-journal"
            // Enable the line below to automatically start the journal when the actorsystem is started
            // auto-start-journals = ["jdbc-journal"]
        }
        snapshot-store {
            plugin = "jdbc-snapshot-store"
            // Enable the line below to automatically start the snapshot-store when the actorsystem is started
            // auto-start-snapshot-stores = ["jdbc-snapshot-store"]
        }
    }
}

jdbc-journal {
    tables {
        event_journal {
            tableName = "EVENT_JOURNAL"
            schemaName = ${ORACLE_SCHEMA}
            columnNames {
                ordering = "ORDERING"
                deleted = "DELETED"
                persistenceId = "PERSISTENCE_ID"
                sequenceNumber = "SEQUENCE_NUMBER"
                writer = "WRITER"
                writeTimestamp = "WRITE_TIMESTAMP"
                adapterManifest = "ADAPTER_MANIFEST"
                eventPayload = "EVENT_PAYLOAD"
                eventSerId = "EVENT_SER_ID"
                eventSerManifest = "EVENT_SER_MANIFEST"
                metaPayload = "META_PAYLOAD"
                metaSerId = "META_SER_ID"
                metaSerManifest = "META_SER_MANIFEST"
            }
        }
        event_tag {
            tableName = "EVENT_TAG"
            schemaName = ${ORACLE_SCHEMA}

            columnNames {
                eventId = "EVENT_ID"
                tag = "TAG"
            }
        }
    }

    slick = ${slick}
}

# the akka-persistence-snapshot-store in use
jdbc-snapshot-store {
    tables {
        snapshot {
            tableName = "SNAPSHOT"
            schemaName = ${ORACLE_SCHEMA}
            columnNames {
                persistenceId = "PERSISTENCE_ID"
                sequenceNumber = "SEQUENCE_NUMBER"
                created = "CREATED"

                snapshotPayload = "SNAPSHOT_PAYLOAD"
                snapshotSerId = "SNAPSHOT_SER_ID"
                snapshotSerManifest = "SNAPSHOT_SER_MANIFEST"

                metaPayload = "META_PAYLOAD"
                metaSerId = "META_SER_ID"
                metaSerManifest = "META_SER_MANIFEST"
            }
        }
    }
    slick = ${slick}
}

# the akka-persistence-query provider in use
jdbc-read-journal {
    tables {
        event_journal {
            tableName = "EVENT_JOURNAL"
            schemaName = ${ORACLE_SCHEMA}
        }
    }
    slick = ${slick}
}

slick {
    profile = "slick.jdbc.OracleProfile$"
    db {
        host = ${ORACLE_HOST}
        url = ${?ORACLE_URL}
        user = ${ORACLE_USER}
        password = ${ORACLE_PASSWORD}
        driver = "oracle.jdbc.OracleDriver"
        numThreads = 5
        maxConnections = 5
        minConnections = 1
    }
}

Looking for some help here. Thank you so much.
Regards

A: It worked fine when I changed the schemaName to "", but I am not sure if this should be the expected behaviour.
akka {
    persistence {
        journal {
            plugin = "jdbc-journal"
            // Enable the line below to automatically start the journal when the actorsystem is started
            // auto-start-journals = ["jdbc-journal"]
        }
        snapshot-store {
            plugin = "jdbc-snapshot-store"
            // Enable the line below to automatically start the snapshot-store when the actorsystem is started
            // auto-start-snapshot-stores = ["jdbc-snapshot-store"]
        }
    }
}

jdbc-journal {
    tables {
        event_journal {
            tableName = "EVENT_JOURNAL"
            schemaName = ""
            columnNames {
                ordering = "ORDERING"
                deleted = "DELETED"
                persistenceId = "PERSISTENCE_ID"
                sequenceNumber = "SEQUENCE_NUMBER"
                writer = "WRITER"
                writeTimestamp = "WRITE_TIMESTAMP"
                adapterManifest = "ADAPTER_MANIFEST"
                eventPayload = "EVENT_PAYLOAD"
                eventSerId = "EVENT_SER_ID"
                eventSerManifest = "EVENT_SER_MANIFEST"
                metaPayload = "META_PAYLOAD"
                metaSerId = "META_SER_ID"
                metaSerManifest = "META_SER_MANIFEST"
            }
        }
        event_tag {
            tableName = "EVENT_TAG"
            schemaName = ""

            columnNames {
                eventId = "EVENT_ID"
                tag = "TAG"
            }
        }
    }

    slick = ${slick}
}

# the akka-persistence-snapshot-store in use
jdbc-snapshot-store {
    tables {
        snapshot {
            tableName = "SNAPSHOT"
            schemaName = ""
            columnNames {
                persistenceId = "PERSISTENCE_ID"
                sequenceNumber = "SEQUENCE_NUMBER"
                created = "CREATED"

                snapshotPayload = "SNAPSHOT_PAYLOAD"
                snapshotSerId = "SNAPSHOT_SER_ID"
                snapshotSerManifest = "SNAPSHOT_SER_MANIFEST"

                metaPayload = "META_PAYLOAD"
                metaSerId = "META_SER_ID"
                metaSerManifest = "META_SER_MANIFEST"
            }
        }
    }
    slick = ${slick}
}

# the akka-persistence-query provider in use
jdbc-read-journal {
    tables {
        event_journal {
            tableName = "EVENT_JOURNAL"
            schemaName = ""
        }
    }
    slick = ${slick}
}

slick {
    profile = "slick.jdbc.OracleProfile$"
    db {
        host = ${ORACLE_HOST}
        url = ${?ORACLE_URL}
        user = ${ORACLE_USER}
        password = ${ORACLE_PASSWORD}
        driver = "oracle.jdbc.OracleDriver"
        numThreads = 5
        maxConnections = 5
        minConnections = 1
    }
}


text:
Q: Ambiguity issue with Vb.Net and MySql Connector I'm running into a weird issue with a VB.Net project using the MySql ADO.Net connector. I have the following code:
Dim param As New MySqlParameter("@val29", MySqlDbType.DateTime)

And I'm getting the following error message:
Ambiguous invocation:
  Public Enum member Datetime As MySqlDbType (in Enum MySqlDbType)
  Public Enum member DateTime As MySqlDbType (in Enum MySqlDbType)
match

The difference between them, if you notice, is that DateTime is in a different case then Datetime. Since this is VB.Net and VB is case-insensitive, I'm not sure why I'm getting this error.
Interestingly enough, I opened Object Browser in Visual Studio 2013 and, as you can see from the image below, there does seem to be two definitions of DateTime:

.
Thinking maybe there was an issue with the DLL, I went to their website and downloaded the source code and rolled my own DLL. Same issue. I couldn't seem to find anything on the Internet about it, except for this page, which describes my issue exactly, except it seems to be due to a specific bug in Visual Studio 2015. I'm using Visual Studio 2013. That almost makes me think a Windows Update came along that changed the way the VB.Net compiler works. That doesn't make any sense though because updates are specific to Windows, not Visual Studio. Anyone have any ideas?


text:
Q: How create a @objc representable type in swift? I am having hard to find how I can create a custom Type can use inside @objc.
enum defined in Objc > Declared in Swift > to be used in Objc
Above looks similar, but I still cannot understand.
For example.
import Foundation ;

typealias T = ()-> Void ;

@objc
protocol A {

     var t : [ String : T ] { get set } ;

}

Property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C

How can I get rid of this error? Do I have to define something in Objective-C? How can I do it? Will be very appreciate if you can give me am example.

The problem look like if you place a custom type inside Dictionary or Array, this error will appear, how can I resolve it?


text:
Q: Can I burn a piece of wood by emitting only one photon per second on it? Can I burn a piece of wood by emitting single photons on it? (for example by emitting only one photon per second or per milisecond etc to the wood). How much should be the rate of emitting single photons? How long does it take for wood to catch fire in this way? Are the energy of photons important in this process?

A: The short answer is no.  The energy of a photon is $$E=hf$$ where $h$ is Plancks constant and $f$ is frequency.
For visible light $E= 10^{-34}10^{15}$ about $10^{-19}J$.
This doesn't seem high enough to set fire to wood, as the heat energy generated would easily be conducted away before it could build up to a value high enough to cause a fire.

A: Define "burn". If you mean "set on fire", the answer in general is an obvious "no". Remember that even in space, far away from any stars, there is a constant barrage of ubiquitous background radiation. In order to provide an environment where only "single photons" (your "one per second") hit the wood, you need to shield it from the background radiation, radio, cosmic rays etc. with a thick-walled container that itself is cooled down close to 0K in order to avoid black body radiation. I can assure you that wood in near absolute darkness at ~0K would not spontaneously ignite.
If you instead mean "oxidize" the answer is probably "yes". Above a certain frequency threshold photons will create oxygen radicals which are very reactive and will oxidize the carbon and hydrogen molecules making up most of the wood.  A gram of wood contains something like $10^{22}$ or so atoms; if you oxidize one of them every second you will need about $10^{14}$ years to oxidize the wood. If you speed up the process by a factor thousand you only need $10^{11}$ years, which may or may not constitute progress, depending on the observer. If that is any consolation: Versus the end of the experiment you'll not need the lead chamber any longer because you'll be alone with a very dark sky.

A: No. To set fire to a piece of wood you must deliver heat energy to it at a faster rate than it will dissipate. With visible light, the energy of a single photon arriving per second is negligible.
There is an interesting article on Wikipedia https://en.wikipedia.org/wiki/Ultra-high-energy_gamma_ray which illustrates the energy of extremely high frequency gamma ray photons. In theory it is possible for an individual gamma ray to have more energy than a burning match, say, but there are two practical difficulties that would prevent you from igniting wood that way- firstly there is no way to create such high energy photons at present, and secondly they would tend to pass straight through your stick without interacting with it.

A: If you could make sure your system, which includes some oxygen, is perfectly heat insulated from anything else (which includes your emitter or you are somehow able to emit the photon while maintaining the heat insulation), then over a loooooong time your system would heat up enough.

A: Yes. As others have correctly explained, you need to deliver enough energy per photon to ignite the wood. @charles-tucker-3 calculated that an ultra-high energy gamma ray with about 500 Joule would do the trick, which is incredibly high for a single photon energy.
Others argued that the photon will not interact with the wood, this is wrong. While wood is fairly transparent to X-rays, every material is opaque for ultra-high energy gamma rays. Even "empty" space itself is opaque to such gamma rays which react with photons from the cosmic microwave background.
Even if the probability of interacting was small, the probability is not zero. The question was whether it is possible to ignite wood with a flux of 1 photon/second at all. Taken literally, it means we have infinitely many trials (there is no time-limit on the flux). We can just wait until the interaction happens.
Others argued that the photon will do inverse Compton scattering and that the electron will escape the wood without delivering energy. That is unlikely. For such high energy photons, the most likely interaction is e+e- pair production. The electron-positron pair has a chance to escape the wood, but it also has a chance to interact again inside the material. The energy loss per unit length of such high-energetic particles is extremely high, so for sure energy will be dumped into the wood. Even if it is just a small fraction of the energy of the original photon, we can simply increase the energy of the photon a bit more in our gedankenexperiment to compensate for the losses.
In some cases a local bubble of high-energy plasma would be formed by the interaction. The plasma gets absorbed by the surrounding matter which is heated in turn. If this bubble is close enough to the surface so that the heated material has a chance to combust in contact with air, then yes you could ignite the piece of wood with a photon flux of 1 Hz.

A: Let's try to calculate that:
The heat capacity of wood is (Wikipedia): $C=1700 \frac{J}{kg K}$ and the temperature at which wood starts to burn is approx $300^\circ C$. Assuming that the wood has approx $0^\circ C$ (it's winter...) we need to heat it by $\Delta T = 300 K$.
An assumption is needed for the mass of the wood we want to burn, let's assume a very small piece of wood of only $m=0.001$ kg.
The energy $Q$ needed to heat this piece of wood is: $Q = C \cdot m \cdot \Delta T = 510$ J $= 3.2 \cdot 10^{21}$ eV. That is massive, a Photon in the visible spectral range has only about 3 eV.
Anyways, the corresponding wavelength of a photon of that energy is $\lambda = \frac{h \cdot c}{Q} = 3.88 \cdot 10^{-28}$ m $= 3.88 \cdot 10^{-19}$ nm.
Thats really ultra short, much much shorter than X-rays or gamma rays, but still larger than the Planck length, so could exist in theory.
However, that's the mathematical answer. In the real world the energy of the photon would not 1:1 go into heat because in the first place the photon would produce a free electron of large energy that would in a cascade produce other electrons and ions and most of them would just escape from the piece of wood taking their energy with them.

A: Sure, emit them while traveling toward the piece of wood at high velocity and they'll bunch up enough to make fire in any size of timber


text:
Q: wpf get screen position of selected item in listview In the mouseup event for a listview, how do I get the screen position of a selected item?  I can get the screen position of the listview itself (.pointtoscreen) but can't find a way to determine the screen position of a selected item.
I've reviewed other SO articles but didn't find anything specific to items in the listview.

A: You can handle the ListBox.SelectionChanged event (or Selector.Selected). Then get the container of the selected item to calculate its coordinates:
partial class MainWindow : Window
{
  private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    var listBox = sender as ListBox;
    var selectedItemContainer = listBox.ItemContainerGenerator.ContainerFromItem(listBox.SelectedItem) as UIElement;
    var pointOnSelectedItem = new Point(); // top-left corner

    var pointOnScreen = selectedItemContainer.PointToScreen(pointOnSelectedItem);
    var pointRelativeToWindow = selectedItemContainer.TranslatePoint(pointOnSelectedItem, this);
  }
}


text:
Q: Magento is sending confirmation emails to all email addresses except site admin's My Magento site has been sending order confirmations to all email addresses except for the admin email address of the site. I questioned if a spam filter was the real issue and Magento does not appear to be hitting any errors, but I'm not seeing any kind of exception through Magento. Has anyone else experienced issues with order confirmation emails for orders placed with the admin account for Magento?

A: We bumped into the same problem. I must say it did confuse us for quite a while. Basically, if it works with third party domains, all you need to do is to disable postfix local delivery.
In order to do that, please refer here: https://serverfault.com/questions/137591/postifx-disable-local-delivery
Here's an excerpt from our main.cf file:
myhostname = www.someshop.co.uk (this is obviously not real)
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination =
relayhost = smtp.mailgun.org:25
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

We left mydestination blank to do it. Magic.


text:
Q: Disable Order Tax on specific Line Item I'm using the Square Connect Api V2 and was wondering if it is possible to create an Order, using the Orders/createOrder endpoint, with an Order-level tax, and disable the tax for a specific line item?
As a work-around, I think I can move the Order-level tax to the line-item, but was hoping for the ability to disable tax or to find some other workaround.
Thanks in advance!

A: If you use CreateOrder and pass in a top-level taxes array, then this tax will be applied to all line_items. Simply do not include taxes as part of a line_item and it should work successfully, even if a tax is applied to the item in Dashboard.


text:
Q: How to query for the list of members and their basic profiles, including Teams user IDs? Is there an end-to-end sample provided to query for the list of members and their basic profiles, including Teams user IDs and Azure Active Directory (Azure AD)?
I am following https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/get-teams-context?tabs=json and microsoft graph Postman collection, however it seems too complex for me to understand.
I need to fetch all the userId under for my MS Team

A: The document you are following is indeed used to get the information you need, including Teams user IDs and Azure Active Directory (Azure AD).
I'm not sure where you don't quite understand. But it's strongly suggested to firstly learn about Bot Framework Rest API reference.
You should pay attention to how to get the Base URI (serviceUrl). After that, you could issue a GET request on /conversations/{teamId}/members/, using the value of as the endpoint: serviceUrl.
Like this:
GET https://{serviceUrl}/v3/conversations/{teamId}/members/
Authorization: Bearer {access token}
Content-Type: application/json

For details about how to obtain an access token for your bot, see Authenticate requests from your bot to the Bot Connector service.
Now you have the request endpoint and headers. You could test the Rest API in Postman.

A: The best way to get teams user details is by fetching roster details.
You can also use Graph API for getting members of a team/group. But this API provides basic details of user. like
[
    {
        "@odata.type": "#microsoft.graph.user",
        "id": "xxxxxxx-95ea-xxxxxxxxx",
        "businessPhones": [
            "xxxxxxxxxxxxx"
        ],
        "displayName": "Vivek",
        "givenName": "Vivek",
        "jobTitle": "xxxxxxxx",
        "mail": "xxxxxxxx@microsoft.com",
        "mobilePhone": "xxxxxxxxxxx",
        "officeLocation": "LINCOLN xxxxxxxxx",
        "preferredLanguage": null,
        "surname": "Shah",
        "userPrincipalName": "xxxxxxxx@microsoft.com"
    },
]

A: Below are the commands I used to fetch Team user IDs

*

*Step 1: Request an access token from the Azure AD v2 account login
service

*Step 2: Obtain TenantID

*Step 3: Get User Access Token
https://login.microsoftonline.com/{{TenantID}}/oauth2/v2.0/token

*Step 4: Call My Joined Team, get ID
https://graph.microsoft.com/v1.0/me/joinedTeams

*Step 5: Findchannels of a team
https://graph.microsoft.com/v1.0/teams/{{TeamId}}/channels

*Step 6:
Find all the user profile using following
https://{{serviceUrl}}/v3/conversations/{{channelid}}/members/


text:
Q: Python openpyxl telling me " No such file or directory:" even though python file is in same directory as the excel file, among others Beginner here.
I've tried making new excel files, running the python code while the excel file is open, tried renaming the excel file, but nothing works. I was just following this youtube tutorial: https://www.youtube.com/watch?v=7YS6YDQKFh0&t=14s
from openpyxl import Workbook, load_workbook

workbook = load_workbook("Test2.xlsx")

The error:
Traceback (most recent call last):
  File "c:\Users\Name\Desktop\Python Projects\Excel Manipulation\Excel_Test.py", line 3, in <module>
    workbook = load_workbook("Test2.xlsx")
  File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1239, in __init__
    self.fp = io.open(file, filemode)
**FileNotFoundError: [Errno 2] No such file or directory: 'Test2.xlsx'
PS C:\Users\Name>**

A: I found a solution. Turns out you just need to copy the file location, convert it to raw string, and add \ExcelFile to the end:
from openpyxl import Workbook, load_workbook
location = r'C:\Users\Name\Desktop\Python Projects\Excel Manipulation\Test2.xlsx'
workbook = load_workbook(location)

Derp.


text:
Q: Is it okay to put game logic in a draw function? I am making a game, and I have finally finished the gameplay aspect of it, but now it's time for me to create a menu and a high scores screen.  I'm not entirely sure how to do it, the game will be in a different state (MENU_STATE, GAMEPLAY_STATE, SCORESCREEN_STATE) and in each state I want to draw different things to the screen, is it okay for me to do something like this then?
draw function()
{
    if MENU_STATE
        draw menu
    if GAMEPLAY_STATE
        draw game
    if SCORESCREEN_STATE
        draw scores
}

I've been following a strictly no logic in the draw function and it's been good so far, but I really can't figure out a different way to do this.

A: You could use separate classes for the three states, implementing a common interface, and rather than setting a constant for state, set an instance of one of the classes:
interface IState {
    void draw();
}

class Menu implements IState {
    void draw() {
        // Draw menu
    }
}

class Game implements IState {
    void draw() {
        // Draw game
    }
}

void draw() {
    state.draw();
}

This still isn't ideal (you don't really want drawing code in your state, you want something a bit more separate), but the abstraction is a common one and could be relevant (and it's hard to advise further without knowing more of your architecture).

A: You are calling some drawing functions in that routine but that doesn't mean
you have to name it draw.
Perhaps this is more appropriate in your case:
// pseudocode
on_game_state function(state)
{
    select (state):
      MENU_STATE:
        draw menu
      GAMEPLAY_STATE:
        draw game
      SCORESCREEN_STATE:
        draw scores
}

A: Using a statemachine would make this simpler. Each state will have its own set of update and draw functions that are called when it is on top of the state stack. Instead of having one draw function with internal state switches you would have Game_Draw(), Menu_Draw(), HighScoreScreen_Draw() etc. Similarly your update functions could be separated out.
static void StateMachine_DrawTopState()
{
   switch(stateMachine_topState)
   {
       case STATE_GAMEPLAY:
       {
           Gameplay_Draw();
       }
       break;
       case STATE_MENU:
       {
           Menu_Draw();
       }
       break;
   }
}

A: Similar to Andrew Aylett's answer and assuming an object-oriented language, perhaps you could do something like:
Interface IState {
    void init();
    void update();
    void draw();
}

class GameplayScene implements IState {
    void init() {
        // initialize gameplay
    }
    void update() {
        // update game logic
    }
    void draw() {
        // draw game
    }
}

class MenuScene implements IState {
    void init() {
        // initialize menu
    }
    void update() {
        // update menu logic
    }
    void draw() {
        // draw menu
    }
}

class ScoresScene etc...

class TitleScene etc...

// Somewhere else, probably in the Game class
void Main() {
    // Init game
    Scene currentScene = new TitleScene;
    while (Scene != null) {
        Scene.init();
        Scene.update();
        Scene.draw();
    }
    // Exit game
}

You would also need to think about how to handle transition between scenes. You could have each scene class have a member variable called something like nextScene and the main function queries it at the start of the loop to switch to the proper scene.
If you don't have the luxury of using an object-oriented programming language (like C++, Java, C#, Python, etc.), both Colin's and Nick D's answers might help, although I'd try to have the switch statement in one place (say one big game_update function) to allow adding new states by making a change in one place. Alternatively, you could build on the Colin's state machine design to make something more generic and that doesn't explicitly require a hard-coded switch statement. (although to be honest I can't think of a good way to do it at the moment)

A: It is absolutely not ok to put game logic in a draw function.
However, if it makes your life easier in this specific case, it's ok anyway.
You can always change it later if it becomes a mess.

A: Yes it's fine, game programmers are allowed to bend the rules for performance gains. The view and the model of a game world are quite often one and the same thing to avoid latency created by decoupling the view and the model.
There's no reason why you can't make the menu and highscores objects part of your game world, it's been done before in quite a few games.


text:
Q: C linked list define how to reimplement a list Hi this is probably a stupid question to ask with a simple solution but I just can't find an answer in the internet.
So I was exercising for an exam and worked on an assignment. The program has the job to find out what the value in the center of a linked list is (if the length of the list is an odd number)
The structdef is:
typedef struct IntList IntList;
struct IntList {
    int value;
    IntList* next;
};

and my exact problem right now is that I get a segmentation fault when I try using:
list = list->next;

I want to go step by step in a loop to go to the wished list at the nth position (the center) of the linked list.
Someone knows how I have to rewrite this? If you need more Information to help just say so and I will explain more.
With that function I check the length of the list and in my other function I have a loop which only goes to the mid of the length.
int length_list(IntList* list) {
    int n = 0;
    for(IntList* node = list; node != NULL; node = node->next) n++;
    return n;
}

A: After this loop ends for(IntList* node = list; node != NULL; node = node->next) n++; you surely have node==NULL.
That is not immediatly a problem.
But depending on what you do with the value of n which you return you might have an off-by-one problem. E.g. in a list with exactly one entry (1 is odd after all), the attempt to use a value which is 1 too high could result in an attempt to access a non-existing node.
Because of this I suspect that your problem might be solved by changing the loop to
for(IntList* node = list; node->next != NULL; node = node->next) n++;, so that it ends on the last existing node, instead of behind. The return value will be lower, whatever you do with it will be "more-careful".
That or try something similar with the small code fragment you show and ask about, list = list->next; only do that if the next is not NULL, not if only list is not NULL.