R包安装package "methods" in options("defaultPackages") was not found ?

安装R包时出现下面的问题,哪位大神可以指点一二?

> BiocManager::install("KEGG.db",ask = F,update = F)
Bioconductor version 3.9 (BiocManager 1.30.4), R 3.6.1 (2019-07-05)
Installing package(s) 'KEGG.db'
installing the source package ‘KEGG.db’

trying URL 'https://mirrors.ustc.edu.cn/bioc//packages/3.9/data/annotation/src/contrib/KEGG.db_3.2.3.tar.gz'
Content type 'application/gzip' length 1976342 bytes (1.9 MB)
downloaded 1.9 MB

* installing *source* package 'KEGG.db' ...
** using staged installation
** R
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
  converting help for package 'KEGG.db'
    finding HTML links ... 好了
    KEGGBASE                                html  
    KEGGENZYMEID2GO                         html  
    KEGGEXTID2PATHID                        html  
    KEGGGO2ENZYMEID                         html  
    KEGGMAPCOUNTS                           html  
    KEGGPATHID2EXTID                        html  
    KEGGPATHID2NAME                         html  
    KEGGPATHNAME2ID                         html  
    KEGG_dbconn                             html  
** building package indices
** testing if installed package can be loaded from temporary location
*** arch - i386
Warning message:
package "methods" in options("defaultPackages") was not found 
在启动过程中 - Warning messages:
1: package 'utils' in options("defaultPackages") was not found 
2: package 'grDevices' in options("defaultPackages") was not found 
3: package 'graphics' in options("defaultPackages") was not found 
4: package 'stats' in options("defaultPackages") was not found 
5: package 'methods' in options("defaultPackages") was not found 
Error in library.dynam(lib, package, package.lib) : 
  没有这个DLL 'tools':是不是没有为此架构安装?
Calls: ::: ... asNamespace -> getNamespace -> loadNamespace -> library.dynam
停止执行
*** arch - x64
ERROR: loading failed for 'i386'
* removing 'C:/Program Files/R/R-3.6.1/library/KEGG.db'

The downloaded source packages are in
    ‘C:\Users\Administrator.SC-201907281012\AppData\Local\Temp\RtmpiG0vqg\downloaded_packages’
