Tag Archives: class

About the problem of calling tools library by running Python program under Mac OS X, modulenotfoundererror: no module named ‘tools‘

ModuleNotFoundError: No module named ‘Tools’

For example, import the tools library into pcharm of MAC

from Tools.scripts.abitype import classify
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from sklearn import datasets
from minisom import MiniSom

The first line will report error!!!

It seems that it is very difficult to change the tools variable in MAC environment. The solutions are as follows

Direct import classify

import classify

The test is effective ~

Error: the main class usertest could not be found or loaded

This class has a specified package

An error occurred when running java test from the command line: the main class usertest could not be found or loaded

    first of all, the user test needs to compile
    the command, such as the folder where the user test.java is located, executes javac user test.java to compile. After compiling, the user test.class file appears in the directory where the user test.java is located, and then it can be run on the command line<

    runs the usertest.class file through the Java command
    first, let’s see what the package name written after the package of the class usertest.java is. My name is com.bean

    when I run Java usertest in the bean directory, I report an error: can't find or load the main class usertest

    later, I see that someone says Java com.bean.usertest can run, and it really can run after a try. But Java usertest can’t run. Later, it is found that this class has a specified package

This class does not specify a package

1. Use javac usertest. Java to compile our. Java file

2. If the java file does not specify a package, just use the Java command to run our class file (Java usertest)

Detailed explanation of Python__ new__() method

The new () method mainly exists in the new class of Python 2 and in Python 3. It is the static method responsible for creating class instances.

When Python instantiates an object, it first calls the__ new__() Method to construct an instance of a class and allocate the memory space of the corresponding type for it. The memory address of the instance is its unique identifier. And then call__ init__() Method to initialize an instance, usually the properties of the instance.

Here are some examples to illustrate:

Example 1: call first__ new__() Method call again__ init__() method

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        return super().__new__(cls)
    
    def __init__(self):
        print("__init__ called")
		  
a = Person()
		

result:

__new__ called
__init__ called

Example 2: the new () method constructs a class instance and passes it to its own__ init__() Method, i.e__ init__() The self parameter of the method.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        instance = super().__new__(cls)
        print(type(instance))
        print(instance)
        print(id(instance))
        return instance
    
    def __init__(self):
        print("__init__ called")
        print(id(self))

b = Person()

result:

__new__ called
<class '__main__.Person'>
<__main__.Person object at 0x1093c1580>
4449899904
__init__ called
4449899904

Example 3: if__ new__() Method does not return any instances, the init () method will not be called.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")

    def __init__(self):
        print("__init__ called")

c = Person()

result:

__new__ called

Example 4: if__ new__() Method returns an instance of another class__ init__() Method will not be called. Moreover, the new () method will initialize an object of another class.

class Animal(object):

    def __init__(self):
        pass

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        return Animal()

    def __init__(self):
        print("__init__ called")

d = Person()
print(type(d))
print(d)

result:

__new__ called
<class '__main__.Animal'>
<__main__.Animal object at 0x10fea3550>

Example 5: if overridden__ new__() Method, except for the CLS parameter, if no other parameters are set, it cannot be used__ init__() Method to set initialization parameters.

class Person(object):
    
    def __new__(cls):
        print("__new__ called")
        instance = super().__new__(cls)
        return instance
    
    def __init__(self, name):
        print("__init__ called")
        self.name = name

e = Person("Eric")
print(e.name)

result:

Traceback (most recent call last):
  File "example.py", line 102, in <module>
    e = Person("Eric")
TypeError: __new__() takes 1 positional argument but 2 were given

Example 6: in rewriting__ new__() Method, you need to add * args, * * kwargs to the parameters, or explicitly add the corresponding parameters to pass__ init__() Method initialization parameters.

class Person(object):
    
    def __new__(cls, *args,**kwargs):  # Or def __new__(cls, name)
        print("__new__ called")
        instance = super().__new__(cls)
        return instance
    
    def __init__(self, name):
        print("__init__ called")
        self.name = name

e = Person("Eric")
print(e.name)

result:

__new__ called
__init__ called
Eric

An unable to locate appropriate constructor on class solution appears

Today, when using hibernate operation, the query operation also made this error. I couldn’t figure out the solution. Finally, I found the ending method on the Internet, which should not be regarded as the method. That’s the reason.

First, I use the following HQL statement

String hql="select new PO(。。。。) from 。。。";

This error is largely due to the time format. The reasons are as follows

1. In Oracle, what is the return time of using hibernate query java.util.Date Yes.

2. When using struts1, the time plug-ins in the foreground must be string in the form, otherwise an error will be reported.

3. Use BeanUtils.copyProperties Method, the string time in form can only be converted to java.sql.Date Type.

4. Due to the reason of 3, the time type of Po entity class should be java.sql.Date Type.

5. Oracle return java.util.Date , Po is java.sql.Date So the problem arises.

The current solution is to transform in the construction method, and another method is to implement string to java.util.Date But what I’m doing now is an old project. There was a lot of code before, and it would be troublesome if I made a mistake. So it’s relatively safe to use the construction method to convert.

We have to make complaints about the problems in our project, which are basically caused by the time type related to the database, and the conflict of jar packages in the project.

Python: Understanding__ str__

The following is my understanding if there is anything wrong with me. Please do tell me. Thank you very much!
In The Python language, successie __str__ is usually formatted this way.
class A:

def __str__(self):

return “this is in str”

Literally, ___ is called by the print function, usually return something. This thing should be in the form of a string. If you don’t want to use the STR () function. If you print a class, print first calls each ___ by str__, such as STR. Py

#!/usr/bin/env python
                                                                                                                                                                                 
class strtest:
    def __init__(self):
        print "init: this is only test"
    def __str__(self):
        return "str: this is only test"

if __name__ == "__main__":
    st=strtest()
    print st

$./str.pyinit: this is only test

str: this is only test
As you can see from the above example, the function with ___ is called when you print an instance of STRtest st.
By default, the python objects almost always have the __str__ function used by print. S the dictionary with ___, see the red part:
> > > dir({})
[‘__class__’, ‘__cmp__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘has_key’, ‘items’, ‘iteritems’, ‘iterkeys’, ‘itervalues’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’]
> > > t={}
> > > t[‘1’] = “hello”
> > > t[‘2’] = “world”

> > > t
# is equal to print t

{‘1’: ‘hello’, ‘2’: ‘world’}

> > > t.__str__()

“{‘1’: ‘hello’, ‘2’: ‘world’}”

You can see a dictionary, print t and t. str__() are the same. Simply output the contents of the dictionary as a string.
If it’s not a string returned in the function ___, see str1.py

#!/us/bin/env/python                                                                                                                                                                                        
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
    def __init__(self):
        self.val = 1
    def __str__(self):
        return self.val

if __name__ == "__main__":
    st=strtest()
    print st

$./str1.py

Traceback (most recent call last):
File “./ STR. Py “, line 12, in < module>
print st
TypeError: ___, returned non-string (type int)
Error message with: ___ returned a non-string. Here’s what we should do: see str2. Py

#!/usr/bin/env python                                                                                                                                                                                        
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
    def __init__(self):
        self.val = 1
    def __str__(self):
        return str(self.val)

if __name__ == "__main__":
    st=strtest()
    print st

$./str2.py

1
We used STR () to change the integer to a character.

Copy forbidden in C + +++