Warning message:
In install.packages(pkgs = doing, lib = lib, repos = repos, ...) :
  installation of package ‘KEGG.db’ had non-zero exit status

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
What will happen if change the "package" property?
what will happen if you change the "package" property in the Manifest.xml of your android project?
R语言安装包总是报错,本地安装也不行。总是提示安装有非0出口
小白一枚,安装bioconductor里面的"org.Hs.eg.db"包,总是不成功。。 ![图片说明](https://img-ask.csdn.net/upload/202002/14/1581651842_314166.jpg) Warning messages: 1: In download.file(url, destfile, method, mode = "wb", ...) : downloaded length 48910336 != reported length 81813830 2: In install.packages(...) : installation of package ‘org.Hs.eg.db’ had non-zero exit status 有没有大神帮忙解答下
The content of element type "package" must match "...
在编写后台登陆模块时,将许多默认的设置放在一个名为default的package <br />里。然后再定义其他package继承该包。之前我的struts.xml配置如下 <br />&lt;struts&gt; <br />&nbsp;&nbsp;&nbsp; &lt;constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" /&gt; <br />&nbsp;&nbsp;&nbsp; &lt;constant name="struts.devMode" value="true" /&gt; <br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; &lt;package name="exam_default" extends="struts-default" namespace="/"&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;!--自定义拦截器及拦截器栈--&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptors&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;!--用户认证拦截器--&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor name="authentication" class="action.admin.AuthenticationInterceptor"/&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;!--用户认证拦截器栈,用于防止用户非法访问--&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor-stack name="user" &gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor-ref name="authentication" /&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor-ref name="defaultStack"/&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/interceptor-stack&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor-stack name="guest" &gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;interceptor-ref name="defaultStack"/&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/interceptor-stack&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/interceptors&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;!--全局异常映射--&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;global-exception-mappings&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;exception-mapping result="error" exception="java.lang.Exception"/&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/global-exception-mappings&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;!--全局result--&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;global-results&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;result name="error"&gt;/error.jsp&lt;/result&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/global-results&gt; <br />&nbsp;&nbsp;&nbsp; &lt;/package&gt; <br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; &lt;package name="admin" extends="exam_default" namespace="/admin"&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;action name="login" class="login"&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;result type="redirectAction"&gt;index&lt;/result&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/action&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;action name="index"&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;result&gt;index.jsp&lt;/result&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/action&gt; <br />&nbsp;&nbsp;&nbsp; &lt;/package&gt; <br />&lt;/struts&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 各位,谁看出来这哪里错了吗??反正最开始我是没看出来。一运行程 <br />序来个错误。 <br />“The content of element type "package" must match "(result-types?,interceptors?,default-interceptor-ref?,default-action-ref?,default-class-ref?,global-results?,global-exception-mappings?,action*)". ” <br />刚看到这个错误我就想,哪个也没写错呀。仔细对了好几遍也没发现哪个属 <br />性写错了。最后Google了一下,看了别人写的文章豁然开朗了。 <br /> <br />&nbsp;&nbsp;&nbsp;&nbsp; 这个错误的意思是,package里元素必须按照一定的顺序排列。这个顺序 <br />就是 <br />result-types <br />interceptors <br />default-interceptor-ref <br />default-action-ref <br />default-class-ref <br />global-results <br />global-exception-mappings <br />action*(就是所有的action放到最后) <br /> <br /><img src="/images/smiles/icon_redface.gif"/>&nbsp;<img src="/images/smiles/icon_eek.gif"/> <br /><strong>问题补充:</strong><br />鄙视javaeye的版主, <br /> <br />六月下雪了。 <br /> <br />我的博客被移到了问答,严重怀疑管理的IQ.
<context:component-scan base-package="x"/> 不起作用
spring的扫描配置 <context:component-scan base-package="cn.xm.*"> 不起作用,扫描不到注解 applicationcontext.xml ``` <context:component-scan base-package="cn.xm.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> ``` springmvc-servlet.xml ``` <context:component-scan base-package="com.xm.controller"/> ``` 发现@controller扫描到了,@service那些没有扫描到 就好像是applicationcontext.xml那个扫描注解的配置没有执行扫描
spring整合使用mybatis的接口,但使用时显示在spring容器内找不到dao的接口对象。
本来已经整合了spring和springmvc,然后我再添加了mybatis的依赖,数据库的配置等等。在test类里mybatis可以单独运作。但是和spring整合的时候就出现问题. 这是我的目录结构 ![图片说明](https://img-ask.csdn.net/upload/202002/11/1581431166_377484.png) 我的dao中的类如下 ``` @Repository public interface IAccountDao { @Select("select * from account") List<Account> findAll(); @Insert("insert into account(name,money) values (#{name},#{money})") void saveAccount(Account account); } ``` service中的类如下 ``` @Service("accountService") public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public List<Account> findAll() { System.out.println("findAll_service"); return accountDao.findAll(); } @Override public void saveAccount(Account account) { System.out.println("saveAccount_service"); accountDao.saveAccount(account); } } ``` 而且我的spring的配置文件已经按照教程中那样引入了mybatis的工厂什么的 ``` <?xml version="1.0" encoding="UTF-8"?> <beans 一堆约束省略了> <context:component-scan base-package="com.HSY"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 整合Mybatis--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssm" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- 配置SqlSession的工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置扫描dao的包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.HSY.dao"/> </bean> </beans> ``` SqlMapConfig的数据库配置也配了,但是最后仍然报错 ``` beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.HSY.dao.IAccountDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ``` 请问大神们怎么解决
python scrapy 爬虫图片新手求助
求问大神 我这个data她怎么了 报错: 2020-02-07 09:24:55 [scrapy.utils.log] INFO: Scrapy 1.8.0 started (bot: meizitu) 2020-02-07 09:24:55 [scrapy.utils.log] INFO: Versions: lxml 4.5.0.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d 10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.17763-SP0 2020-02-07 09:24:55 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'meizitu', 'NEWSPIDER_MODULE': 'meizitu.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['meizitu.spiders']} 2020-02-07 09:24:55 [scrapy.extensions.telnet] INFO: Telnet Password: 0936097982b9bcc8 2020-02-07 09:24:55 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2020-02-07 09:24:56 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2020-02-07 09:24:56 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] Unhandled error in Deferred: 2020-02-07 09:24:56 [twisted] CRITICAL: Unhandled error in Deferred: Traceback (most recent call last): File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 184, in crawl return self._crawl(crawler, *args, **kwargs) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 188, in _crawl d = crawler.crawl(*args, **kwargs) File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1613, in unwindGenerator return _cancellableInlineCallbacks(gen) File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1529, in _cancellableInlineCallbacks _inlineCallbacks(None, g, status) --- <exception caught here> --- File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1418, in _inlineCallbacks result = g.send(result) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 86, in crawl self.engine = self._create_engine() File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 111, in _create_engine return ExecutionEngine(self, lambda _: self.stop()) File "e:\python3.7\lib\site-packages\scrapy\core\engine.py", line 70, in __init__ self.scraper = Scraper(crawler) File "e:\python3.7\lib\site-packages\scrapy\core\scraper.py", line 71, in __init__ self.itemproc = itemproc_cls.from_crawler(crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 53, in from_crawler return cls.from_settings(crawler.settings, crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 34, in from_settings mwcls = load_object(clspath) File "e:\python3.7\lib\site-packages\scrapy\utils\misc.py", line 46, in load_object mod = import_module(module) File "e:\python3.7\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed builtins.SyntaxError: unexpected EOF while parsing (pipelines.py, line 22) 2020-02-07 09:24:56 [twisted] CRITICAL: Traceback (most recent call last): File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1418, in _inlineCallbacks result = g.send(result) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 86, in crawl self.engine = self._create_engine() File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 111, in _create_engine return ExecutionEngine(self, lambda _: self.stop()) File "e:\python3.7\lib\site-packages\scrapy\core\engine.py", line 70, in __init__ self.scraper = Scraper(crawler) File "e:\python3.7\lib\site-packages\scrapy\core\scraper.py", line 71, in __init__ self.itemproc = itemproc_cls.from_crawler(crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 53, in from_crawler return cls.from_settings(crawler.settings, crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 34, in from_settings mwcls = load_object(clspath) File "e:\python3.7\lib\site-packages\scrapy\utils\misc.py", line 46, in load_object mod = import_module(module) File "e:\python3.7\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\python_work\爬虫\meizitu\meizitu\pipelines.py", line 22 f.write(data) ^ SyntaxError: unexpected EOF while parsing 代码如下: pipeline ``` import requests class MeizituPipeline(object): def process_item(self, item, spider): print("main_title:",item['main_title']) print("main_image:", item['main_image']) print("main_tags:", item['main_tags']) print("main_meta:", item['main_meta']) print("page:", item['main_pagenavi']) url = requests.get(item['main_image']) print(url) try: with open(item['main_pagenavi'] +'.jpg','wb') as f: data = url.read() f.write(data) ``` image.py ``` import scrapy from scrapy.http import response from ..items import MeizituItem class ImageSpider(scrapy.Spider): #定义Spider的名字scrapy crawl meiaitu name = 'SpiderMain' #允许爬虫的域名 allowed_domains = ['www.mzitu.com/203554'] #爬取的首页列表 start_urls = ['https://www.mzitu.com/203554'] #负责提取response的信息 #response代表下载器从start_urls中的url的到的回应 #提取的信息 def parse(self,response): #遍历所有节点 for Main in response.xpath('//div[@class = "main"]'): item = MeizituItem() #匹配所有节点元素/html/body/div[2]/div[1]/div[3]/p/a content = Main.xpath('//div[@class = "content"]') item['main_title'] = content.xpath('./h2/text()') item['main_image'] = content.xpath('./div[@class="main-image"]/p/a/img') item['main_meta'] = content.xpath('./div[@class="main-meta"]/span/text()').extract() item['main_tags'] = content.xpath('./div[@class="main-tags"]/a/text()').extract() item['main_pagenavi'] = content.xpath('./div[@class="main_pagenavi"]/span/text()').extract_first() yield item new_links = response.xpath('.//div[@class="pagenavi"]/a/@href').extract() new_link =new_links[-1] yield scrapy.Request(new_link,callback=self.parse) ``` setting ``` BOT_NAME = 'meizitu' SPIDER_MODULES = ['meizitu.spiders'] NEWSPIDER_MODULE = 'meizitu.spiders' ROBOTSTXT_OBEY = True #配置默认请求头 DEFAULT_REQUEST_HEADERS = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36", 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' } ITEM_PIPELINES = { 'meizitu.pipelines.MeizituPipeline':300, } IMAGES_STORE = 'E:\python_work\爬虫\meizitu' IMAGES_MIN_HEIGHT = 1050 IMAGES_MIN_WIDTH = 700 ```
求助!谁知道C++UDP打洞?
# 为什么我的代码不在一个局域网内无法连接,也无反应? 服务器(UDP打洞): ``` #include <Winsock2.h> #include <stdio.h> #include <stdlib.h> #define DEFAULT_PORT 4768 #define BUFFER_SIZE 100 int main() { int serverPort = DEFAULT_PORT; WSADATA wsaData; SOCKET serverListen; struct sockaddr_in serverAddr; if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0 ) { printf("Failed to load Winsock.\n"); return -1; } serverListen = socket(AF_INET,SOCK_DGRAM,0); if (serverListen == INVALID_SOCKET) { printf("socket() failed:%d\n",WSAGetLastError()); return -1; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(serverPort); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(serverListen,(LPSOCKADDR)&serverAddr,sizeof(serverAddr)) == SOCKET_ERROR) { printf("bind() failed:%d\n",WSAGetLastError()); return -1; } struct sockaddr_in sourceAddr1; int sourceAddrLen1 = sizeof(sourceAddr1); SOCKET sockC1 = socket(AF_INET,SOCK_DGRAM,0); char bufRecv1[BUFFER_SIZE]; int len; len = recvfrom(serverListen, bufRecv1, sizeof(bufRecv1), 0,(struct sockaddr*)&sourceAddr1,&sourceAddrLen1); if (len == SOCKET_ERROR) { printf("recv() failed:%d\n", WSAGetLastError()); return -1; } printf("C1 IP:[%s],PORT:[%d]\n",inet_ntoa(sourceAddr1.sin_addr) ,ntohs(sourceAddr1.sin_port)); struct sockaddr_in sourceAddr2; int sourceAddrLen2 = sizeof(sourceAddr2); SOCKET sockC2 = socket(AF_INET,SOCK_DGRAM,0); char bufRecv2[BUFFER_SIZE]; len = recvfrom(serverListen, bufRecv2, sizeof(bufRecv2), 0,(struct sockaddr*)&sourceAddr2,&sourceAddrLen2); if (len == SOCKET_ERROR) { printf("recv() failed:%d\n", WSAGetLastError()); return -1; } printf("C2 IP:[%s],PORT:[%d]\n",inet_ntoa(sourceAddr2.sin_addr) ,ntohs(sourceAddr2.sin_port)); char bufSend1[BUFFER_SIZE]; memset(bufSend1,'\0',sizeof(bufSend1)); char* ip2 = inet_ntoa(sourceAddr2.sin_addr); char port2[10]; itoa(ntohs(sourceAddr2.sin_port),port2,10); for (int i=0;i<strlen(ip2);i++) { bufSend1[i] = ip2[i]; } bufSend1[strlen(ip2)] = '^'; for (int i=0;i<strlen(port2);i++) { bufSend1[strlen(ip2) + 1 + i] = port2[i]; } len = sendto(sockC1,bufSend1,sizeof(bufSend1),0,(struct sockaddr*)&sourceAddr1,sizeof(sourceAddr1)); if (len == SOCKET_ERROR) { printf("send() failed:%d\n",WSAGetLastError()); return -1; } else if (len == 0) { return -1; } else { printf("send() byte:%d\n",len); } char bufSend2[BUFFER_SIZE]; memset(bufSend2,'\0',sizeof(bufSend2)); char* ip1 = inet_ntoa(sourceAddr1.sin_addr); char port1[10];//C1的port itoa(ntohs(sourceAddr1.sin_port),port1,10); for (int i=0;i<strlen(ip1);i++) { bufSend2[i] = ip1[i]; } bufSend2[strlen(ip1)] = '^'; for (int i=0;i<strlen(port1);i++) { bufSend2[strlen(ip1) + 1 + i] = port1[i]; } len = sendto(sockC2,bufSend2,sizeof(bufSend2),0,(struct sockaddr*)&sourceAddr2,sizeof(sourceAddr2)); if (len == SOCKET_ERROR) { printf("send() failed:%d\n",WSAGetLastError()); return -1; } else if (len == 0) { return -1; } else { printf("send() byte:%d\n",len); } closesocket(serverListen); closesocket(sockC1); closesocket(sockC2); WSACleanup(); return 0; } ``` 用户C1: ``` #include<Winsock2.h> #include<stdio.h> #include<stdlib.h> #include <thread> #define PORT 7777 #define BUFFER_SIZE 100 int main(int argc,char* argv[]) { char APTTTTT[]="127.0.0.1"; scanf("%s",APTTTTT); int HYH=4768; WSADATA wsaData; struct sockaddr_in serverAddr; struct sockaddr_in thisAddr; thisAddr.sin_family = AF_INET; thisAddr.sin_port = htons(PORT); thisAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0) { printf("Failed to load Winsock.\n"); return -1; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(HYH); serverAddr.sin_addr.s_addr = inet_addr(APTTTTT); SOCKET sockS = socket(AF_INET,SOCK_DGRAM,0); if (sockS == INVALID_SOCKET) { printf("socket() failed:%d\n",WSAGetLastError()); return -1; } if (bind(sockS,(LPSOCKADDR)&thisAddr,sizeof(thisAddr)) == SOCKET_ERROR) { printf("bind() failed:%d\n",WSAGetLastError()); return -1; } SOCKET sockC = socket(AF_INET,SOCK_DGRAM,0); if (sockC == INVALID_SOCKET) { printf("socket() failed:%d\n",WSAGetLastError()); return -1; } char bufSend[] = "I am C1"; char bufRecv[BUFFER_SIZE]; memset(bufRecv,'\0',sizeof(bufRecv)); struct sockaddr_in sourceAddr; int sourceAddrLen = sizeof(sourceAddr); struct sockaddr_in oppositeSideAddr; int len; len = sendto(sockS,bufSend,sizeof(bufSend),0,(struct sockaddr*)&serverAddr,sizeof(serverAddr)); if (len == SOCKET_ERROR) { printf("sendto() failed:%d\n", WSAGetLastError()); return -1; } len = recvfrom(sockS, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); if (len == SOCKET_ERROR) { int TRYY=WSAGetLastError(); if(TRYY!= WSAECONNRESET) { printf("recvfrom() failed:%d\n", WSAGetLastError()); return -1; } } closesocket(sockS); if (bind(sockC,(LPSOCKADDR)&thisAddr,sizeof(thisAddr)) == SOCKET_ERROR) { printf("bind() failed:%d\n",WSAGetLastError()); return -1; } char ip[20]; char port[10]; int i; for (i=0;i<strlen(bufRecv);i++) if (bufRecv[i] != '^') ip[i] = bufRecv[i]; else break; ip[i] = '\0'; int j; for (j=i+1;j<strlen(bufRecv);j++) port[j - i - 1] = bufRecv[j]; port[j - i - 1] = '\0'; oppositeSideAddr.sin_family = AF_INET; oppositeSideAddr.sin_port = htons(atoi(port)); oppositeSideAddr.sin_addr.s_addr = inet_addr(ip); unsigned long ul = 1; ioctlsocket(sockC, FIONBIO, (unsigned long*)&ul); while (1) { Sleep(1000); len = sendto(sockC,bufSend,sizeof(bufSend),0,(struct sockaddr*)&oppositeSideAddr,sizeof(oppositeSideAddr)); if (len == SOCKET_ERROR) { printf("while sending package to C2 , sendto() failed:%d\n", WSAGetLastError()); return -1; }else { printf("successfully send package to C2\n"); } len = recvfrom(sockC, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); if (len == WSAEWOULDBLOCK) { continue; }else { printf("C2 IP:[%s],PORT:[%d]\n",inet_ntoa(sourceAddr.sin_addr) ,ntohs(sourceAddr.sin_port)); printf("C2 says:%s\n",bufRecv); break; } } char buff[1024]={}; while(1) { memset(buff, 0, 1024); scanf("%s",buff); sendto(sockC,buff,sizeof(buff),0,(struct sockaddr*)&oppositeSideAddr,sizeof(oppositeSideAddr)); recvfrom(sockC, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); printf("%s\n\n",bufRecv); } closesocket(sockC); } ``` 用户C2: ``` #include<Winsock2.h> #include<stdio.h> #include<stdlib.h> #include <thread> #define PORT 8888 #define BUFFER_SIZE 100 int main(int argc,char* argv[]) { char APTTTTT[]="127.0.0.1"; scanf("%s",APTTTTT); int HYH=4768; WSADATA wsaData; struct sockaddr_in serverAddr; struct sockaddr_in thisAddr; thisAddr.sin_family = AF_INET; thisAddr.sin_port = htons(PORT); thisAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0) { printf("Failed to load Winsock.\n"); return -1; } serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(HYH); serverAddr.sin_addr.s_addr = inet_addr(APTTTTT); SOCKET sockS = socket(AF_INET,SOCK_DGRAM,0); if (sockS == INVALID_SOCKET) { printf("socket() failed:%d\n",WSAGetLastError()); return -1; } if (bind(sockS,(LPSOCKADDR)&thisAddr,sizeof(thisAddr)) == SOCKET_ERROR) { printf("bind() failed:%d\n",WSAGetLastError()); return -1; } SOCKET sockC = socket(AF_INET,SOCK_DGRAM,0); if (sockC == INVALID_SOCKET) { printf("socket() failed:%d\n",WSAGetLastError()); return -1; } char bufSend[] = "I am C2"; char bufRecv[BUFFER_SIZE]; memset(bufRecv,'\0',sizeof(bufRecv)); struct sockaddr_in sourceAddr; int sourceAddrLen = sizeof(sourceAddr); struct sockaddr_in oppositeSideAddr; int len; len = sendto(sockS,bufSend,sizeof(bufSend),0,(struct sockaddr*)&serverAddr,sizeof(serverAddr)); if (len == SOCKET_ERROR) { printf("sendto() failed:%d\n", WSAGetLastError()); return -1; } len = recvfrom(sockS, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); if (len == SOCKET_ERROR) { int TRYY=WSAGetLastError(); if(TRYY!= WSAECONNRESET) { printf("recvfrom() failed:%d\n", WSAGetLastError()); return -1; } } closesocket(sockS); if (bind(sockC,(LPSOCKADDR)&thisAddr,sizeof(thisAddr)) == SOCKET_ERROR) { printf("bind() failed:%d\n",WSAGetLastError()); return -1; } char ip[20]; char port[10]; int i; for (i=0;i<strlen(bufRecv);i++) if (bufRecv[i] != '^') ip[i] = bufRecv[i]; else break; ip[i] = '\0'; int j; for (j=i+1;j<strlen(bufRecv);j++) port[j - i - 1] = bufRecv[j]; port[j - i - 1] = '\0'; oppositeSideAddr.sin_family = AF_INET; oppositeSideAddr.sin_port = htons(atoi(port)); oppositeSideAddr.sin_addr.s_addr = inet_addr(ip); unsigned long ul = 1; ioctlsocket(sockC, FIONBIO, (unsigned long*)&ul); while (1) { Sleep(1000); len = sendto(sockC,bufSend,sizeof(bufSend),0,(struct sockaddr*)&oppositeSideAddr,sizeof(oppositeSideAddr)); if (len == SOCKET_ERROR) { printf("while sending package to C1 , sendto() failed:%d\n", WSAGetLastError()); return -1; }else { printf("successfully send package to C1\n"); } len = recvfrom(sockC, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); if (len == WSAEWOULDBLOCK) { continue; }else { printf("C1 IP:[%s],PORT:[%d]\n",inet_ntoa(sourceAddr.sin_addr) ,ntohs(sourceAddr.sin_port)); printf("C1 says:%s\n",bufRecv); break; } } char buff[1024]={}; while(1) { memset(buff, 0, 1024); scanf("%s",buff); sendto(sockC,buff,sizeof(buff),0,(struct sockaddr*)&oppositeSideAddr,sizeof(oppositeSideAddr)); recvfrom(sockC, bufRecv, sizeof(bufRecv), 0,(struct sockaddr*)&sourceAddr,&sourceAddrLen); printf("%s\n\n",bufRecv); } closesocket(sockC); } ```
Android studio想要从登陆界面跳转到这个界面会闪退,求解决,这个界面的代码有什么问题吗,但是并没有报错
![图片说明](https://img-ask.csdn.net/upload/202002/12/1581516213_390363.png) package com.example; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import com.example.AskHelp.SystemHelp; import com.example.BloodPressure.BloodPressureActivity; import com.example.BloodSugar.BloodSugarActivity; import com.example.FileManager.FileManagerActivity; import com.example.HeartAuscultation.HeartListen; import com.geniuseoe.demo.R; /** * 功能描述:将系统的各个功能模块添加在TabHost选项卡中,实现在各选项卡之间手动切换以显示不同模块的内容 * */ @SuppressWarnings("deprecation") public class MainTabHost extends TabActivity { private TabHost tabHost; private RadioGroup radioGroup; // Tab选项卡的图标数组 private int[] tabIconViewArray = { R.drawable.tab_icon1, R.drawable.tab_icon2, R.drawable.tab_icon3, R.drawable.tab_icon4, R.drawable.tab_icon5 }; // Tab选项卡的文字数组 private String[] tabNameTextArray = { "档案", "血压", "血糖", "听诊", "帮助" }; // Tab选项卡中的内容(类)数组 private Class[] tabContentClassArray = { FileManagerActivity.class, BloodPressureActivity.class, BloodSugarActivity.class, HeartListen.class, SystemHelp.class }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_tab_host); // 为每一个选项卡设置按钮、图标、文字和内容,将Tab按钮添加进Tab选项卡中 TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); for (int i = 0; i < tabContentClassArray.length; i++) { TabSpec tabSpec = tabHost.newTabSpec(tabNameTextArray[i]) .setIndicator(tabNameTextArray[i]) .setContent(getTabItemIntent(i)); tabHost.addTab(tabSpec); } initData(); } // 对选项卡上的每个按钮进行监听,以实现模块的切换 private void initData() { radioGroup = (RadioGroup) findViewById(R.id.main_radiogroup); radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.RadioButton0: tabHost.setCurrentTabByTag(tabNameTextArray[0]); break; case R.id.RadioButton1: tabHost.setCurrentTabByTag(tabNameTextArray[1]); break; case R.id.RadioButton2: tabHost.setCurrentTabByTag(tabNameTextArray[2]); break; case R.id.RadioButton3: tabHost.setCurrentTabByTag(tabNameTextArray[3]); break; case R.id.RadioButton4: tabHost.setCurrentTabByTag(tabNameTextArray[4]); break; } } }); ((RadioButton) radioGroup.getChildAt(0)).toggle(); } // 给Tab选项卡设置Activity内容,并且将LoginActivity传入的swapUsername数据转让每个Intent携带分发给每个Tab选项 private Intent getTabItemIntent(int index) { Bundle swapData = new Bundle(); swapData.putString("swapUsername", this.getBundleData()); Intent intent = new Intent(this, tabContentClassArray[index]); intent.putExtras(swapData); return intent; } // 获取启动该MainTabHostAcitivity的Intent,传入Intent携带的 username数据 public String getBundleData() { Intent intent = getIntent(); Bundle data = intent.getExtras(); String swapData = data.getString("username").toString(); return swapData; } } ``` ```
新登录的用户名怎么判断是否和已登录的用户名重名?
用户1、用户2、用户3、用户4依次登录,再登录用户2怎么判断是否重名 ![图片说明](https://img-ask.csdn.net/upload/202002/13/1581566962_929174.png) ![图片说明](https://img-ask.csdn.net/upload/202002/13/1581566977_484440.png) ``` package Pack; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; public class Test { private JFrame jf = null; private JTextField CastIPTxtFiled = new JTextField("228.9.6.8");// 组播IP地址文本框 private JTextField portTxtFiled = new JTextField("8000");// 端口地址文本框 private JTextField nameField = new JTextField("用户");// 用户名文本框 private JTextArea receiveMesArea = new JTextArea();// 接收消息文本域 private JTextArea sendMesArea = new JTextArea();// 发送消息文本域 private JButton startChatBtn = new JButton("开始聊天");// 按钮 private JButton stopChatBtn = new JButton("断开聊天"); private JButton quitBtn = new JButton("退出"); private JButton saveBtn = new JButton("保存"); private JButton cleaBtn = new JButton("清空"); private JButton sendBtn = new JButton("发送"); private JRadioButton groupchatBtn = new JRadioButton("群聊");// 单选按钮 private JRadioButton privatechatBtn = new JRadioButton("私聊"); private ButtonGroup btg = new ButtonGroup(); private JList<String> jlist = new JList<String>();// 列表框 private DefaultListModel<String> dlm = new DefaultListModel<String>();// 用dlm向jlist动态增删用户 private JScrollPane jScrollPane1 = new JScrollPane(receiveMesArea);// 滚动窗口 private JScrollPane jScrollPane2 = new JScrollPane(sendMesArea); private JScrollPane jScrollPane3 = new JScrollPane(jlist); private BroadCast broadCast = null; boolean broadCastIsDisable = true; boolean chitchat = true;// 判断是群聊还是私聊 public void InitFrame() { jf = new JFrame("组播聊天室"); jf.setLayout(null); jf.setSize(650, 530); jf.setLocationRelativeTo(null);// 在屏幕中居中显示 jf.setResizable(false);// 不可调整窗口大小 jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// 标题栏关闭按钮失效 JLabel nameJLabel = new JLabel("用户名"); nameJLabel.setBounds(30, 80, 60, 20); jf.add(nameJLabel); nameField.setBounds(80, 80, 100, 20); jf.add(nameField); JLabel portTxtJLabel = new JLabel("端口地址"); portTxtJLabel.setBounds(300, 20, 60, 20); jf.add(portTxtJLabel); portTxtFiled.setBounds(360, 20, 100, 20); jf.add(portTxtFiled); JLabel CastIPTxtJLabel = new JLabel("组播IP地址"); CastIPTxtJLabel.setBounds(10, 20, 90, 20); jf.add(CastIPTxtJLabel); CastIPTxtFiled.setBounds(80, 20, 100, 20); jf.add(CastIPTxtFiled); startChatBtn.setBounds(220, 80, 100, 20); stopChatBtn.setBounds(360, 80, 100, 20); jf.add(startChatBtn); jf.add(stopChatBtn); JLabel receiveJLabel = new JLabel("接收消息"); receiveJLabel.setBounds(20, 140, 100, 20); jScrollPane1.setBounds(20, 160, 460, 130); jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane1); jf.add(receiveJLabel); JLabel sendJLabel = new JLabel("发送消息"); sendJLabel.setBounds(20, 300, 100, 20); jScrollPane2.setBounds(20, 320, 460, 100); jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane2); jf.add(sendJLabel); jlist.setModel(dlm); jScrollPane3.setBorder(BorderFactory.createTitledBorder("在线用户列表")); jScrollPane3.setBounds(500, 20, 120, 430); jScrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jScrollPane3); quitBtn.setBounds(20, 460, 100, 20); // 退出 jf.add(quitBtn); saveBtn.setBounds(140, 460, 100, 20); // 保存 jf.add(saveBtn); cleaBtn.setBounds(260, 460, 100, 20);// 清空 jf.add(cleaBtn); sendBtn.setBounds(380, 460, 100, 20); // 发送 jf.add(sendBtn); groupchatBtn.setBounds(120, 120, 100, 20); jf.add(groupchatBtn); privatechatBtn.setBounds(320, 120, 100, 20); jf.add(privatechatBtn); btg.add(groupchatBtn); btg.add(privatechatBtn); groupchatBtn.setSelected(true); jf.setVisible(true); // 显示窗口 BtnFalse(); Object1(); receiveMesArea.setEditable(false);// 接收消息文本域不能被编辑 sendBtn.setMnemonic(KeyEvent.VK_ENTER); // 给sendBtn设置快捷键(Alt+Enter) broadCast = new BroadCast(Integer.parseInt(portTxtFiled.getText()), CastIPTxtFiled.getText(), nameField.getText()); startChatBtn.addActionListener(new ButtonAction()); stopChatBtn.addActionListener(new ButtonAction()); groupchatBtn.addActionListener(new ButtonAction()); privatechatBtn.addActionListener(new ButtonAction()); quitBtn.addActionListener(new ButtonAction()); saveBtn.addActionListener(new ButtonAction()); cleaBtn.addActionListener(new ButtonAction()); sendBtn.addActionListener(new ButtonAction()); jlist.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { Object2(); } }); } public class ButtonAction implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource().equals(startChatBtn)) { jf.setTitle("当前用户:" + nameField.getText()); startChatBtn.setEnabled(false); BtnTrue(); Object2(); broadCastIsDisable = false; StartChat(); } else if (e.getSource().equals(stopChatBtn)) { jf.setTitle("组播聊天室"); startChatBtn.setEnabled(true); BtnFalse(); Object1(); broadCastIsDisable = true; broadCast.StopChat(); // 用户下线 } else if (e.getSource().equals(groupchatBtn)) { chitchat = true; Object2(); } else if (e.getSource().equals(privatechatBtn)) { chitchat = false; Object2(); } else if (e.getSource().equals(quitBtn)) { if (broadCastIsDisable == false) { broadCast.StopChat(); } System.exit(0); } else if (e.getSource().equals(saveBtn)) { try { SaveScreen(); Object2(); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource().equals(cleaBtn)) { ClearScreen(); Object2(); } else if (e.getSource().equals(sendBtn)) { if (sendMesArea.getText().equals("")) { JOptionPane.showMessageDialog(jf, "请输入需要发送的消息", "提示!!!", JOptionPane.ERROR_MESSAGE); } else { SendMessage(); sendMesArea.setText(null);// 按发送按钮,立即将发送消息文本域内容清空 } Object2(); } } } public void Object1() { nameField.requestFocusInWindow();// 将nameField设置为焦点 nameField.selectAll(); startChatBtn.getRootPane().setDefaultButton(startChatBtn);// 将startChatBtn设置为焦点,按回车相当于鼠标单击 } public void Object2() { sendMesArea.requestFocusInWindow(); } public void BtnTrue() {// 按钮可点击 stopChatBtn.setEnabled(true); sendBtn.setEnabled(true); groupchatBtn.setEnabled(true); privatechatBtn.setEnabled(true); } public void BtnFalse() {// 按钮不可点击 stopChatBtn.setEnabled(false); sendBtn.setEnabled(false); groupchatBtn.setEnabled(false); privatechatBtn.setEnabled(false); } public void StartChat() { // 用户上线开始聊天 String port = portTxtFiled.getText(); String castIp = portTxtFiled.getText(); if (!castIp.equals("") && !port.equals("")) { broadCast = new BroadCast(Integer.parseInt(portTxtFiled.getText()), CastIPTxtFiled.getText(), nameField.getText()); broadCast.start(); // 启动线程 } } public void SendMessage() { if (chitchat == true) { broadCast.SendMessage(sendMesArea.getText().toString()); } else { broadCast.SendMessage("@" + jlist.getSelectedValue() + "#" + sendMesArea.getText().toString()); } } public void SaveScreen() throws IOException { broadCast.SaveScreen(); } public void ClearScreen() { broadCast.ClearScreen(); } public static void main(String[] args) { Test client = new Test(); client.InitFrame(); } public class BroadCast extends Thread { public int port = 0; // 端口地址 String Ip = ""; // 组播IP地址 String name = ""; // 用户名 MulticastSocket multicastSocket = null; boolean StopThread = false; static final char FLAG_CHAT = '#'; static final char FLAG_PM_USER = '@'; static final char FLAG_PM_TEXT = '#'; static final char FLAG_ONLINE = '$'; static final char FLAG_OFFLINE = '&'; static final char FLAG_REQ_ONLINE = '*'; static final char FLAG_ALREADY_ONLINE = '+'; public BroadCast(int port, String Ip, String name) { this.port = port; this.Ip = Ip; this.name = name; } public void SocketSend(String data) // 发送组播消息 { try { byte[] buf = data.getBytes(); DatagramPacket datagramPacket1 = new DatagramPacket(buf, buf.length); InetAddress address = InetAddress.getByName(Ip); datagramPacket1.setAddress(address); datagramPacket1.setPort(port); multicastSocket.send(datagramPacket1); } catch (IOException e) { e.printStackTrace(); } } public void SendMessage(String message) // 发送组播消息 { SocketSend(FLAG_CHAT + this.name + ":" + message); // '#' + this.name + ":" + message } public void SendUserOnline() // 发送用户上线消息 { SocketSend(FLAG_ONLINE + this.name); // '$' + this.name } public void SendUserOffline() // 发送用户下线消息 { SocketSend(FLAG_OFFLINE + this.name); // '&' + this.name } public void ReqOnlineUser() // 请求在线用户 { SocketSend(String.valueOf(FLAG_REQ_ONLINE)); // '*' 请求在线用户 } public void SendAlreadyOnline() // 当前在线用户 { SocketSend(FLAG_ALREADY_ONLINE + this.name); // '+' + this.name } public void StopChat() { SendUserOffline(); // 发送用户下线消息 StopThread = true; // 用户下线 while (StopThread == true) { dlm.removeAllElements(); } } public void PrintMessageWT(String message) // 带时间的消息 { receiveMesArea.append("[" + GetSystemTime() + "] "); receiveMesArea.append(message); receiveMesArea.append("\n"); receiveMesArea.setCaretPosition(receiveMesArea.getText().length()); } public void SaveScreen() throws IOException { // 保存聊天记录 String msg = receiveMesArea.getText(); FileOutputStream Note = new FileOutputStream(this.name + "的聊天记录.txt"); PrintMessageWT("聊天记录保存地址:" + System.getProperty("user.dir") + "\\" + this.name + "的聊天记录.txt"); Note.write(msg.getBytes()); Note.close(); } public void ClearScreen() { receiveMesArea.setText(""); // 清空接收消息文本域内容 } public String GetSystemTime() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // 获取当前时间(格式yyyy-MM-dd HH:mm:ss) return sdf.format(new Date()); // 返回当前时间 } public void run() { // 启动线程 try { InetAddress address = InetAddress.getByName(Ip); multicastSocket = new MulticastSocket(this.port); multicastSocket.joinGroup(address); SendUserOnline(); // 发送用户上线消息 ReqOnlineUser(); // 请求在线用户 while (!StopThread) { byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); if (multicastSocket.isClosed() == false) { multicastSocket.receive(datagramPacket); String string_MS = new String(datagramPacket.getData(), 0, datagramPacket.getLength()); switch (string_MS.charAt(0)) { case (FLAG_ONLINE): // '$' string_MS = string_MS.substring(1, string_MS.length()); // 去掉第一个字符,获取用户名 // dlm.addElement(string_MS); PrintMessageWT("系统提示:" + string_MS + " 上线!"); break; case (FLAG_OFFLINE): // '&' string_MS = string_MS.substring(1, string_MS.length()); dlm.removeElement(string_MS); PrintMessageWT("系统提示:" + string_MS + " 下线!"); break; case (FLAG_REQ_ONLINE): // '*' SendAlreadyOnline(); break; case (FLAG_ALREADY_ONLINE): // '+' string_MS = string_MS.substring(1, string_MS.length()); boolean notfound = true; for (int i = 0; i < dlm.size(); i++) { if (dlm.get(i).equals(string_MS)) { notfound = false; break; } } if (notfound == true) { if (nameField.getText().equals(string_MS)) { JOptionPane.showMessageDialog(jf, "欢迎加入组播聊天室!!!", "提示!!!", JOptionPane.INFORMATION_MESSAGE); } dlm.addElement(string_MS); // receiveMesArea.append("新加入用户:" + string_MS + "\n"); // receiveMesArea.append("目前总人數:" + String.valueOf(dlm.size()) + "\n"); } } int max = dlm.size(), min = 0; int ran = (int) (Math.random() * (max - min) + min); jlist.setSelectedIndex(ran); boolean IsPM1 = false, IsPM2 = false;// 判断是否为私聊,默认不是 int num1 = 0, num2 = 0; if (string_MS.charAt(0) == FLAG_CHAT) {// '#' 判断第一个字符是否相等 string_MS = string_MS.substring(1, string_MS.length());// 去掉第一个字符 for (int i = 0; i < string_MS.length(); i++) {// 私聊,判断@和#在哪个位置,获取姓名 if (string_MS.charAt(i) == FLAG_PM_USER) { // '@' num1 = i + 1; IsPM1 = true;// 是私聊 } if (string_MS.charAt(i) == FLAG_PM_TEXT) { // '#' num2 = i; } } String Chat_UserName = string_MS.substring(num1, num2++);// 获取私聊对象的姓名 if (IsPM1 == true) {// 是私聊 String PM_SenderName = string_MS.substring(0, num1 - 2);// 获取私聊对象的姓名 if (this.name.equals(Chat_UserName)) {// 是和我私聊 PrintMessageWT("私聊消息--> " + PM_SenderName + "@我:" + string_MS.substring(num2, string_MS.length())); } else if (this.name.equals(PM_SenderName)) {// 自己发私聊消息 PrintMessageWT("私聊消息--> " + "我@" + Chat_UserName + ":" + string_MS.substring(num2, string_MS.length())); } else {// 不是和我私聊 IsPM2 = true; } } if (IsPM1 == false && IsPM2 == false) { // 不是私聊 PrintMessageWT(string_MS); } } } } } catch (Exception e) { e.printStackTrace(); } try { multicastSocket.close(); } catch (Exception e) { e.printStackTrace(); } StopThread = false; } } } ```
pycham中django项目中导入自定义模块报错
从进行数据迁移的时候,报的错。 从comment/models.py 导入blog/models.py中的Post类。刚接触这个,上网查了整不懂。。。![图片说明](https://img-ask.csdn.net/upload/202002/09/1581227182_368122.jpg)![图片说明](https://img-ask.csdn.net/upload/202002/09/1581227190_265330.jpg)![图片说明](https://img-ask.csdn.net/upload/202002/09/1581227198_245260.jpg) 查的一般都说工作目录下搜不到这个目录,求大神告知 下面是我的报错 (venv) C:\Users\hty11\PycharmProjects\typeidea\typeidea>python manage.py makemigrations C:\Users\hty11\PycharmProjects\typeidea\typeidea C:\Users\hty11\PycharmProjects\typeidea C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\python38.zip C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\DLLs C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\lib C:\Users\hty11\AppData\Local\Programs\Python\Python38-32 C:\Users\hty11\PycharmProjects\typeidea\venv C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\pip-19.0.3-py3.8.egg C:\Users\hty11\PycharmProjects\typeidea\typeidea\blog\models.py Traceback (most recent call last): File "manage.py", line 24, in <module> main() File "manage.py", line 20, in main execute_from_command_line(sys.argv) File "C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\hty11\PycharmProjects\typeidea\typeidea\comment\models.py", line 7, in <module> from typeidea.blog.models import Post ModuleNotFoundError: No module named 'typeidea.blog' ![图片说明](https://img-ask.csdn.net/upload/202002/09/1581237107_695039.jpg) C:\Users\hty11\PycharmProjects\typeidea\typeidea C:\Users\hty11\PycharmProjects\typeidea C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\python38.zip C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\DLLs C:\Users\hty11\AppData\Local\Programs\Python\Python38-32\lib C:\Users\hty11\AppData\Local\Programs\Python\Python38-32 C:\Users\hty11\PycharmProjects\typeidea\venv C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg C:\Users\hty11\PycharmProjects\typeidea\venv\lib\site-packages\pip-19.0.3-py3.8.egg C:\Users\hty11\PycharmProjects\typeidea
【小白求助】安卓opencv用分类器对人脸进行识别的一些问题
小白入门,最近在看opencv的人脸识别(分类) 然后按照网上的代码,学习了之后,自己写了一段,发现运行的时候会卡很久,甚至直接退出,并且越用越卡。 我想实现的是对一张图片进行读入,然后加载多个分类器对图片内容进行识别,从而达到分类的目的。 我那个问题困扰了我一天,想来求助大神 我加载人脸识别的模型没问题,但是同时加载两个模型,比如说人脸和上身,就会卡死。 代码分3个部分,分别是MainActivity.java , execDetect.java , Detector.java 以下是MainActivity.java ``` package com.RinGo.IMGfenlei; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; public class MainActivity extends AppCompatActivity { private Detector frontfaceDetector; private Detector smileDetector; private static String CAMERAIMAGENAME = "image.jpg"; private ImageButton imageButton; private ImageButton imageButton2; private TextView textView; private Bitmap bitmap; private Bitmap rectBitmap; private Bitmap resizeBitmap; private Toast toast; private Button addFile; private Button startDetect; private Button check; private execDetect toDetcet; private String show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv_face); // imageButton = (ImageButton) findViewById(R.id.iv_face); //imageButton.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); // imageButton2 = (ImageButton) findViewById(R.id.iv_face2); // imageButton2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); toDetcet=new execDetect(); addFile=(Button)findViewById(R.id.addPic); startDetect=(Button)findViewById(R.id.startDetect); check=(Button)findViewById(R.id.check); startDetect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // startDetect.setClickable(false); textView.setText("正在检测"); // detect(); Thread d =new Thread(new Runnable() { @Override public void run() { toDetcet.initExecDetect(MainActivity.this,bitmap); // Toast.makeText(MainActivity.this, "initialize succeed", Toast.LENGTH_SHORT).show(); show= toDetcet.startDetect(); // Toast.makeText(MainActivity.this, " succeed", Toast.LENGTH_SHORT).show(); } }); d.run(); textView.setText(show); // startDetect.setClickable(true); } }); check.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // startDetect.setClickable(false); textView.setText(toDetcet.getReturntoMain()); // startDetect.setClickable(true); } }); addFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 添加照片 // 打开本地相册 Intent intent1 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent1, 101); //startActivity(intent1); } }); String strLibraryName = "opencv_java3"; // 不需要添加前缀 libopencv_java3 { try { Log.e("loadLibrary", strLibraryName); System.loadLibrary(strLibraryName); //System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // couldn't find "libopencv_java320.so" } catch (UnsatisfiedLinkError e) { Log.e("loadLibrary", "Native code library failed to load.\n" + e); } catch (Exception e) { Log.e("loadLibrary", "Exception: " + e); } } // frontfaceDetector = new Detector(this, R.raw.haarcascade_frontalface_alt, 6, 0.2F, 0.2F, new Scalar(255, 0, 0, 255)); } /** * 点击添加照片事件 * * @param v */ public void onClick(View v) { int bt_id = v.getId(); switch (bt_id) { /* case R.id.takePhoto: // 拍照 // 打开本地相机 Intent intent2 = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), CAMERAIMAGENAME)); intent2.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent2, 102); break; */ case R.id.back: this.finish(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 加判断 不选择照片或者不拍照时不闪退 //Log.e("data", String.valueOf(data)); //if (data == null) //return; bitmap = null; switch (requestCode) { // 选择图片库的图片 case 101: if (resultCode == RESULT_OK) { try { Uri uri = data.getData(); bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); } catch (Exception e) { e.printStackTrace(); } } break; // 表示调用本地照相机拍照 case 102: if (resultCode == RESULT_OK) { //Bundle bundle = data.getExtras(); //bm = (Bitmap) bundle.get("data"); bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + CAMERAIMAGENAME); } break; default: break; } Log.e("bitmap", String.valueOf(bitmap)); if (bitmap == null) { toast = Toast.makeText(MainActivity.this, "未选择图像", Toast.LENGTH_SHORT); toast.show(); return; } // 识别图片 并画框 /* Thread detect=new Thread(new Runnable() { @Override public void run() { } }); detect.run(); */ // 将照片剪裁 bitmap将被释放重新赋值 //int ibWidth = imageButton.getWidth(); // int ibHeight = imageButton.getHeight(); //resizeBitmap = imageButton.resizeBitmap(bitmap, ibWidth, ibHeight); //imageButton.setBitmap(resizeBitmap); //imageButton2.setBitmap(rectBitmap); } private void detect() { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { toDetcet.initExecDetect(MainActivity.this,bitmap); // Toast.makeText(MainActivity.this, "initialize succeed", Toast.LENGTH_SHORT).show(); String show= toDetcet.startDetect(); // Toast.makeText(MainActivity.this, " succeed", Toast.LENGTH_SHORT).show(); textView.setText(show); } }); //textView.setText(toDetcet.getReturntoMain()); } } ``` 以下是activity_main.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_face" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:text="未检测到人脸" android:textColor="@color/colorAccent" app:layout_constraintBottom_toTopOf="@+id/ll1" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <LinearLayout android:id="@+id/ll1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"> <com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton android:id="@+id/addPic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_weight="1" android:onClick="onClick" android:text=" 选择图片(CV) " android:textSize="16sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton android:id="@+id/startDetect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_weight="1" android:onClick="onClick" android:text=" 开始识别 " android:textSize="16sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_weight="1" android:onClick="onClick" android:text=" 结果 " android:textSize="16sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="0dp" android:layout_weight="1" android:onClick="onClick" android:text=" 返回 " android:textSize="16sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> </LinearLayout> </LinearLayout> ``` 以下是execDetect.java ``` package com.RinGo.IMGfenlei; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import com.RinGo.IMGfenlei.R; import com.RinGo.IMGfenlei.Detector; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; public class execDetect { private Detector frontfaceDetector; private Detector smilefaceDetector; private Detector[] detectors=new Detector[10]; private Detector detector; private Bitmap bitmap; private Bitmap rectBitmap; private String returntoMain=""; private String[] detectorNames=new String[10]; private CascadeClassifier mFrontalFaceClassifier = null; //正脸 级联分类器 private CascadeClassifier mProfileFaceClassifier = null; //侧脸 级联分类器 private int smilefacenum=0; private Context mcontext; private int[] cascades=new int[10]; public void initExecDetect(Context _context,Bitmap _bitmap) { bitmap=_bitmap; mcontext=_context; cascades[0]=R.raw.haarcascade_frontalface_alt; detectors[0] = new Detector(_context,R.raw.haarcascade_frontalface_alt, 1, 0.2F, 0.2F, new Scalar(255, 0, 0, 255)); detectorNames[0]="正面人脸"; cascades[1]=R.raw.lbpcascade_frontalface; detectors[1] = new Detector(_context,R.raw.lbpcascade_frontalface, 1, 0.2F, 0.2F, new Scalar(255, 0, 0, 255)); detectorNames[1]="正面人脸2"; } public String startDetect() { // bitmapToMat Mat toMat = new Mat(); Utils.bitmapToMat(bitmap, toMat); // Mat copyMat = new Mat(); // toMat.copyTo(copyMat); // 复制 // togray Mat gray = new Mat(); MatOfRect mRect = new MatOfRect(); Imgproc.cvtColor(toMat, gray, Imgproc.COLOR_RGBA2GRAY); for (int id = 0; id < detectors.length; id++) { //detector = new Detector(mcontext,cascades[id], 3, 0.1F, 0.1F, new Scalar(255, 0, 0, 255)); try { int num = 0; mRect=new MatOfRect(); Rect[] object = detectors[id].detectObjectImage( gray, mRect); Log.e("objectLength", object.length + ""); num=object.length; /* for (Rect rect : object) { num++; } */ returntoMain =returntoMain+ String.format("检测到%1$d个" + detectorNames[id], num) + "\n"; } catch (Exception e) { e.printStackTrace(); } //textView.setText(String.format("检测到%1$d个人脸", facenum)); //Utils.matToBitmap(toMat, bitmap); } return returntoMain; } public String getReturntoMain() { return returntoMain; } } ``` 以下是Detector.java,定义了我的级联分类器的设置 ``` package com.RinGo.IMGfenlei; import android.content.Context; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.objdetect.CascadeClassifier; import org.opencv.objdetect.Objdetect; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by think-hxr on 17-10-12. */ public class Detector { private CascadeClassifier mCascadeClassifier; private int mMinNeighbors; private float mRelativeObjectWidth; private float mRelativeObjectHeight; private Scalar mRectColor; /** * 构造方法 * * @param context 上下文 * @param id 级联分类器ID * @param minNeighbors 连续几帧确认目标 * @param relativeObjectWidth 最小宽度屏占比 * @param relativeObjectHeight 最小高度屏占比 * @param rectColor 画笔颜色 */ public Detector(Context context, int id, int minNeighbors, float relativeObjectWidth, float relativeObjectHeight, Scalar rectColor) { context = context.getApplicationContext(); mCascadeClassifier = createDetector(context, id); mMinNeighbors = minNeighbors; mRelativeObjectWidth = relativeObjectWidth; mRelativeObjectHeight = relativeObjectHeight; mRectColor = rectColor; } /** * 创建检测器 * * @param context 上下文 * @param id 级联分类器ID * @return 检测器 */ private CascadeClassifier createDetector(Context context, int id) { CascadeClassifier javaDetector; InputStream is = null; FileOutputStream os = null; try { is = context.getResources().openRawResource(id); File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE); File cascadeFile = new File(cascadeDir, id + ".xml"); os = new FileOutputStream(cascadeFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } javaDetector = new CascadeClassifier(cascadeFile.getAbsolutePath()); //javaDetector=new CascadeClassifier(); // javaDetector.load(cascadeFile.getAbsolutePath()); if (javaDetector.empty()) { javaDetector = null; } boolean delete = cascadeDir.delete(); return javaDetector; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { if (null != is) { is.close(); } if (null != os) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 目标检测 视频 * * @param gray 灰度图像 * @param object 识别结果的容器 * @return 检测到的目标位置集合 */ public Rect[] detectObject(Mat gray, MatOfRect object) { // 使用Java人脸检测 mCascadeClassifier.detectMultiScale( gray, // 要检查的灰度图像 object, // 检测到的人脸 1.1, // 表示在前后两次相继的扫描中,搜索窗口的比例系数。默认为1.1即每次搜索窗口依次扩大10%; mMinNeighbors, // 默认是3 控制误检测,表示默认几次重叠检测到人脸,才认为人脸存在 Objdetect.CASCADE_SCALE_IMAGE, getSize(gray, mRelativeObjectWidth, mRelativeObjectHeight), // 目标最小可能的大小 gray.size()); // 目标最大可能的大小 return object.toArray(); } /** * 目标检测 图片 * * @param gray 灰度图像 * @param object 识别结果的容器 * @return */ public Rect[] detectObjectImage(Mat gray, MatOfRect object) { mCascadeClassifier.detectMultiScale(gray,object); return object.toArray(); } /** * 根据屏占比获取大小 * * @param gray gray * @param relativeObjectWidth 最小宽度屏占比 * @param relativeObjectHeight 最小高度屏占比 * @return 大小 */ private Size getSize(Mat gray, float relativeObjectWidth, float relativeObjectHeight) { Size size = gray.size(); int cameraWidth = gray.cols(); int cameraHeight = gray.rows(); int width = Math.round(cameraWidth * relativeObjectWidth); int height = Math.round(cameraHeight * relativeObjectHeight); size.width = 0 >= width ? 0 : (cameraWidth < width ? cameraWidth : width); // width [0, cameraWidth] size.height = 0 >= height ? 0 : (cameraHeight < height ? cameraHeight : height); // height [0, cameraHeight] return size; } /** * 获取画笔颜色 * * @return 颜色 */ public Scalar getRectColor() { return mRectColor; } } ```
基于springmvc+mybatis的登录表单提交后404
前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符编码 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)
Java swing选项卡中有表格,表格中有按钮,按钮按不到
![成果图](https://oscimg.oschina.net/oscnet/up-f1f985da2b44ac32a58a6e778c7c15e22a1.JPEG) ``` package com.java.gui; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.image.ImageConsumer; import java.net.URL; public class JTabbedPaneDemo extends JPanel { private JTabbedPane jTabbedPane = new JTabbedPane(); private String[] tabNames = {"选项卡1", "选项卡2", "表格"}; private ImageIcon icon = createImageIcon("middle.png"); public JTabbedPaneDemo() { layoutComponents(); } private void layoutComponents() { int i = 0; JPanel jpanelFirst = new JPanel(); jTabbedPane.addTab(tabNames[i++], icon, jpanelFirst, "fitst"); jTabbedPane.setMnemonicAt(0, KeyEvent.VK_0); JLabel jLabel1 = new JLabel("选项卡1:"); jpanelFirst.add(jLabel1); JTextField jTextField1 = new JTextField(20); jTextField1.setText("测试选项卡1"); jpanelFirst.add(jTextField1); JButton jButton1 = new JButton("提交"); jButton1.addActionListener((ActionEvent e) -> { JFrame jFrame = new JFrame(); JLabel jLabel = new JLabel(); jLabel.setIcon(icon); jFrame.add(jLabel); JOptionPane.showMessageDialog(jFrame, "提交成功!!!", "选项卡1提交", JOptionPane.INFORMATION_MESSAGE); }); jpanelFirst.add(jButton1); JPanel jpanelSecond = new JPanel(); // 加入第2个页面 jTabbedPane.addTab(tabNames[i++], icon, jpanelSecond, "second"); // 设置快捷键为1 jTabbedPane.setMnemonicAt(1, KeyEvent.VK_1); JLabel jLabel2 = new JLabel("选项卡2:"); jpanelSecond.add(jLabel2); JTextField jTextField2 = new JTextField(20); jTextField2.setText("测试选项卡2"); jpanelSecond.add(jTextField2); JButton jButton2 = new JButton("提交"); jButton2.addActionListener((ActionEvent e) -> { JOptionPane.showMessageDialog(null, "提交成功!!!", "选项卡2提交", JOptionPane.INFORMATION_MESSAGE); }); jpanelSecond.add(jButton2); JPanel jpanel3 = new JPanel(); jTabbedPane.addTab(tabNames[i++], icon, jpanel3, "第三个"); jTabbedPane.setMnemonicAt(2, KeyEvent.VK_2); String[] columsNames = {"序号", "姓名", "语文", "数学", "英语", "总分", "操作"}; Object[][] rowData = { {1, "张三", 80, 80, 80, 240, null}, {2, "John", 70, 80, 90, 240, null}, {3, "Sue", 70, 70, 70, 210, null}, {4, "Jane", 80, 70, 60, 210, null}, {5, "Joe_05", 80, 70, 60, 210, null}, {6, "Joe_06", 80, 70, 60, 210, null}, {7, "Joe_07", 80, 70, 60, 210, null}, {8, "Joe_08", 80, 70, 60, 210, null}, {9, "Joe_09", 80, 70, 60, 210, null}, {10, "Joe_10", 80, 70, 60, 210, null}, {11, "Joe_11", 80, 70, 60, 210, null}, {12, "Joe_12", 80, 70, 60, 210, null}, {13, "Joe_13", 80, 70, 60, 210, null}, {14, "Joe_14", 80, 70, 60, 210, null}, {15, "Joe_15", 80, 70, 60, 210, null}, {16, "Joe_16", 80, 70, 60, 210, null}, {17, "Joe_17", 80, 70, 60, 210, null}, {18, "Joe_18", 80, 70, 60, 210, null}, {19, "Joe_19", 80, 70, 60, 210, null}, {20, "Joe_20", 80, 70, 60, 210, null} }; JTable table = new JTable(rowData, columsNames); // 设置表格内容颜色 table.setForeground(Color.BLACK); // 字体颜色 table.setFont(new Font(null, Font.PLAIN, 14)); // 字体样式 table.setSelectionForeground(Color.DARK_GRAY); // 选中后字体颜色 table.setSelectionBackground(Color.LIGHT_GRAY); // 选中后字体背景 table.setGridColor(Color.GRAY); // 设置行高 table.setRowHeight(30); // 第一列列宽设置为40 table.getColumnModel().getColumn(0).setPreferredWidth(40); // 设置滚动面板视口大小(超过该大小的行数据,需要拖动滚动条才能看到) table.setPreferredScrollableViewportSize(new Dimension(800, 300)); table.getColumnModel().getColumn(6).setCellRenderer(new MyButtonRender()); DefaultTableModel defaultTableModel = new DefaultTableModel(); defaultTableModel.addRow(new Object[]{3, "Sue", 70, 70, 70, 210, null}); JScrollPane jsp = new JScrollPane(table); jpanel3.add(jsp); setLayout(new GridLayout(1, 1)); add(jTabbedPane); } private ImageIcon createImageIcon(String path) { URL url = JTabbedPaneDemo.class.getResource(path); if (url == null) { System.out.println("the image " + path + " is not exist!"); return null; } return new ImageIcon(url); // return new ImageIcon("/Users/mt-mac/IdeaProjects/JavaGUI/src/main/java/com/java/gui/middle.png"); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame jFrame = new JFrame(); jFrame.setLayout(null); jFrame.setVisible(true); jFrame.setContentPane(new JTabbedPaneDemo()); jFrame.setSize(800, 800); }); } public class MyButtonRender implements TableCellRenderer { private JPanel jPanel; private JButton jButton; public MyButtonRender() { initButton(); initPanel(); jPanel.add(jButton); } private void initPanel() { jPanel = new JPanel(); jPanel.setLayout(null); } private void initButton() { jButton = new JButton(); jButton.setBounds(2, 3, 80, 30); jButton.addActionListener((ActionEvent e) -> { System.out.println("" + e.getActionCommand()); System.out.println(jButton.getText()); }); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { jButton.setText("编辑"); return jPanel; } } } ```
求助:用Java编写存取款程序,报错 $Exception in thread "main" 和java.lang.IllegalStateException: Scanner closed
package piggybank; import java.util.Scanner; public class piggybank { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Welcome to the Piggy Bank. Please enter starting balance: "); double startingBalance = input.nextDouble(); System.out.println("Piggy Bank ATM"); System.out.printf("Balance : %6.2f", startingBalance); System.out.println(); while (true){ System.out.println(); System.out.println("OPTIONS"); System.out.println(); System.out.println("1.Deposit\n"+"2.Withdraw\n"+"3.Quit\n"); System.out.println(); System.out.println("Choose one:"); int option = input.nextInt(); switch (option) { case 1: System.out.println("Enter deposit amount:\n" + "Piggy Bank ATM"); double deposit = input.nextDouble(); double depositBalance= startingBalance + deposit; System.out.printf(" Balance: $%6.2f ",depositBalance); System.out.println(); break; case 2: System.out.println("Enter withdrawal amount:\n" + "Piggy Bank ATM"); double withdraw = input.nextDouble(); double withdrawBalance= startingBalance - withdraw; System.out.printf("Balance:$%8.2f ",withdrawBalance); System.out.println(); break; case 3: System.out.printf("Ending Balance: $%8.2f ", startingBalance); break; } input.close(); } } } 我想要反复执行存取款程序,但是就会显示出错 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658326_406248.png) 求帮忙! 想要得到以下运行结果 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658512_523449.png) 我的运行结果是这样的,没有办法进行第二次输入 ![图片说明](https://img-ask.csdn.net/upload/201909/28/1569658741_470527.png) 呜呜呜,初学什么都不会,求助
问个有关django+heroku的问题
``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```
问个有关python+django+heroku的问题
``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```
在测试sql注入时,出现 Unknown column 'id' in 'where clause'错误,试了很多修改方法都不行
![图片说明](https://img-ask.csdn.net/upload/202002/04/1580746566_81510.png)![图片说明](https://img-ask.csdn.net/upload/202002/04/1580746575_798099.png)![图片说明](https://img-ask.csdn.net/upload/202002/04/1580746583_259652.png) ``` package com.bjsxt.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /*测试SQL执行语句,以及SQL注入问题 *试了很多修改方法都不行,比如:我在eclipse中把id改成整型int...,或把"5"的引号去掉,都不行。(String id = "5 or 1=1";是测试恶意数据的) * */ public class Demo02 { public static void main(String[] args){ try { //加载驱动类 Class.forName("com.mysql.jdbc.Driver"); //建立连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","admin"); Statement stmt = conn.createStatement(); ** **_ //测试sql注入 _**** String id = "5 or 1=1"; String sql = "delete from t_user where id="+id; stmt.execute(sql); /*试了很多修改方法都不行,比如:我在eclipse中把id改成整型int...,或把"5"的引号去掉,都不行。(String id = "5 or 1=1";是测试恶意数据的) 都不行!!* */ } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ```
Exception in thread "Thread-12" java.lang.RuntimeException: java.lang.NullPointerException
第一次着手项目,springboot+mybatis,项目搭建是跟着教程做的。项目搭建好之后项目能正常运行,但是启动后报: Exception in thread "Thread-12" java.lang.RuntimeException: java.lang.NullPointerException at com.mysql.jdbc.JDBC4Connection$1$1.run(JDBC4Connection.java:106) Caused by: java.lang.NullPointerException at com.mysql.jdbc.ConnectionImpl.abortInternal(ConnectionImpl.java:1240) at com.mysql.jdbc.JDBC4Connection$1$1.run(JDBC4Connection.java:104) 启动Console: 2019-08-05 10:29:12.921 INFO 7416 --- [ restartedMain] com.xintujiuzhang.aimanagement.App : Starting App on DESKTOP-J57CTN6 with PID 7416 (D:\JAVA\eclipse\TaxHandwritingRecognition\target\classes started by Administrator in D:\JAVA\eclipse\TaxHandwritingRecognition) 2019-08-05 10:29:12.921 INFO 7416 --- [ restartedMain] com.xintujiuzhang.aimanagement.App : No active profile set, falling back to default profiles: default 2019-08-05 10:29:12.958 INFO 7416 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6070b0bb: startup date [Mon Aug 05 10:29:12 CST 2019]; root of context hierarchy 2019-08-05 10:29:13.450 INFO 7416 --- [ restartedMain] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [mybatis-config.xml] 2019-08-05 10:29:13.503 INFO 7416 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'sqlSessionFactory' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=app; factoryMethodName=sqlSessionFactoryBean; initMethodName=null; destroyMethodName=(inferred); defined in com.xintujiuzhang.aimanagement.App] with [Generic bean: class [org.mybatis.spring.SqlSessionFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [mybatis-config.xml]] 2019-08-05 10:29:13.599 WARN 7416 --- [ restartedMain] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.xintujiuzhang.aimanagement]' package. Please check your configuration. 2019-08-05 10:29:13.958 INFO 7416 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b535b905] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-08-05 10:29:14.332 INFO 7416 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2019-08-05 10:29:14.348 INFO 7416 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-08-05 10:29:14.349 INFO 7416 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 2019-08-05 10:29:14.355 INFO 7416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5]. 2019-08-05 10:29:14.355 INFO 7416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. 2019-08-05 10:29:14.355 INFO 7416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] 2019-08-05 10:29:14.357 INFO 7416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018] 2019-08-05 10:29:14.418 INFO 7416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-08-05 10:29:14.418 INFO 7416 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1462 ms 2019-08-05 10:29:14.514 INFO 7416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2019-08-05 10:29:14.517 INFO 7416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2019-08-05 10:29:14.517 INFO 7416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2019-08-05 10:29:14.517 INFO 7416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2019-08-05 10:29:14.517 INFO 7416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2019-08-05 10:29:14.631 INFO 7416 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2019-08-05 10:29:19.625 INFO 7416 --- [ restartedMain] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (com.mysql.jdbc.JDBC4Connection.getNetworkTimeout()I) 2019-08-05 10:29:19.629 INFO 7416 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2019-08-05 10:29:19.670 INFO 7416 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2019-08-05 10:29:19.684 INFO 7416 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2019-08-05 10:29:19.738 INFO 7416 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.2.10.Final} 2019-08-05 10:29:19.739 INFO 7416 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2019-08-05 10:29:19.770 INFO 7416 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2019-08-05 10:29:19.874 INFO 7416 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2019-08-05 10:29:19.897 INFO 7416 --- [ restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 2019-08-05 10:29:20.037 INFO 7416 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 10:29:20,543 INFO App:32-org.springframework.orm.jpa.JpaTransactionManager 2019-08-05 10:29:20.796 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6070b0bb: startup date [Mon Aug 05 10:29:12 CST 2019]; root of context hierarchy 2019-08-05 10:29:20.824 WARN 7416 --- [ restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2019-08-05 10:29:20.846 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/application/handwriting_authorization],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ApplicationAuthorizationController.joinHWA(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.847 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/application/handwriting_information],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ApplicationInformationController.joinHWI(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.847 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/log/background_management_login],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.BackgroundManagementLoginController.joinHWI(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.847 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/log/computer_login],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ComputerLoginController.jumpDEM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.847 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/department_management],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.DepartmentManagementController.jumpDEM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.848 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/dictionary_management],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.DictionaryManagementController.jumpDM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.848 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/equipment/hardware_devices],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.EquipmentManagementController.jumpDM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.848 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryGetServerStatusInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.GetServerStatusInterfaceController.queryGetServerStatus(java.lang.String,java.lang.String) 2019-08-05 10:29:20.848 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryHandwritingInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.HandwritingInterfaceController.queryHandwriting(java.lang.String,java.lang.String,java.lang.Integer,java.util.Date) 2019-08-05 10:29:20.849 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/identity/identity_management],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.IdentityManagementController.jumpDM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.849 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryInstallationRequest],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.InstallationRequestInterfaceController.queryInstallationRequest(java.lang.String,java.lang.String,java.lang.String) 2019-08-05 10:29:20.849 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryLicenseInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.LicenseInterfaceController.queryLicense(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.util.Date) 2019-08-05 10:29:20.851 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.MainController.main(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.851 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView com.xintujiuzhang.aimanagement.controller.MainController.login() 2019-08-05 10:29:20.851 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.MainController.login(java.lang.String,java.lang.String,java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.851 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/main],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.MainController.jumpmain(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/menu_management],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.MenuManagementController.jumpMM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/log/module_browsing],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ModuleBrowsingController.jumpTM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/log/module_operation],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ModuleOperationController.jumpMM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/deletehandwriting],methods=[POST]}" onto public void com.xintujiuzhang.aimanagement.controller.NotesController.deletehandwriting(java.lang.String) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/updatehandwriting],methods=[POST]}" onto public void com.xintujiuzhang.aimanagement.controller.NotesController.updatehandwriting(com.xintujiuzhang.aimanagement.pojo.Handwriting) 2019-08-05 10:29:20.852 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/addhandwriting],methods=[POST]}" onto public void com.xintujiuzhang.aimanagement.controller.NotesController.addhandwriting(com.xintujiuzhang.aimanagement.pojo.Handwriting) 2019-08-05 10:29:20.853 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/querynotes],methods=[GET]}" onto public com.xintujiuzhang.aimanagement.pojo.Handwriting com.xintujiuzhang.aimanagement.controller.NotesController.querynotes(java.lang.String) 2019-08-05 10:29:20.853 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/parameter_settings],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.parameterSettingsController.jumpPS(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.853 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/role_authorization],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.RoleAuthorizationController.jumpRA(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.853 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/log/service_call],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.ServiceCallController.jumpRA(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.853 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/task_management],methods=[GET]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.TaskManagementController.jumpTM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.854 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/authority/user_management]}" onto public java.lang.String com.xintujiuzhang.aimanagement.controller.UserController.jnmpUM(java.util.Map<java.lang.String, java.lang.Object>) 2019-08-05 10:29:20.854 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryUserInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.UserInterfaceController.queryLicense(java.lang.String,java.lang.String,java.lang.Integer,java.util.Date) 2019-08-05 10:29:20.854 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryVersionCheckingInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.VersionCheckingInterfaceController.queryVersionChecking(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.Integer,java.util.Date) 2019-08-05 10:29:20.854 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/queryVersionupdateInterface],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.xintujiuzhang.aimanagement.controller.VersionUpdateInterfaceController.queryVersionupdate(java.lang.String,java.lang.String,java.lang.String,java.util.Date) 2019-08-05 10:29:20.857 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2019-08-05 10:29:20.857 INFO 7416 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2019-08-05 10:29:20.881 INFO 7416 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2019-08-05 10:29:20.881 INFO 7416 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2019-08-05 10:29:20.906 INFO 7416 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2019-08-05 10:29:21.115 INFO 7416 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2019-08-05 10:29:21.164 INFO 7416 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2019-08-05 10:29:21.165 INFO 7416 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure 2019-08-05 10:29:21.170 INFO 7416 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource] 2019-08-05 10:29:21.196 INFO 7416 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-08-05 10:29:21.198 INFO 7416 --- [ restartedMain] com.xintujiuzhang.aimanagement.App : Started App in 8.458 seconds (JVM running for 8.828) Exception in thread "Thread-12" java.lang.RuntimeException: java.lang.NullPointerException at com.mysql.jdbc.JDBC4Connection$1$1.run(JDBC4Connection.java:106) Caused by: java.lang.NullPointerException at com.mysql.jdbc.ConnectionImpl.abortInternal(ConnectionImpl.java:1240) at com.mysql.jdbc.JDBC4Connection$1$1.run(JDBC4Connection.java:104) **在执行一些方法后“Thread-12”会不断增加** **ps:“Thread-668"**
error: No resource identifier found for attribute 'compileSdkVersion' in package 'android' 找不到compileSdkVersion资源符
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:compileSdkVersion="23" android:compileSdkVersionCodename="6.0-2438415" android:installLocation="auto" package="com.QQ38441066.game" platformBuildVersionCode="23" platformBuildVersionName="6.0-2438415"> 这是代码 怎么解决
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
Linux(服务器编程):15---两种高效的事件处理模式(reactor模式、proactor模式)
前言 同步I/O模型通常用于实现Reactor模式 异步I/O模型则用于实现Proactor模式 最后我们会使用同步I/O方式模拟出Proactor模式 一、Reactor模式 Reactor模式特点 它要求主线程(I/O处理单元)只负责监听文件描述符上是否有事件发生,有的话就立即将时间通知工作线程(逻辑单元)。除此之外,主线程不做任何其他实质性的工作 读写数据,接受新的连接,以及处...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n
进程通信方式总结与盘点
​ 进程通信是指进程之间的信息交换。这里需要和进程同步做一下区分,进程同步控制多个进程按一定顺序执行,进程通信是一种手段,而进程同步是目标。从某方面来讲,进程通信可以解决进程同步问题。 ​ 首先回顾下我们前面博文中讲到的信号量机制,为了实现进程的互斥与同步,需要在进程间交换一定的信息,因此信号量机制也可以被归为进程通信的一种方式,但是也被称为低级进程通信,主要原因为: 效率低:一次只可操作少量的...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
听说了吗?阿里双11作战室竟1根网线都没有
双11不光是购物狂欢节,更是对技术的一次“大考”,对于阿里巴巴企业内部运营的基础保障技术而言,亦是如此。 回溯双11历史,这背后也经历过“小米加步枪”的阶段:作战室从随处是网线,交换机放地上的“一地狼藉”;到如今媲美5G的wifi网速,到现场却看不到一根网线;从当年使用商用AP(无线路由器),让光明顶双11当天断网一分钟,到全部使用阿里自研AP……阿里巴巴企业智能事业部工程师们提供的基础保障...
在阿里,40岁的奋斗姿势
在阿里,40岁的奋斗姿势 在阿里,什么样的年纪可以称为老呢?35岁? 在云网络,有这样一群人,他们的平均年龄接近40,却刚刚开辟职业生涯的第二战场。 他们的奋斗姿势是什么样的呢? 洛神赋 “翩若惊鸿,婉若游龙。荣曜秋菊,华茂春松。髣髴兮若轻云之蔽月,飘飖兮若流风之回雪。远而望之,皎若太阳升朝霞;迫而察之,灼若芙蕖出渌波。” 爱洛神,爱阿里云 2018年,阿里云网络产品部门启动洛神2.0升...
关于研发效能提升的思考
研发效能提升是最近比较热门的一个话题,本人根据这几年的工作心得,做了一些思考总结,由于个人深度有限,暂且抛转引入。 三要素 任何生产力的提升都离不开这三个因素:人、流程和工具,少了其中任何一个因素都无法实现。 人,即思想,也就是古人说的“道”,道不同不相为谋,是制高点,也是高层建筑的基石。 流程,即方法,也是古人说的“法”。研发效能的提升,也就是要提高投入产出比,既要增加产出,也要减...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆  每天早上8:30推送 作者| Mr.K   编辑| Emma 来源| 技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯
程序员该看的几部电影
##1、骇客帝国(1999) 概念:在线/离线,递归,循环,矩阵等 剧情简介: 不久的将来,网络黑客尼奥对这个看似正常的现实世界产生了怀疑。 他结识了黑客崔妮蒂,并见到了黑客组织的首领墨菲斯。 墨菲斯告诉他,现实世界其实是由一个名叫“母体”的计算机人工智能系统控制,人们就像他们饲养的动物,没有自由和思想,而尼奥就是能够拯救人类的救世主。 可是,救赎之路从来都不会一帆风顺,到底哪里才是真实的世界?
入职阿里5年,他如何破解“技术债”?
简介: 作者 | 都铎 作为一名技术人,你常常会听到这样的话: “先快速上线” “没时间改” “再缓一缓吧” “以后再解决” “先用临时方案处理” …… 当你埋下的坑越来越多,不知道哪天哪位同学就会踩上一颗雷。特别赞同“人最大的恐惧就是未知,当技术债可说不可见的时候,才是最让人不想解决的时候。” 作为一个程序员,我们反对复制粘贴,但是我们经常会见到相似的代码,相同的二方包,甚至整个代码...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布了 2019年国民经济报告 ,报告中指出:年末中国大陆总人口(包括31个
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
2020年的1月,我辞掉了我的第一份工作
其实,这篇文章,我应该早点写的,毕竟现在已经2月份了。不过一些其它原因,或者是我的惰性、还有一些迷茫的念头,让自己迟迟没有试着写一点东西,记录下,或者说是总结下自己前3年的工作上的经历、学习的过程。 我自己知道的,在写自己的博客方面,我的文笔很一般,非技术类的文章不想去写;另外我又是一个还比较热衷于技术的人,而平常复杂一点的东西,如果想写文章写的清楚点,是需要足够...
别低估自己的直觉,也别高估自己的智商
所有群全部吵翻天,朋友圈全部沦陷,公众号疯狂转发。这两周没怎么发原创,只发新闻,可能有人注意到了。我不是懒,是文章写了却没发,因为大家的关注力始终在这次的疫情上面,发了也没人看。当然,我...
Java坑人面试题系列: 包装类(中级难度)
Java Magazine上面有一个专门坑人的面试题系列: https://blogs.oracle.com/javamagazine/quiz-2。 这些问题的设计宗旨,主要是测试面试者对Java语言的了解程度,而不是为了用弯弯绕绕的手段把面试者搞蒙。 如果你看过往期的问题,就会发现每一个都不简单。 这些试题模拟了认证考试中的一些难题。 而 “中级(intermediate)” 和 “高级(ad
深度学习入门笔记(十八):卷积神经网络(一)
欢迎关注WX公众号:【程序员管小亮】 专栏——深度学习入门笔记 声明 1)该文章整理自网上的大牛和机器学习专家无私奉献的资料,具体引用的资料请看参考文献。 2)本文仅供学术交流,非商用。所以每一部分具体的参考资料并没有详细对应。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。 3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。 4)此属于第一版本,若有错误,还需继续修正与...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
节后首个工作日,企业们集体开晨会让钉钉挂了
By 超神经场景描述:昨天 2 月 3 日,是大部分城市号召远程工作的第一天,全国有接近 2 亿人在家开始远程办公,钉钉上也有超过 1000 万家企业活跃起来。关键词:十一出行 人脸...
Java基础知识点梳理
Java基础知识点梳理 摘要: 虽然已经在实际工作中经常与java打交道,但是一直没系统地对java这门语言进行梳理和总结,掌握的知识也比较零散。恰好利用这段时间重新认识下java,并对一些常见的语法和知识点做个总结与回顾,一方面为了加深印象,方便后面查阅,一方面为了学好java打下基础。 Java简介 java语言于1995年正式推出,最开始被命名为Oak语言,由James Gosling(詹姆
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
你也能看懂的:蒙特卡罗方法
蒙特卡罗方法,也称统计模拟方法,是1940年代中期由于科学技术的发展和电子计算机的发明,而提出的一种以概率统计理论为指导的数值计算方法。是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法 蒙特卡罗方法可以粗略地分成两类:一类是所求解的问题本身具有内在的随机性,借助计算机的运算能力可以直接模拟这种随机的过程。另一种类型是所求解问题可以转化为某种随机分布的特征数,比如随机事件出现的概率,或...
相关热词 c#开发的dll注册 c#的反射 c# grid绑定数据源 c#多线程怎么循环 c# 鼠标左键 c# char占位符 c# 日期比较 c#16进制转换为int c#用递归求顺序表中最大 c#小型erp源代码
立即提问