A common way to disallow copying classes is to define copy constructors and assignment functions as private functions, as shown in effective c++ :
Real estate agents sell houses, and software systems that serve such agents naturally have a class to represent the houses being sold:
class HomeForSale { … };
Every real estate agent is quick to point out that every property is unique — no two are exactly alike. In this case, the idea of making a copy for a HomeForSale Object is puzzling. How can you copy something unique?So it’s best to make things like this attempt to copy a HomeForSale Object non-compilable:
HomeForSale h1;
HomeForSale h2;
HomeForSale h3(h1);// attempt to copy the h1 – should
// not compile!
h1 = h2;// attempt to copy the h2 – should
// not compile!
Alas, the way to prevent this kind of compilation is not that straightforward. In general, if you don’t want a class to support some kind of functionality, you can simply not declare the function that gives it that functionality. This strategy does not work for copy constructor (copy constructor) or copy assignment operator (copy assignment operator) because, as indicated in Item 5, if you do not declare them and someone wants to call them, the compiler will declare them for you.
That limits you. If you do not declare copy constructor or copy assignment operator, the compiler can also generate them for you. Your class will also support copying. On the other hand, if you declare these functions, your classes will still support copying. During this period, our aim is to prevent copying!
The key to solving this problem is that all compiler generated functions are public. To prevent these functions from being generated, you have to declare them yourself, but you have no reason to declare them public. Instead, declare the copy constructor (copy constructor) and the copy assignment operator (copy assignment operator) private. By explicitly declaring a member function, you prevent the compiler from generating its own version, and by declaring the function private, you prevent others from calling it.
In general, this option is not very safe, as the member and friend functions can still call your private functions. In other words, unless you’re smart enough not to define them. So, when someone accidentally calls them, there will be an error at link-time. This technique – declaring member functions private yet deliberately failing to implement it – is indeed very good. In the iostreams library of C++, there are several classes using this method to prevent copying. For example, if you look at the definitions (definitions) of ios_base, basic_ios, and Sentry in your standard library implementation, you will see that the copy constructor (copy constructor) and the copy assignment operator (copy assignment operator) are declared private and are not defined.
To apply this trick to HomeForSale, it’s simple:
The class HomeForSale {
public:

Private:

HomeForSale (const HomeForSale&) ;// declarations only
HomeForSale& operator=(const HomeForSale&) ;
};
You’ll notice That I omitted the name functions’ parameters. It’s not necessary, it’s just a common practice. After all, functions are not implemented and are less likely to be used, so why specify parameter names?
For the above class Definition, the compiler will prevent a client from attempting to copy HomeForSale Objects, and if you accidentally do so in a Member or friend function, the linker will protest.
Will link – time error (connection) in advance to compile time is feasible after all, the discovery of the error (early than late found good), by not HomeForSale itself declared in the copy constructor (copy constructor) and copy the assignment operator (copy assignment operator) is a private, but in a to prevent copying (prevent copy) and specially designed base class (base class) in a statement. The base class itself is very simple:
Class Uncopyable {
protected:// allow construction
Uncopyable () {}// and destruction of
~ Uncopyable () {}// derived objects…
Private:
Uncopyable (const Uncopyable&) ;//… But prevent copying
Uncopyable& operator=(const Uncopyable&) ;
};
To prevent copying HomeForSale Objects, we must now make it inherit from Uncopyable:
Class HomeForSale: private Uncopyable {// class no longer
…// declares copy ctor or
};// copy the assign. Operator
This is done because if someone — even a member (member) or friend function (friend function) — tries to copy a HomeForSale Objects (object), the compiler will attempt to generate a copy constructor (copy constructor) and a copy assignment operator (copy assignment operator). As explained by Item 12, the compiler-generated versions of these functions attempt to call the corresponding functions of the Base class, and these calls are rejected because the copy operation is private in the Base class.
The implementation and use of Uncopyable contain subtlety. For example, inheritance from Uncopyable need not be public (see Items 32 and 39), and Uncopyable’s destructor need not be virtual (see Item 7). Because Uncopyable does not contain data, it meets the condition of Empty Base Class Optimization described by Item 39, but because it is a base class, multiple inheritance cannot be introduced for application of this technique (see Item 40). On the other hand, Multiple inheritance sometimes defies empty Base Class optimization (see Item 39 again). In general, you can ignore these subtleties and use Uncopyable only as demonstrated here, because it works like an advertisement. You can also use a version available in Boost (see Item 55). That class is called noncopyable. That’s a good thing, I just found that name a little UN – (no…) HMM… Nonnatural.

non-static variable this cannot be referenced from a static context

While practicing Java today, I found an interesting question that may actually be common sense for computer science majors. But I don’t know how many friends like me, or even computer related professional friends noticed this problem.

Idle talk less, get down to business, look at the code first.
Error code 1:

class ConsDemo {

            private static String name;  //declare name attribute
            private static int age; // delcare age attribute

            public static void tell(){
                   System.out.println("name: "+this.name+",age: "+this.age);
             }

 }

The above code will report an error, such as the question.

Why?

First, adjust the code as follows:
 

class ConsDemo {

            private String name;  //declare name attribute
            private int age; // delcare age attribute

            public  void tell(){
                   System.out.println("name: "+this.name+",age: "+this.age);
             }

 }

The above code can be run or rewritten as follows:
Fixed code 2:

 
class ConsDemo {

            private static String name;  //declare name attribute
            private static int age; // delcare age attribute   
            public  static void tell(){
                  System.out.println("name: "+name+",age: "+age);
            }
}

So here’s the conclusion:

If this pointer is removed from the error code 1, the error will become: non-static variable name cannot be referenced from a static context; The static variable name,age, cannot be found in the context.
So the tell method static declaration is removed from code one, while the name is removed from code two, and the static declaration keyword is added to the age property.
Therefore, the following conclusions can be drawn:
You can only use static variables in static methods;
The same:
Class methods can only use class variables.

Run time error “430”

Recently, the use of VB6.0, encountered a lot of trouble problems, is about. DLL problems. After the source program is introduced into the machine, you need to register the.DLL files used. But sometimes there will be some changes so that the files registered in the system cannot adapt to the changed environment, then Runtime Error 430
Class dose not support automation or does not support expected interface will occur. Error message.
Solution: Manually unregister the original.DLL file from the system with Regsvr32/U /s XXx. DLL and re-register it with RegSVr32 /s XXX. DLL.
This version inconsistency often occurs when a program is introduced to a native. The best way is to re-register all the files in the original reference.

When SAP receives the goods, the system prompts that it can only be recorded in the period 2009 / 09 and 2009 / 08 of company code 1101

Error: when receiving goods according to PO, the system prompts can only be accounted for in the period 2009/09 and 2009/08 of Company code 1101. The current date is 2009-10-8.
Answer: this is an old problem, it is the problem of MM opening account,< a target=”_blank” class=”link_tag” href=”http://blog.vsharing.com/Tag/%3Ca%20href=” http:=”” www.vsharing.com=”” sap”=”” style=”line-height: 21px; color: rgb(85, 66, 15); Font: Verdana, Arial, Helvetica, Sans-serif; font: Verdana, Arial, Helvetica; sans-serif; text-decoration: underline; “> SAP”> MM in SAP can only open accounts for 2 months, which should be opened in sequence.
You can use the transaction code: MMRV to check the current accounting period, and then use MMPV to adjust month by month, if the prompt is not the current calendar year, enter can be past.

didFailWithError: Error Domain=kCLErrorDomain Code=0 “The operation couldn’t be completed. (kCLError

I believe that many people have encountered this problem, the Internet is also by a variety of answers which this calculate more comprehensive
The reason for the error is the project — &gt in Xcode; The scheme – & gt; Edit scheme – & gt; The options – & gt; The core location – & gt; Error allowing location simulation;
solutions:

    if it is already set, uncheck it and save it; The simulator – & gt; Reset content and Settings: re-check allow location simulation, then reset content and Settings

Most people should have solved the problem, but I didn’t… And the solution is this

It’s not because I’m in Hong Kong. It’s because there’s only one Chinese in Hong Kong.
will not report an error after it is set. In fact, it is to specify the position of the simulator. I don’t know why the simulator cannot be automatically positioned, so I can test with the real machine

Learn iOS, he is enough, small code brother video, wisdom, dark horse, all kinds of Swift books