text
stringlengths 0
13M
|
---|
Title: Visual Studio 2017 can't connect to TFS 2017: LoadCachedCredentialsFormRegisterdProviders Method not found
Tags: visual-studio;tfs
Question: We are using Visual Studio 2017 & TFS 2017.
I have access to TFS web portal & TFS server (remote, share, db,..) & ... and everything works, but I can't connect with Visual Studio (just in my pc).
Error is:
```
```Server 'http://tfs:8080/tfs' was not added.```
```Method not found:```
```'Microsoft.VisualStudio.Services.Common.VssCredentials```
```Microsoft.VisualStudio.Services.Common.VssCredentials.LoadCachedCredentialsFromRegisteredProviders(System.Uri, Boolean ByRef)'.```
```
Firewall is Off
Antivirus is Disable
Remove All Credentials in Credential Manager
Check port access with telnet
VS Version is 15.5.6
TFS Version is 15.117.26714.0
Any advice?
Screenshot
Comment: Seems it's the VS issue, try to repair VS, or reset user data : `C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe /resetuserdata`. It that still not work, just try to install the [standalone Team Explorer 2017](https://blogs.msdn.microsoft.com/bharry/2017/04/05/team-explorer-for-tfs-2017/), then try it again.
Comment: So, it proves that it's an issue with the installation of VS 2017. I tested on my side, can not reproduce this issue. You can check if this issue occurs on other machines, also try to uninstall it completely then reinstall.
Comment: Have you resolved the issue?
Comment: I tried all of that!!
Comment: I try VS 2015 and can be connected without problem!
Comment: I try that. Uninstall > Restart > Install.
I probably have to reinstall Windows.
Comment: I could not solve the problem. I had to reinstall windows.
Comment: The problem was resolved only after the installation of Windows!
Here is another answer: I recently ran into this issue and after hours and hours of searching on the Internet, I found a post suggesting to install the Microsoft.TeamFoundationServer.ExtendedClient package from Nuget. I added this package to the project that connected to the TFS server and the error went away.
I should note that I tried pretty much everything else I found, including reinstalling VS2017 on my original machine, then installing VS2017 on a fresh VM and getting the same exact error.
|
Title: PGFPlots: point meta colormap index as fill value
Tags: tikz-pgf;pgfplots;color
Question: I have the following simple PGFPlots sample
```\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=0, xmax=1,
ymin=0, ymax=1,
width=7.5cm,
colorbar,
colormap={mymap}{[1pt]
rgb(0pt)=(0,0,0.5);
rgb(22pt)=(0,0,1);
rgb(25pt)=(0,0,1);
rgb(68pt)=(0,0.86,1);
rgb(70pt)=(0,0.9,0.967741935483871);
rgb(75pt)=(0.0806451612903226,1,0.887096774193548);
rgb(128pt)=(0.935483870967742,1,0.0322580645161291);
rgb(130pt)=(0.967741935483871,0.962962962962963,0);
rgb(132pt)=(1,0.925925925925926,0);
rgb(178pt)=(1,0.0740740740740741,0);
rgb(182pt)=(0.909090909090909,0,0);
rgb(200pt)=(0.5,0,0)
},
point meta min=12.0628665990324,
point meta max=98.5559785610705,
colorbar style={
ytick={20,30,40,50,60,70,80,90},
yticklabels={20,30,40,50,60,70,80,90}
}
]
\path [draw=black, fill=blue, opacity=0.4]
(axis cs:0.722443382570222,0.322958913853178)--
(axis cs:0.361788655622314,0.228263230878956)--
(axis cs:0.293714046388829,0.630976123854488)--
cycle;
\end{axis}
\end{tikzpicture}
\end{document}
```
and would like to fill the path with a value of the colormap, i.e., ```point meta```. How to?
Here is another answer: This requires direct access to the colormap functions of ```pgfplots```:
```\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=0, xmax=1,
ymin=0, ymax=1,
width=7.5cm,
colorbar,
colormap={mymap}{[1pt]
rgb(0pt)=(0,0,0.5);
rgb(22pt)=(0,0,1);
rgb(25pt)=(0,0,1);
rgb(68pt)=(0,0.86,1);
rgb(70pt)=(0,0.9,0.967741935483871);
rgb(75pt)=(0.0806451612903226,1,0.887096774193548);
rgb(128pt)=(0.935483870967742,1,0.0322580645161291);
rgb(130pt)=(0.967741935483871,0.962962962962963,0);
rgb(132pt)=(1,0.925925925925926,0);
rgb(178pt)=(1,0.0740740740740741,0);
rgb(182pt)=(0.909090909090909,0,0);
rgb(200pt)=(0.5,0,0)
},
point meta min=12.0628665990324,
point meta max=98.5559785610705,
colorbar style={
ytick={20,30,40,50,60,70,80,90},
yticklabels={20,30,40,50,60,70,80,90}
}
]
\path [
/utils/exec={
% map linearly from [0:1000] into the colormap. 500 is in the
% middle:
\pgfplotscolormapdefinemappedcolor{500}
},
draw=black, fill=mapped color]
(0,0)-- (0.5,0.2) -- (0,0.4) -- cycle;
\path [
/utils/exec={
\pgfplotsset{colormap access=direct}
% direct access using an index. Yours has 201 elements:
\pgfplotscolormapdefinemappedcolor{127}
},
draw=black, fill=mapped color]
(0.722443382570222,0.322958913853178)--
(0.361788655622314,0.228263230878956)--
(0.293714046388829,0.630976123854488)--
cycle;
\end{axis}
\end{tikzpicture}
\end{document}
```
Since there is currently no key of sorts "use color map value", you have to resort to the macro which defines ```mapped color``` as outlined above. I used ```/utils/exec```, a way of PGF which allows you to invoke a macro in a context where key-value pairs are expected.
Here is another answer: As with the release of PGFPlots v1.13 you can use the new keys ```color of colormap``` or ```index of colormap``` to get easy access to the colors of the colormap. See section 4.7.6 pages 192f in the manual.
```\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=0, xmax=1,
ymin=0, ymax=1,
width=7.5cm,
colorbar,
colormap={mymap}{[1pt]
rgb(0pt)=(0,0,0.5);
rgb(22pt)=(0,0,1);
rgb(25pt)=(0,0,1);
rgb(68pt)=(0,0.86,1);
rgb(70pt)=(0,0.9,0.967741935483871);
rgb(75pt)=(0.0806451612903226,1,0.887096774193548);
rgb(128pt)=(0.935483870967742,1,0.0322580645161291);
rgb(130pt)=(0.967741935483871,0.962962962962963,0);
rgb(132pt)=(1,0.925925925925926,0);
rgb(178pt)=(1,0.0740740740740741,0);
rgb(182pt)=(0.909090909090909,0,0);
rgb(200pt)=(0.5,0,0)
},
point meta min=12.0628665990324,
point meta max=98.5559785610705,
colorbar style={
ytick={20,30,40,50,60,70,80,90},
yticklabels={20,30,40,50,60,70,80,90},
}
]
\path [color of colormap=500,draw=.!80!black, fill=., opacity=0.4]
(0,0)-- (0.5,0.2) -- (0,0.4) -- cycle;
\path [index of colormap=128,draw=.!80!black, fill=., opacity=0.4]
(0.722443382570222,0.322958913853178) --
(0.361788655622314,0.228263230878956) --
(0.293714046388829,0.630976123854488) --
cycle;
\end{axis}
\end{tikzpicture}
\end{document}
```
|
Title: TFS Build Definition Issue
Tags: tfs;build;tfsbuild
Question: I am trying to create a build definition using TFS 2012.
I have set up the drop folder as local machine folder.
It creates drop folder and copy the dlls only when I do a get latest in TFS.
Can anyone please suggst how to copy the components to a drop folder in local machine automatically?(without doing get latest)
Here is another answer: If the "Copy build output to the following drop folder (UNC path, such \server\share)" is selected in the build definition, when queue a new build, build output files (.exe, .dll) and some log files are copied to the UNC folder. That is, the files are not copied during the Get Latest process.
|
Title: Performing multiple tasks at the same time in Python
Tags: python;selenium
Question: The following code can download one file from one given url at a time:
```from selenium import webdriver
with open("url_lists.txt","r") as fi: ###The text file contains hundreds of urls
urls = fi.read().splitlines()
for url in urls:
browser = webdriver.Firefox()
browser.get(url)
browser.find_element_by_id('download').click()
```
I want to modify the code so that 5 urls are open simultaneously by 5 different browsers, and download all the 5 files at a time.
How can I accomplish it?
Comment: If my answer solves your problem, please confirm it. Thanks!
Here is the accepted answer: You can use ```threading```.
```#!/usr/bin/env python
#-*- coding:utf-8 -*-
from selenium import webdriver
from threading import Thread
with open("url_lists.txt","r") as fi: ###The text file contains hundreds of urls
urls = fi.read().splitlines()
def func(url, bro):
browserFunc = getattr(webdriver, bro, webdriver.Firefox)
browser = browserFunc()
browser.get(url)
browser.find_element_by_id('download').click()
t = []
urls = [1,2,3,4,5]
bros = [1,2,3,4,5]
for i in range(len(urls)):
t.append(Thread(target=func, args=[urls[i], bros[i]]))
for i in t:
t.start()
for i in t:
t.join()
if __name__ == '__main__':
a = test1()
```
Comment for this answer: Sorry, I don't get your point. You mean download from 5 urls from one browsers?Or?
Comment for this answer: How can I control resources and download only, for example, 5 urls at one time?
Comment for this answer: I mean downloading from 5 urls using ONLY 5 browsers at a time.
Here is another answer: Use can use gevent for this:
```from gevent import monkey
monkey.patch_all()
from gevent import spawn, joinall
from selenium import webdriver
def worker(url, worker_number):
browser = webdriver.Firefox()
print 'worker #%s getting "%s"' % (worker_number, url)
browser.get(url)
print 'worker #%s got "%s"' % (worker_number, url)
if __name__ == '__main__':
print 'start'
fh = open('url_lists.txt', 'rb')
joinall([spawn(worker, url.strip(), i) for i, url in enumerate(fh.readlines())])
fh.close()
print 'stop'
```
This example will spawn as many threads (workers) as urls in the file. So if your file has too many urls it's better to use queues or pool of LIMIT number of workers to control resources and download only, for example, 50 urls at one time.
|
Title: GlassFish V3 is not creating ConnectionPool and JDBC resources for Postgresql while deploying the application
Tags: glassfish-3
Question: When i deploy my EE application, jdbc resources are not being created. when i deploy my application in glassfish v2.x resources were created and application was deployed properly.
I copied the postgresql jar file in galssfish --> ext folder and i have changed the provider to Eclipse in Pesistence.xml
```<provider> org.eclipse.persistence.jpa.PersistenceProvider </provider>
```
When i deploy the application, I am getting exception like:
```SEVERE: Invalid resource : jdbc/demo7-datasource__pm
org.glassfish.deployment.common.DeploymentException: Invalid resource : jdbc/demo7-datasource__pm
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:166)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:870)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1067)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1247)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:465)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:222)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:234)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: Invalid resource : jdbc/demo7-datasource__pm
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:539)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupPMResource(ConnectorRuntime.java:468)
at org.glassfish.persistence.common.PersistenceHelper.lookupPMResource(PersistenceHelper.java:63)
at org.glassfish.persistence.jpa.ProviderContainerContractInfoBase.lookupDataSource(ProviderContainerContractInfoBase.java:71)
at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:108)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:154)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:119)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:213)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:220)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:166)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:870)
at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:290)
at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:86)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:141)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:138)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:215)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:224)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:250)
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:138)
... 29 more
Caused by: com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Invalid resource : jdbc/demo7-datasource__pm
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl$MyDataSource.validateResource(ConnectorResourceAdminServiceImpl.java:272)
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl$MyDataSource.setResourceInfo(ConnectorResourceAdminServiceImpl.java:253)
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl.lookupDataSourceInDAS(ConnectorResourceAdminServiceImpl.java:243)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:537)
... 48 more
SEVERE: Exception while preparing the app : Invalid resource : jdbc/demo7-datasource__pm
java.lang.RuntimeException: Invalid resource : jdbc/demo7-datasource__pm
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:539)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupPMResource(ConnectorRuntime.java:468)
at org.glassfish.persistence.common.PersistenceHelper.lookupPMResource(PersistenceHelper.java:63)
at org.glassfish.persistence.jpa.ProviderContainerContractInfoBase.lookupDataSource(ProviderContainerContractInfoBase.java:71)
at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:108)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:154)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:119)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:213)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:220)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:166)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:870)
at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:290)
at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:86)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:141)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:138)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:215)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:224)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:250)
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:138)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:870)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1067)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1247)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:465)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:222)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:234)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Invalid resource : jdbc/demo7-datasource__pm
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl$MyDataSource.validateResource(ConnectorResourceAdminServiceImpl.java:272)
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl$MyDataSource.setResourceInfo(ConnectorResourceAdminServiceImpl.java:253)
at com.sun.enterprise.connectors.service.ConnectorResourceAdminServiceImpl.lookupDataSourceInDAS(ConnectorResourceAdminServiceImpl.java:243)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:537)
... 48 more
```
what sort of the things need to do for creating jdbc resources?
Here is the accepted answer: You need to provide the resource config either by setting up a connection pool and associated jdbc resource in the admin gui or with a glassfish-resources.xml.
See https://blogs.oracle.com/JagadishPrasath/entry/application_scoped_resources_in_glassfish
Comment for this answer: Additionally, in your persistence.xml, use the correct JNDI name. For the error given above, the correct name would be `java:app/jdbc/demo7-datasource`. Note the 'java:app/' prefix for application-scoped resources.
Comment for this answer: Maven should automatically package this inside the ear file. The file should be located in the ear project's resources/META-INF folder. It sounds like you may not have it in the correct location or you've got some options in your ear pom.xml that are incorrect.
Comment for this answer: I have defined the connectionpool and jndi name in sun-resources.xml. but ear file is not packing the this sun-resources.xml even i renamed to glassfish-resources.xml but no use. can you suggest anything on this.
Comment for this answer: Actually my application is maven based EE application. framework is jsf2.0 IDE netbeans applicationServer Glassfish v3.1
Here is another answer:
Start server.
Go to localhost:4848.
Configure your jdbc-pool and dont forget to put postgres.jdbc to your ```glassfish/glassfish/domain/your_domain/lib/ext```
|
Title: JQuery Multi File event not firing
Tags: javascript;jquery-plugins
Question: I have the following code in aspx
```<input id="fileControl" type="file" class="multi" name="fileControl"/>
```
and
``` $(document).ready(function () {
var fileSelections = [];
$('#fileControl').MultiFile({
onFileAppend: function () {
//$('#F9-Log').append('<li>onFileAppend - '+value+'</li>')
fileSelections.push(value);
},
onFileSelect: function () {
fileSelections.push();
},
afterFileSelect: function () {
fileSelections.push();
},
afterFileAppend: function () {
fileSelections.push();
}
});
});
```
I have added the following files as part of jQuery multifile plugin
```jquery.MetaData.js
jquery.MultiFile.js
jquery.MultiFile.pack.js
```
But when I add or remove a file the events are not fired. Why is this?
Here is another answer: I ran into this same issue and the problem is that if you want to subscribe to events, you can't set the class in the input element.
So, your input element should look like this:
```<input id="fileControl" type="file" name="fileControl"/>```
Then it should work.
I imagine this isn't an issue for you anymore, but in case this is ever needed by anyone else.
Here is another answer: Just seen this.... have updated the documentation accordingly
http://www.fyneworks.com/jquery/multiple-file-upload/
I can hardly find the time to keep the docs up to date, but this is a huge issue (the reason behind most support queries I receive) so thanks for pointing it out!
|
Title: copying python packages from normal user folder to root folder
Tags: linux;python
Question: I have a python script that runs through service autorun when it starts, it displays an import error. then I decided to run my script with sudo python3 main.py to make sure it would work, but it didn't work again. only works if I just run the script via python3 main.py
then i compared pip3 list and sudo pip3 list they were different. I tried using the python3 -m site command to find out where the packages of both users are located, I tried to copy from the usual one to the root, but it did not work because there is no path for the root user
here are the findings of the python site:
```sys.path = [
'/home/gleb',
'/usr/lib/python310.zip',
'/usr/lib/python3.10',
'/usr/lib/python3.10/lib-dynload',
'/home/gleb/.local/lib/python3.10/site-packages',
'/usr/lib/python3.10/site-packages',
]
USER_BASE: '/home/gleb/.local' (exists)
USER_SITE: '/home/gleb/.local/lib/python3.10/site-packages' (exists)
ENABLE_USER_SITE: True
```
for root
```sys.path = [
'/root',
'/usr/lib/python310.zip',
'/usr/lib/python3.10',
'/usr/lib/python3.10/lib-dynload',
'/usr/lib/python3.10/site-packages',
]
USER_BASE: '/root/.local' (exists)
USER_SITE: '/root/.local/lib/python3.10/site-packages' (doesn't exist)
ENABLE_USER_SITE: True
```
How can I transfer these packages without downloading them again
|
Title: Solr 8.0.0 Delta import Issue
Tags: solr
Question: The delta import is not working. No new records get indexed. posting_id is a unique id for each record.
```<dataConfig>
<dataSource type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
batchSize="-1"
autoReconnect="true"
socketTimeout="0"
connectTimeout="0"
encoding="UTF-8"
url="jdbc:mysql://xxx.xxx.xxx.xx:3306/news?zeroDateTimeBehavior=convertToNull"
user="admin"
password="admin"/>
<document>
<!--<entity name="news10" query="select * from news10"
deltaQuery="select posting_id from item where last_modified > '${dataimporter.last_index_time}'">
</entity>-->
<entity name="news10" pk="posting_id"
query="SELECT * FROM news10"
deltaImportQuery="SELECT * FROM news10
WHERE posting_id = '${dataimporter.delta.posting_id}'"
deltaQuery="SELECT posting_id FROM news10
WHERE last_modified > '${dataimporter.last_index_time}'">
</entity>
</document>
</dataConfig>
```
Comment: https://stackoverflow.com/questions/21580331/solr-delta-import-not-working
Comment: https://stackoverflow.com/questions/31110290/solr-delta-import-does-not-working-but-full-import-working-fine
|
Title: Why does Multiplying a column stochastic matrix with a vector that sums to one result in vector that again has sum one
Tags: matrix;multiplication;stochastic
Question: Suppose I have a ```nxn``` coulmn stochastic matrix. If I multiply it by a vector of length ```n``` that has elements that sum to one I get a resultant vector of length ```n``` that again sums to one Why does this happen? What if I give the vector of lenght ```n``` sum =0.8 or some 1.2?
Edit:
What happens if one of the columns of the matrix dosent add up to 1?
Here is another answer: Consider matrix ```B=4x4``` and vector ```A=4x1```. Now when we are calculating the output vector sum it can be broken as
```a1*(b11+b21+b31+b41)+a2*(b12+b22+b32+b42)+a3*(b13+b23+b33+b43)+a4*(b14+b24+b34+b44)
```
Now since all columns sum to 1 since it's column stochastic the
```sum=a1*1+a2*1+a3*1+a4*1=1
```
since the vector was 1. Now if one of the cols is not 1 we will have that column's contribution reduced for the jth entry of vector A. For eg. if
```b13+b23+b33+b43=0.8
```
then
```sum=a1*1+a2*1+a3*(0.8)+a4*1=a1*1+a2*1+a3*1+a4*1 -0.2*a3
```
So there is a leak of ```-0.2a*3``` from the original sum of 1
|
Title: Unable to make the arrow tip longer
Tags: html;css
Question: As you can see when you run the snippet below, The "outer" arrow that currently wraps 5 smaller arrows dont look alot the smaller once.
I know this is the line I have to modify, but no matter what I do, I can't achieve the desired result.
```background: linear-gradient(var(--c), var(--c)) 20px 0 /calc(100% - 40px) 100% no-repeat, linear-gradient(to bottom right, var(--c) 50%, transparent 50.5%) 100% 100%/20px 51% no-repeat, linear-gradient(to top right, var(--c) 50%, transparent 50.5%) 100% 0/20px 51% no-repeat, linear-gradient(to top left, var(--c) 50%, transparent 50.5%) 0 100%/20px 51% no-repeat, linear-gradient(to bottom left, var(--c) 50%, transparent 50.5%) 0px 0/20px 51% no-repeat;
```
Style whise I want the "outer" arrow to look like the last arrow. as you can see the start and end of the "outer" arrow is not that "pointy"
```.phases {
width: 1000px;
}
.breadcrumb {
list-style: none;
overflow: hidden;
font: 18px Sans-Serif;
margin: 0;
padding: 32px 0;
}
.breadcrumb li {
float: left;
margin-right: -15px;
}
.breadcrumb li:first-child {
margin-left: -20px;
}
.breadcrumb li a {
color: white;
text-decoration: none;
padding: 20px 40px;
--c: #004c89;
background: linear-gradient(var(--c), var(--c)) 20px 0 /calc(100% - 40px) 100% no-repeat, linear-gradient(to bottom right, var(--c) 50%, transparent 50.5%) 100% 100%/20px 51% no-repeat, linear-gradient(to top right, var(--c) 50%, transparent 50.5%) 100% 0/20px 51% no-repeat, linear-gradient(to top left, var(--c) 50%, transparent 50.5%) 0 100%/20px 51% no-repeat, linear-gradient(to bottom left, var(--c) 50%, transparent 50.5%) 0 0/20px 51% no-repeat;
position: relative;
float: left;
}
.breadcrumb li a:hover {
--c: #0078d7;
}
.breadcrumb_wrapper {
margin-left: 42px;
position: relative;
}
.breadcrumb_wrapper:before {
content: "";
position: absolute;
top: 0px;
bottom: 0px;
left: -32px;
right: 0;
--c:#e0dad7;
background: linear-gradient(var(--c), var(--c)) 20px 0 /calc(100% - 40px) 100% no-repeat, linear-gradient(to bottom right, var(--c) 50%, transparent 50.5%) 100% 100%/20px 51% no-repeat, linear-gradient(to top right, var(--c) 50%, transparent 50.5%) 100% 0/20px 51% no-repeat, linear-gradient(to top left, var(--c) 50%, transparent 50.5%) 0 100%/20px 51% no-repeat, linear-gradient(to bottom left, var(--c) 50%, transparent 50.5%) 0px 0/20px 51% no-repeat;
}
.breadcrumb_wrapper .breadcrumb {
padding: 0;
margin-bottom: 30px;
}
.breadcrumb_wrapper span {
color: white;
display: block;
position: relative;
text-align: center;
padding: 5px 0;
}
.breadcrumb_wrapper ul li:last-child {
margin-right: 20px;
}
.firsta {
margin-top: 29px;
}```
```<div class="phases">
<ul class="breadcrumb">
<li><a href="Pre-project.aspx" class="firsta">Pre-project</a></li>
<li class="breadcrumb_wrapper">
<span>Implementation project</span>
<ul class="breadcrumb">
<li><a href="Analysis.aspx">Analysis</a></li>
<li><a href="Design.aspx">Design</a></li>
<li><a href="Development.aspx">Development</a></li>
<li><a href="Implementation.aspx">Implementation</a></li>
<li><a href="Operation.aspx">Operation</a></li>
</ul>
</li>
</ul>
</div>```
Comment: you could also aks on the previous question and i told you how to do ;) no need to a whole question to ask clarification for code you got from a previous question
Here is the accepted answer:
```.phases {
width: 1000px;
}
.breadcrumb {
list-style: none;
overflow: hidden;
font: 18px Sans-Serif;
margin: 0 0 0 7px;
padding: 32px 0;
}
.breadcrumb li {
float: left;
margin-right: -15px;
}
.breadcrumb li:first-child {
margin-left: -20px;
}
.breadcrumb li a {
color: white;
text-decoration: none;
padding: 20px 40px;
--c: #004c89;
background: linear-gradient(var(--c), var(--c)) 20px 0 /calc(100% - 40px) 100% no-repeat, linear-gradient(to bottom right, var(--c) 50%, transparent 50.5%) 100% 100%/20px 51% no-repeat, linear-gradient(to top right, var(--c) 50%, transparent 50.5%) 100% 0/20px 51% no-repeat, linear-gradient(to top left, var(--c) 50%, transparent 50.5%) 0 100%/20px 51% no-repeat, linear-gradient(to bottom left, var(--c) 50%, transparent 50.5%) 0 0/20px 51% no-repeat;
position: relative;
float: left;
}
.breadcrumb li a:hover {
--c: #0078d7;
}
.breadcrumb_wrapper {
margin-left: 50px;
position: relative;
}
.breadcrumb_wrapper:before {
content: "";
position: absolute;
top: 0px;
bottom: 0px;
left: -32px;
right: 0;
--c:#e0dad7;
background: linear-gradient(var(--c), var(--c)) 30px 0 /calc(100% - 62px) 100% no-repeat, linear-gradient(to bottom right, var(--c) 50%, transparent 50.5%) 100% 100%/32px 51% no-repeat, linear-gradient(to top right, var(--c) 50%, transparent 50.5%) 100% 0/32px 51% no-repeat, linear-gradient(to top left, var(--c) 50%, transparent 50.5%) 0 100%/32px 51% no-repeat, linear-gradient(to bottom left, var(--c) 50%, transparent 50.5%) 0px 0/32px 51% no-repeat;
}
.breadcrumb_wrapper .breadcrumb {
padding: 0;
margin-bottom: 30px;
}
.breadcrumb_wrapper span {
color: white;
display: block;
position: relative;
text-align: center;
padding: 5px 0;
}
.breadcrumb_wrapper ul li:last-child {
margin-right: 43px;
}
.firsta {
margin-top: 29px;
}```
```<div class="phases">
<ul class="breadcrumb">
<li><a href="Pre-project.aspx" class="firsta">Pre-project</a></li>
<li class="breadcrumb_wrapper">
<span>Implementation project</span>
<ul class="breadcrumb">
<li><a href="Analysis.aspx">Analysis</a></li>
<li><a href="Design.aspx">Design</a></li>
<li><a href="Development.aspx">Development</a></li>
<li><a href="Implementation.aspx">Implementation</a></li>
<li><a href="Operation.aspx">Operation</a></li>
</ul>
</li>
</ul>
</div>```
Comment for this answer: i know what you have done because this is my code :) but you need to explain what you have done in the answer ... a code only answer is not a good answer even if it fixes the OP issue
Comment for this answer: @TemaniAfif i just adjusted the size and position attributes in the background properties.
|
Title: In Flutter, Dependencies must specify version number?
Tags: dart;flutter
Question: Typically, you have to add something like
```dependencies:
camera: "^0.2.0"
```
to the pubspec.yaml file. What happens if I don't include the version number? It's a small thing, but usually, I find a piece of code and want to test it. At the top, I see something like >>
```import 'package:camera/camera.dart';
```
Do I have to go to the package's homepage to find the version number?
Here is the accepted answer: You can use ```any```
```dependencies:
camera: any
```
Having tighter constraints makes it easier for ```packages get```/```packages upgrade``` to search matching versions because it reduces the solution space, but for simple examples it usually doesn't matter.
```pub``` got an improved solver recently that makes ```any``` much less of a problem than it used to be where ```pub``` often just timed out when ```any``` was used.
Comment for this answer: Thanks @Günter Zöchbauer
Comment for this answer: Note: You can also use git links.
Here is another answer: as per https://www.dartlang.org/tools/pub/dependencies
```
Based on what data you want to provide, you can specify dependencies
in two ways. The shortest way is to just specify a name:
```
```dependencies:
transmogrify:
```
```
This creates a dependency on transmogrify that allows any version,
and looks it up using the default source, which is pub.dartlang.org.
To limit the dependency to a range of versions, you can provide a
version constraint:
```
dependencies:
transmogrify: ^1.0.0
```
This creates a dependency on transmogrify using the default source and
allowing any version from 1.0.0 to 2.0.0 (but not including 2.0.0).
See Version constraints and Caret syntax for details on the version
constraint syntax.
```
I guess that the real answer to my question is that usually, it's best to specify a major version number ratio e.g.: ^1.0.0 == 1.0.0 < 2.0.0. This is to say that this program works and is tested and will keep working with this library dependancy so long as there are no major changes.
Comment for this answer: @AliAzad Yes, `transmogrify:` will use the last version.
Comment for this answer: Is this mean, dependencies: transmogrify: will use the last version of this package?
|
Title: Error TF31004 connecting VS2012 to TFS
Tags: visual-studio-2012;tfs
Question: I am trying to setup a new connection to TFS with VS2012. Early on I was able to add my TFS server and, using the Microsoft Git Provider, clone a copy of the remote repository from within Visual Studio. Later, as I was fiddling with things in Team Explorer trying to find the branch I wanted to use, something broke. My local repository remains, but my connection to the remote repository was somehow corrupted, as evidenced with this error:
```
TF31004: Unexpected error encountered while connecting to Team Foundation Server at http: //my.server.com:8080/tfs. Wait a few minutes and try again. If the problem persists, contact the server administrator ok help
```
Things I have tried to resolve this:
Wait and try again (as the error message suggested).
Restart Visual Studio.
Reboot my machine.
Reboot TFS server.
Use system restore to revert back before I installed msysgit and Microsoft Git Provider, or had attempted to connect to the TFS server.
Review the MSDN help for the error (see below).
Search Stack Overflow (found one other related issue but did not seem to apply).
Tried devenv /ResetSkipPkgs
Tried devenv /setup
Re-install Team Explorer for VS2012.
Clear IE cookies (per this post).
Clear TFS caches (per this post).
The help page offers these tidbits, but none of them seem likely given that I had, as I said, the connection working at one point:
The version of Team Foundation running on the local computer does not match the version running on the Team Foundation Server server {name}.
The server returned HTML content instead of XML content.
The required Web service on the server could not be found.
Any ideas would be appreciated!
Comment: You said you're using the git provider - is this the Visual Studio Tools for Git extension? If so, have you got the latest version installed? Also are you connecting to the hosted TFService and a git repository on the server or are you using tf-git with TFVC?
Comment: Yes, the git provider is from Visual Studio for Git, version 780-626-5613, installed yesterday. As to your last question, I am not quite sure but I believe it is the former (i.e. *not* using tf-git or TFVC, as I have not heard of those before :-).
Here is another answer: I have had an exactly the same problem.
My solution was to clear all the credentials in the Windows Vault (Credential Manager residing in the Control Panel).
I have no idea why the credentials did get messed up.
Comment for this answer: @Bill Hey. I too have the same problem. Can you tell me where to change the settings from ??
Comment for this answer: This worked for me, although I did not need to clear all the credentials in the Windows Vault. All that I needed to do was remove the entry for the server I was trying to connect to. I had reinstalled the server and kept the same name - that probably caused my credentials to get messed up
Comment for this answer: I had to clear two settings, one was for the git:http://tfs_server... and the other just the plain http://tfs_server. Than I had to reboot Visual Studio. After that, I was able to connect. +1
|
Title: ClearCase label parent folders of a file
Tags: batch-file;clearcase
Question: With a given file path, how to label all parent folders until the VOB level?
for example, file path: \VOB1\dir1\subdir1\moredir1\file1.xml
The following elements I want to be labelled with LABEL1:
```\VOB1\dir1\subdir1\moredir1\file1.xml
\VOB1\dir1\subdir1\moredir1
\VOB1\dir1\subdir1
\VOB1\dir1
```
With mklabel command, easy to do:
```cleartool mklabel LABEL1 \VOB1\dir1\subdir1\moredir1\file1.xml \VOB1\dir1\subdir1\moredir1 \VOB1\dir1\subdir1 \VOB1\dir1
```
However, I want the paths to be calculated intelligently.
The parameter of mklabel -rec don't suit this purpose because the top parent folder may containt lots of other files/dirs.
Any ideas?
Here is the accepted answer: ```@echo off
setlocal EnableDelayedExpansion
set "filePath=\VOB1\dir1\subdir1\moredir1\file1.xml"
set "wantedParent=VOB1"
set "thisPath="
set "labelPaths="
set "labelThisPath="
if "%filePath:~0,1%" equ "\" set "filePath=%filePath:~1%"
for %%a in ("%filePath:\=" "%") do (
set "thisPath=!thisPath!\%%~a"
if defined labelThisPath (
set "labelPaths=!thisPath! !labelPaths!"
) else if "%%~a" equ "%wantedParent%" (
set "labelThisPath=true"
)
)
ECHO cleartool mklabel %labelPaths%
```
Output:
```cleartool mklabel \VOB1\dir1\subdir1\moredir1\file1.xml \VOB1\dir1\subdir1\moredir1 \VOB1\dir1\subdir1 \VOB1\dir1
```
Here is another answer: Since there is no native way to get the list of parent folders (unless ```cleartool lsfolder -ancestor``` works), you would simply 'cd ..' until mklabel fails (which would mean you are outside of the vob)
```cleartool mklabel LABEL1 . || exit
cd ..
```
In bash:
```while true; do cleartool mklabel LABEL1 . || exit; cd ..; done
```
|
Title: How do i display an image when a variable reach a certain value?
Tags: javascript;image;if-statement
Question: So far i have made it so that when the variable "poeng" reaches a value over 12 it shows the message "Hello World", but what if i want it to display an image?
The HTML
5
7
+5
The coding (javascript)
```var poeng = 0;
function myFunction() {
poeng = 5;
console.log(poeng)
check()
}
function myFunction2() {
poeng = 7;
console.log(poeng)
check()
}
function myFunction3() {
poeng = poeng + 5;
console.log(poeng)
check()
}
function check() {
if(poeng > 12) {
console.log("Hello World");
//here i want it to display an image
}
}
```
Comment: You have to create the Image element (see `document.createElemen()` [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)), set its attributes and append it to the DOM (see `ParentNode.append()` [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append))
Comment: Unhide an HTML element? Create and append an HTML element to the page? There are many ways this could be implemented.
Here is the accepted answer: To display an image instead of just outputting to the console, you have to create an ```<img>``` element, add it's ```alt``` and ```src``` attributes and then append it to an element inside your page.
Here's an example. The image is created with a little helper function and appended to the ```<body>``` element inside the ```check()``` function:
```var poeng = 0;
var imgURL = 'https://fillmurray.com/1000/645'; // <-- URL of the image, using a placeholder service for now
// --- Image creation helper
function createImage(url) {
var imgEl = document.createElement('img'); // <-- create an <img> node/element
imgEl.alt = ''; // <-- add an alt-attribute
imgEl.src = url; // <-- add it's source
return imgEl; // <-- return the <img> to the caller
}
function myFunction() {
// ... elided for brevity ...
}
function myFunction2() {
// ... elided for brevity ...
}
function myFunction3() {
// ... elided for brevity ...
}
function check() {
if(poeng > 12) {
console.log("Hello World");
//here i want it to display an image
var imgEl = createImage(imgURL); // <-- create the <img>
document.body.appendChild(imgEl); // <-- add it to the <body> element
}
}
```
Comment for this answer: Thank you David! I am really new to Javascript so it is nice that people like you are kind enough to help me with stuff like this.
|
Title: Can't reduce whitespaces, remove accent, and replace words in R
Tags: r;stringr
Question: I have the following data frame :
```structure(list(matching_var = c("BD Mymensingh", "CN Nei Mongol ", "EC Los Ríos", "MY Johor", "MY Kedah", "MY Kelantan", "MY Negeri Sembilan", "RU Amurskaja oblast")), row.names = c(44L,174L, 259L, 694L, 695L, 696L, 700L, 1029L), class = "data.frame")
```
I would like it to become :
```structure(list(matching_var = c("BD Mymensingh", "CN Nei Mongol", "EC Los Rios", "MY Johor", "MY Kedah", "MY Kelantan", "MY Negeri Sembilan", "RU Amur")), row.names = c(44L, 174L, 259L, 694L, 695L, 696L, 700L, 1029L), class = "data.frame")
```
I tried the following code, but it does not work :
```library(dplyr)
library(stringr)
data <- data %>%
mutate(matching_var = str_replace(matching_var, "MY Johor", "MY Johor")) %>%
mutate(matching_var = str_replace(matching_var, "Los Ríos", "Los Rios"))%>%
mutate(matching_var = str_replace(matching_var, "MY Kedah", "MY Kedah"))%>%
mutate(matching_var = str_replace(matching_var, "MY Kelantan", "MY Kelantan "))%>%
mutate(matching_var = str_replace(matching_var, "Amurskaja oblast", "Amur"))
```
I Also tried this for whitespaces but still nothing :
```data$matching_var <-str_replace_all(data$matching_var, fixed(" "), " ")
```
The output looks exactly like the input, I can't figure out why. Thanks for your help.
Here is the accepted answer:
If you're going to do replacement with fixed strings, one option is to ```merge```/```left_join``` a conversion table:
```conversions <- tribble(
~fm, ~ to,
"MY Johor" , "MY Johor",
"Los Ríos" , "Los Rios",
"MY Kedah" , "MY Kedah",
"MY Kelantan" , "MY Kelantan ",
"Amurskaja oblast" , "Amur")
left_join(data, conversions, by = c("matching_var" = "fm")) %>%
mutate(
new_matching_var = coalesce(to, matching_var)
) %>%
select(-to)
# matching_var new_matching_var
# 1 BD Mymensingh BD Mymensingh
# 2 CN Nei Mongol CN Nei Mongol
# 3 EC Los Ríos EC Los Ríos
# 4 MY Johor MY Johor
# 5 MY Kedah MY Kedah
# 6 MY Kelantan MY Kelantan
# 7 MY Negeri Sembilan MY Negeri Sembilan
# 8 RU Amurskaja oblast RU Amurskaja oblast
```
(Note that the ```"MY Kelantan "``` has a trailing space that you added to your own code.)
Another option is to use ```conversions``` and ```match```, without the merge/join:
```data %>%
mutate(
ind = match(matching_var, conversions$fm),
new_matching_var = if_else(is.na(ind),
matching_var, conversions$to[ind])
) %>%
select(-ind)
# matching_var new_matching_var
# 44 BD Mymensingh BD Mymensingh
# 174 CN Nei Mongol CN Nei Mongol
# 259 EC Los Ríos EC Los Ríos
# 694 MY Johor MY Johor
# 695 MY Kedah MY Kedah
# 696 MY Kelantan MY Kelantan
# 700 MY Negeri Sembilan MY Negeri Sembilan
# 1029 RU Amurskaja oblast RU Amurskaja oblast
```
While this can be done with a named vector, one reason I recommend this is that it is easily maintained (e.g., as a CSV in a directory; you can use Excel or Calc to edit/maintain the list of conversions you want).
For the blank-space removal, one can use ```trimws``` to remove extra spaces from the beginning or end of the strings. I'll continue
```data %>%
mutate(
ind = match(matching_var, conversions$fm),
new_matching_var = if_else(is.na(ind),
matching_var, conversions$to[ind])
) %>%
select(-ind) %>%
mutate(new_matching_var2 = trimws(new_matching_var))
# matching_var new_matching_var new_matching_var2
# 44 BD Mymensingh BD Mymensingh BD Mymensingh
# 174 CN Nei Mongol CN Nei Mongol CN Nei Mongol
# 259 EC Los Ríos EC Los Ríos EC Los Ríos
# 694 MY Johor MY Johor MY Johor
# 695 MY Kedah MY Kedah MY Kedah
# 696 MY Kelantan MY Kelantan MY Kelantan
# 700 MY Negeri Sembilan MY Negeri Sembilan MY Negeri Sembilan
# 1029 RU Amurskaja oblast RU Amurskaja oblast RU Amurskaja oblast
```
though I don't know what didn't work with ```str_replace_all(data$matching_var, fixed(" "), " ")```, that did remove all of the literal mid-string ```" "``` that I saw (well, at this point, there are no double-spaces remaining, but it would have).
You can replace all of that perhaps with a simpler two-step cleanup, assuming that you don't need to otherwise change values:
```data %>%
mutate(
new_matching_var = trimws(str_replace(matching_var, fixed(" "), " "))
)
# matching_var new_matching_var
# 44 BD Mymensingh BD Mymensingh
# 174 CN Nei Mongol CN Nei Mongol
# 259 EC Los Ríos EC Los Ríos
# 694 MY Johor MY Johor
# 695 MY Kedah MY Kedah
# 696 MY Kelantan MY Kelantan
# 700 MY Negeri Sembilan MY Negeri Sembilan
# 1029 RU Amurskaja oblast RU Amurskaja oblast
```
|
Title: htaccess redirect from url with querystring
Tags: .htaccess;redirect
Question: when I digit this url:
```http://www.mydomain/search.php?page=1&order=ASC&contract=rent&new=
```
url should redirect to
```http://www.mydomain/rent/1
```
I try to add this line in my .htaccess, without success:
```Redirect http://www.mydomain/search.php?page=1&order=ASC&contract=rent&new= http://www.mydomain/rent/1
```
thanks in advance!!!
Here is another answer: Add these lines instead (but you'll only need to add the first line if it isn't there already):
```RewriteEngine On
RewriteCond %{QUERY_STRING} ^page=(\d+)&order=ASC&contract=rent&new=$
RewriteRule search.php /rent/%1? [L,R=301]
```
|
Title: refresh google cloud endpoint in android studio
Tags: android-studio;refresh;google-cloud-endpoints
Question: i'm using android studio 1.2.2 to create an android app that relies on a google cloud backend.
i managed to create the app and the backend, to generate backend endpoint to persist data bu now i have added a new constructor to the entity class (to pass parameters that will initialize the object) but i am not able to refresh the api version of this class in the library generated, so there is no new constructor and i can't use.
what are the steps to refresh the contents of this library?
thanks in advance
FROM
```@Entity
public class Coordinates {
@Id
String email;
double latitude;
double longitude;
String timestamp;
public Coordinates(){}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
```
TO
```@Entity
public class Coordinates {
@Id
String email;
double latitude;
double longitude;
String timestamp;
public Coordinates(){}
public Coordinates(String email,double latitude,double longitude,String timestamp) {
this.email=email;
this.latitude=latitude;
this.longitude=longitude;
this.timestamp=timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
```
Comment: What do you mean you've added a new constructor? Can you include code snippets of what you've done?
Comment: thanks for your answer, as you requested i added the code, as you can see i just added the constructor public Coordinates(String email,double latitude,double longitude,String timestamp)
Here is another answer: When you generate your endpoints JAR to be used in Android it does not transfer all the methods or constructors. I don't know the reason for that, probably written somewhere but haven't seen it.
I believe you have two options:
Use your Coordinates class without special constructor, ie use getters and setters
Create Coordinates class in Android app and have a helper class which converts your Android App Coordinates class into Endpoint Coordinates class
Comment for this answer: Yes, the generated client libraries only create a representation of your class on the client side that works with the API you generate. I believe option 1 is what you want to go with. Option 2 will not help you because your api will not accept parameters that are not of the type included in the client library.
Comment for this answer: Using the second option, you guarantee that who need convert your Android App Coordinates class into Endpoint Coordinates class will not forget any important parameter, doing set/get in one place. More useful and better solution of poit of view of oriented object paradigm.
another solution is define a contract using interfaces.
|
Title: When to prefer LinkedBlockingQueue over ArrayBlockingQueue?
Tags: java;multithreading;concurrency;blockingqueue
Question: When to prefer ```LinkedBlockingQueue``` over ```ArrayBlockingQueue```?
Which data structure to use among ```LinkedBlockingQueue``` and ```ArrayBlockingQueue``` when:
You want an efficient read and write
should have lesser memory footprints
Although there is a similar question but it does not highlight the fact that which should be preferred?
Links:
Java: ArrayBlockingQueue vs. LinkedBlockingQueue
What is the Difference between ArrayBlockingQueue and LinkedBlockingQueue
Here is the accepted answer: Boris the Spider has already outlined the most visible difference between ```ArrayBlockingQueue``` and ```LinkedBlockingQueue``` - the former is always bounded, while the latter can be unbounded.
So in case you need an unbounded blocking queue, ```LinkedBlockingQueue``` or a ```LinkedTransferQueue``` used as a ```BlockingQueue``` are your best bets from the ```java.util.concurrent``` toolbox.
But let's say you need a bounded blocking queue.
In the end, you should choose an implementation based on extensive experimenting with a simulation of your real-world workload.
Nevertheless, here are some notes that can help you with your choice or with interpreting the results from the experiment:
```ArrayBlockingQueue``` can be created with a configurable (on/off) scheduling fairness policy. This is great if you need fairness or want to avoid producer/consumer starvation, but it will cost you in throughput.
```ArrayBlockingQueue``` pre-allocates its backing array, so it doesn't allocate nodes during its usage, but it immediately takes what can be a considerable chunk of memory, which can be a problem if your memory is fragmented.
```ArrayBlockingQueue``` should have less variability in performance, because it has less moving parts overall, it uses a simpler and less-sophisticated single-lock algorithm, it does not create nodes during usage, and its cache behavior should be fairly consistent.
```LinkedBlockingQueue``` should have better throughput, because it uses separate locks for the head and the tail.
```LinkedBlockingQueue``` does not pre-allocate nodes, which means that its memory footprint will roughly match its size, but it also means that it will incur some work for allocation and freeing of nodes.
```LinkedBlockingQueue``` will probably have worse cache behavior, which may affect its own performance, but also the performance of other components due to false sharing.
Depending on your use-case and how much do you care about performance, you may also want to look outside of ```java.util.concurrent``` and consider Disruptor (an exceptionally fast, but somewhat specialized bounded non-blocking ring buffer) or JCTools (a variety of bounded or unbounded queues with different guarantees depending on the number of producers and consumers).
Comment for this answer: Since most of java GCs are compacting, problems with heap fragmentation don't really exist.
Comment for this answer: Nice answer! I agree with what you have mentioned also I would like to emphasis (again) the fact that ArrayBlockingQueue is backed by an array that size will never change after creation. Setting the capacity to Integer.MAX_VALUE would create a big array with high costs in space. ArrayBlockingQueue is always bounded.
LinkedBlockingQueue creates nodes dynamically until the capacity is reached. This is by default Integer.MAX_VALUE. Using such a big capacity has no extra costs in space. LinkedBlockingQueue is optionally bounded.
Comment for this answer: @Dimitar Dimitrov what are the `JCTools` alternatives for `BlockingQueue`?
Comment for this answer: Does `ArrayBlockingQueue` move all of the elements in the backing array up by one index every time you remove the head element from the queue? If so, it seems like a simple operation like popping the head element off the queue could be extremely expensive.
Here is another answer: From the JavaDoc for ```ArrayBlockingQueue```
```
A bounded blocking queue backed by an array.
```
Emphasis mine
From the JavaDoc for ```LinkedBlockingQueue```:
```
An optionally-bounded blocking queue based on linked nodes.
```
Emphasis mine
So if you need a bounded queue you can use either, if you need an unbounded queue you must use ```LinkedBlockingQueue```.
For a bounded queue, then you would need to benchmark to work out which is better.
Comment for this answer: Thanks for your answer @BoristheSpider. Your are right this is one good reason for preference, but do we have differences in performance when :
1. You want an efficient read and write
2. there is no concern on whether queue be bounded or not
3. should have lesser memory footprints ?
Comment for this answer: To be able to declare an unbounded queue is also one of the reasons as specified in my answer as linkedList is unbounded whereas arrays are not.
Comment for this answer: @rahulroc you actually never say that at all, and never provide any evidence for your assertions. Saying that an array backed collection is bounded is also simplistic and untrue - an `ArrayList` is array backed.
Comment for this answer: @VaibhavGupta what do you mean by `2`? How can you have _no concern_? If you create an `ArrayBlockingQueue` then you **must** specify the size of the underlying array. If you set it to `Integer.MAX_VALUE` your computer will likely crash, so you have to pick a realistic number. If there is no realistic number, then you require an **unbounded** queue.
|
Title: Distance between two POINT values in MySQL in a loop
Tags: mysql;geometry
Question: I am storing geometry data in a MySQL Database
```--------------------------------------------------
| ID | SPATIAL_INDEX | COORDS | DISTANCE |
| 1 | ... | POINT(0.5,0.5) | 0 |
| 2 | ... | POINT(0.7,0.7) | ? |
---------------------------------------------------
```
The coords come from a 2D-Cartesian tracking system.
How can I populate the column DISTANCE with the distance between the coords of a row and the last row?
```Row 1: Distance = 0;
Row 2: Distance = Distance between coords of row 1 and row 2
Row 3: Distance = Distance between coords of row 2 and row 3
[...]
```
Comment: Assumuing you have all the rows inserted into the table in the first place, and now need to populate the distances then you can for an UPDATE statement that is a self join
Here is the accepted answer: SQL has a special spatial function to calcutate the distance between two points. you can use that plus a join on the table itself to achieve what you want.
```UPDATE tablename AS a
LEFT JOIN tablename AS b
ON b.id = a.id-1
SET a.distance = IFNULL(DISTANCE(a.coord,b.coord),0);
```
|
Title: Are variables declared in pthread's functions shared between threads?
Tags: c;multithreading;pthreads
Question: I am new to C and pthreads. Here's an example (which probably won't compile as I wrote it now) but it shows what I want to know:
int i = 50;
```void* myFunc (void* whatever) {
int myLoop = 0;
for (;;)
{
for (myLoop = 0; myLoop < i; myLoop++)
do work blah;
}
pthread_exit(NULL);
}
int main (void) {
pthread_t threadNo1, threadNo2, threadNo3;
pthread_create(&threadNo1, NULL, myFunc, NULL);
pthread_create(&threadNo2, NULL, myFunc, NULL);
pthread_create(&threadNo3, NULL, myFunc, NULL);
pthread_join(threadNo1, NULL);
pthread_join(threadNo2, NULL);
pthread_join(threadNo3, NULL);
pthread_exit(NULL);
}
```
Is ```int myLoop``` shared between the 3 threads?
Is the loop in ```myFunc``` running as thought on all 3 threads (as in iterating properly to 50 which is the value of ```int i```), or are they fighting continuously over its value due to ```myLoop++```? Is this because the variable ```int myLoop``` shares its memory value in all different threads?
I want myFunc to run on different threads given to different cores without them messing with each other while looping, meaning the loop iterates perfectly on all threads and they are ignorant of each other. Or is this not actually a problem and is indeed doing that?
Comment: Each thread has its own stack.
Comment: It serves the purpose of deadlocking your program. Had the main thread just exited, the runtime would kill all other threads.
Comment: @StoryTeller while the join() call o'death does indeed prevent main() from exiting, it is not deadlock. The pthreads are not waiting on a resource held by the main thread - they are, (presumably:), making forward progress with their 'do work blah'.
Comment: A local variable is a local variable. No sharing will happen.
Comment: Thank you. I also assume the `pthread_join` I added serves no purpose since the functions never end?
Here is the accepted answer: ```
Is int myLoop shared between the 3 threads?
```
Threads have nothing to do with it. The same question could be asked about a single thread. Consider:
```int myFunc(int *j)
{
int q;
// lots of code here
myFunc (&q);
}
```
Consider a single thread that calls ```myFunc``` and then ```myFunc``` calls itself. Do the two instances of ```myFunc``` share ```q``` or not? And the answer is -- both. Each invocation has its own ```q```. But if the second call does ```*j = 2;``` it will change the value of the first invocation's ```q```.
So each has its own, but they can share them if they wish since they have the same view of process memory.
Same with threads.
|
Title: Bookpagination in Biblatex-chicago
Tags: biblatex-chicago
Question: Under biblatex, if an @incollection entry had no bookpagination field, this would be understood to have a default value of "pages", and where necessary the page range would be preceded by p. or pp.. However, in biblatex-chicago this is no longer the case:
```
This, a standard biblatex field, allows you automatically to prefix
the appropriate string bookpagination to information you provide in a
pages field. If you leave it blank, the default is to print no
identifying string (the equivalent of setting it to none), as this is
the practice the Manual recommends for nearly all page numbers.
```
(From the biblatex-chicago manual, p. 24 http://ctan.math.washington.edu/tex-archive/macros/latex/contrib/biblatex-contrib/biblatex-chicago/doc/biblatex-chicago.pdf)
Is it possible to change this, so that the default behaviour is again to put in "p." or "pp." (i.e. to have the default be "pages" rather than "none")? I could of course go through my (now very long) bib file and add in an explicit line
```bookpagination = "pages",
```
to every @incollection item, but this would be inefficient. Is there any way to do this globally?
Here is the accepted answer: Standard ```biblatex``` defaults to ```bookpagination = {pages},``` if no ```bookpagination``` is given. ```biblatex-chicago``` avoids this and essentially falls back to ```bookpagination = {none},``` by adding a test to the field format. We can remove this test and go back to the standard behaviour.
The MWE retains the ```biblatex-chicago``` format for ```@article```s, but you can get "p."/"pp." there as well by simply removing the ```\DeclareFieldFormat[article,periodical]{pages}``` block.
```\documentclass[american]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}
\usepackage[notes, backend=biber]{biblatex-chicago}
\addbibresource{biblatex-examples.bib}
\DeclareFieldFormat{pages}{%
\iftoggle{cms@comprange}%
{\mkcomprange[{\mkpageprefix[bookpagination]}]{#1}}%
{\mkpageprefix[bookpagination]{#1}}}
\DeclareFieldFormat[article,periodical]{pages}{%
\iftoggle{cms@comprange}%
{\iffieldundef{bookpagination}%
{\mkcomprange{#1}\isdot}%
{\mkcomprange[{\mkpageprefix[bookpagination]}]{#1}}}%
{\iffieldundef{bookpagination}%
{#1\isdot}%
{\mkpageprefix[bookpagination]{#1}}}}%
\begin{document}
\cite{sigfridsson,westfahl:space,gaonkar:in}
\printbibliography
\end{document}
```
If you are interested in getting the page prefix also in citations, you may want to add
```\DeclareFieldFormat{postnote}{%
\iftoggle{cms@comprange}%
{\mkcomprange[{\mkpageprefix[pagination]}]{#1}}%
{\mkpageprefix[pagination]{#1}}}%
```
|
Title: An object specified for refresh is not recognized
Tags: c#;asp.net-mvc;linq-to-sql
Question: I have a update function like this:
```public void Update(HomeBanner homebanner)
{
homebanner.EnsureValid();
DataSource.DataContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, homebanner);
DataSource.DataContext.SubmitChanges();
}
```
And i write a update controller
```[AcceptVerbs(HttpVerbs.Post)]
//[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult ManageImages(int ? id,FormCollection form)
{
HomeBanner homebanner= BannerRepository.RetrieveById(id);
this.TryUpdateModel(homebanner);
string photoName = saveImage("photo");
if (photoName != string.Empty)
homebanner.ImageID = photoName;
BannerRepository.Update(homebanner);
return RedirectToAction("list", "Admin");
}
```
and then the view:
```<% using (Html.BeginForm("ManageImages", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<h3>Manage Images</h3>
<div class="label-field">
<label for="ID">Chọn vị trí:</label>
<%= Html.DropDownList("ID", DataHelper.Banner().ToList().ToSelectList("value", "name",Model.HomeBanner.ID.ToString()))%>
</div>
<div class="label-field">
<label for="photo">
Chọn hình</label>
<input type="file" name="photo" value=""/>
</div>
<div class="label-field">
<label for="Link">
Liên kết</label>
<input type="text" name="Link"/>
</div>
<p>
<input type="submit" value="Lưu" />
</p>
<% } %>
```
It get data as well but update step is not success: It mark right here
```DataSource.DataContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, homebanner);
```
and throw exception: An object specified for refresh is not recognized.
I dont know why, i see data filled to object when i debug. Plz someone help me!
Here is another answer: I bump into this error because i was trying to update a just created object that did not exist yet on the database.
Here is another answer: Check the instance of DataContext there, maybe you are using different instance in which original object doesn't exists.
If it doesn't exist, you must first attach object to data context, then call refresh.
P.S. a tip: Make model or service for interacting with data, in controller it looks messy ;)'
Comment for this answer: Yes, it's really..Thank you. Can u believe, finally i find out the problem: i forgot create primary key for HomeBanner table!!!!
|
Title: Wizz Air insurance policy
Tags: insurance;wizz-air
Question: I booked a flight and together with the flight, I bought a travel insurance.
However, I never got an insurance policy with my name and personal information on it: I just received the general terms and conditions.
Does Wizz Air not issue such policy at all, or is it just very well hidden?
Comment: WizzAir doesn't issue the policy anyway, since they do not operate as an insurance provider, they just function as a middleman. The insurance provider is either Chubb European Group SE or Chubb Insurance Switzerland, depending on your residence. Have you checked your spam folder, if you maybe got an email from them, which was flagged?
Comment: @dunni : bingo, it was in spam folder :D
|
Title: confused over the usage of free () in C
Tags: c;memory-management;linked-list
Question: This is done by someone who is better in C programming than me.
confused over the usage of free () in C
below is the struct of linked list
```typedef struct node {
int value;
struct node *next;
} ListNode;
typedef struct list {
ListNode *head;
} LinkedList;
```
after created a list with some nodes
his code does this when exit
```void deleteList(LinkedList *ll) {
if (ll != NULL) {
ListNode *temp;
while (ll->head) {
temp = ll->head;
ll->head = temp->next;
free(temp);
}
free(ll);
}
}
```
The above is what I don't understand. Why he needs to create such complexity, why not just do free(ll).
Please help
thanks in advance.
Comment: @Deduplicator while your technical point is correct, I don't think it's busywork. Unless you malloc directly in main(), I don't think you can ever make a case where it won't eventually harm you... i.e. when you convert your standalone program to a lib or convert your simple program to a daemon, or convert your single-use program into one that processes multiple connections at once, etc. Please don't encourage bad practice for new programmers.
Comment: @Deduplicator... yeah, and I guess debugging future memory leaks doesn't count against that. To each his own. Enjoy!
Comment: Thanks everybody !!!! i was assuming free() will take the pointer and track down all the nodes and free all of them.
Comment: how well do you understand what a linked list is? there's a short explanation here or a long one...
Comment: Actually, every allocation operation should be reversed **unless you are tearing the house down and the platform will do it for you.** In the latter case it's busywork, though might be useful for leak-detection. Expanding on that theme, if you know your application will never in its whole lifetime (which must be short) allocate much memory, all deallocation can be deferred until exit. That also allows a more efficient implementation of the memory allocator.
Comment: @SanJacinto: Ever heard of future discounting? Making your program considerably faster and simpler and cheaper now, is worth much more than doing work for the nebulous future in which you might perhaps eventually under some conditions want to convert it to a demon or library.
Comment: You have to `free` every single thing you `malloc`.
Comment: Remember that each allocation operation should be reversed. Look at the implementation of adding nodes to the list - this should give you a clue.
Here is the accepted answer: Linked list is made up of individual objects that happen to point at each other. If you want to delete a list you have to delete all of its nodes. ```free()``` won't do that. It doesn't know that these objects make up a list. It doesn't even know that these objects contain pointers to anything. Therefore you need to iterate over the list and ```free``` each node by hand.
Comment for this answer: Thanks !!!! i was assuming free() will take the pointer and track down all the nodes and free all of them.
Here is another answer: You can do with the following struct alone
```typedef struct node {
int value;
struct node *next;
} ListNode;
```
But every time you have to declare a global variable ```struct node *HEAD```. In a bigger program it may confuse you. The author has done this so that you can create a linked list like a variable. Every time you have to create a new linked list all you have to do is declare
```LinkedList *ll;
```
When there are two struct, one has to free the objects of both the ```struct```.
Here is another answer: That's because each pointer points to a memory location. You need to free all memory locations that were previously allocated. ```free(ll)``` would only remove the node pointed to by the ```ll``` pointer.
Here is another answer: if you have a linked list, suposse that every "*" is a node.
``` 0 1 2 3 4
head--> *--*--*--*--*
```
the first *, es the head, is you just do "free ll"
this will be on the memory
``` 0 1 2 3 4
head-->nul *--*--*--*
```
the problem here, is, all the "memory" that you ask for those nodes will still be there, and now you can't know where is it (you have nothing poiting to that memory) for every malloc you need a free (not 100% true, but for simple things work).
What that algorithm do is:
get the reference to the next node (if you don't do this and you free the node, you won't be able to get the "next" node, becouse head will be pointing to nothing ).
free the head.
make head point to the reference that you get before.
|
Title: Why is WPF slider value not precise
Tags: slider;wpf-controls
Question: I have a slider in wpf
```<Slider x:Name="slider" Maximum="8" Minimum="1" VerticalAlignment="Center" TickFrequency=".1" IsSnapToTickEnabled="True" TickPlacement="TopLeft" SmallChange="0.1" />
```
To its ```value``` I have bounded a label
```<Label Content="{Binding Value, ElementName=slider}"/>
```
As I set the focus on the slider and move to right, or drag the thumb with mouse, the value gets raised by 0.1 as expected, but sometimes it shows this kind of value ```1.7000000002```
Does anybody know how to fix this to show just the values like 1.1, 1.2 etc? Thanks
Here is another answer: Why don't you use a TextBlock instead of Label?
```<TextBlock Text="{Binding Value, ElementName=slider}"/>```
display the slider's value exactly as you want.
Comment for this answer: dont know why should I, is there any difference? but I may try that, if that should solve my problem
|
Title: How can we do Multiple Operations using Single RecordSet?
Tags: vb.net;adodb
Question: I have some task regarding do operations on database using ADODB in Vb.NET. Can any help me regarding using the same record set multiple times?
I have tried on this topic just by closing the recordset after performing First operation and doing second operation e.t.c.
Example:
``` Dim rs As New ADODB.Recordset()
OpenConnection()
rs.Open("table1")
//Some Operations
//Now using same recordSet for Second Operation
rs.Close()
rs.Open("table2")
```
In ADO.NET we have "MultipleActiveResultSets=True" in ConnectionString for SqlDataReader.Do we have any property like this in ADODB?
Here is the accepted answer: The more similar thing that exists in ADODB is sending multiple queries in your Sql String then proccessing them one by one using rs.NextRecordset (rs is the Recordset), here is an example: ADO NextRecordset Method Demonstration
But, personally, i prefer doing it as you're doing it now, using just one recordset for each query. Take into account that using multiple recordsets inside one, like in the previous example may require some additional commands in some dbs to ensure no additional unwanted recordsets are created from messages coming from the backend, for example for Sql Server it's a good idea using:
Set NoCount On and Set ANSI_Warnings OFF
|
Title: How to programmatically solve y = (a1 * x1) + (a2 * x2) + .... + (a28 * x28) where y and a1, a2 ....a28 are known?
Tags: algorithm;math
Question: I am trying to solve this equation with 28 variables:
y = (a1 * x1) + (a2 * x2) + .... + (a28 * x28)
1) y is known, so are a1, a2 all the way through a28.
2) x1, x2 ..... x28 are unknown variables and they are in the range of [-4, 4] with 0.1 increment.
Could somebody shed some lights on my baffled brain as to what algorithm would be the most efficient to use here?
Comment: What do you mean by `the range of [-4, 4] with 0.1 increment`?
Comment: Is the discretisation intrinsic to the problem, or just an assumed approach? For the continuous problem, can you not simply allow _any_value of say `x2` through to `x28`, and then solve for `x1` in terms of that?
Comment: I wonder what Wolfram Alpha does with this =p
Comment: Are `a` and `y` reals, rationals or integers?
Comment: unfortunately yes, they are all different values
Comment: @irrelephant Karthik is right, that means it could be one of the 80 numbers from -4.0 to 4.0
Comment: @KarthikT there will most definitely be multiple answers
Comment: @DanielFischer all answers are wanted and preferably within reasonable amount of time
Comment: it's intrinsic, allowing x2 through x28 to deviate from the range would change the problem in question
Comment: @Jason just curious, how will you present the solution?
Comment: in at least one scenario, there will be 439804651110400000000000000 solutions.
Comment: Do you want all answers or would any answer suffice?
Comment: @irrelephant im guessing they are -4 or -3.9 or.... 3.9 or 4
Comment: Wont there be multiple answers?
Comment: Are x1... x28 all different values? Because in that case, there will be a very, very large number of valid solutions, if I'm not mistaken.
Here is another answer: This is equivalent to integer linear programming, though since there is only one equation with 28 simple constraints (the bounds, rather than a system of equations), you might be able to do better. In general this is going to be NP-hard (see https://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns), but there are several implementations you might be able to use (see for example How to choose an integer linear programming solver?)
Comment for this answer: This is not a linear programming problem, it is an equation not a relation or maximization. The answer must be exactly y.
Comment for this answer: You can think of it as maximizing the right hand side sum, subject to the limitation that the sum must not exceed y. That, combined with multiplying by 10 to get rid of the fractions, may turn it into a problem with existing practical solvers.
Here is another answer: First of all multiply everything by 10 so you can stay in integer math. Also add sum(40*a_u) to both sides will change the range of x_i to [0,80]
Secondly there may be an exponential number of answers so your algorithm must take exponential time.
Given that there are 80^28 (approximately 2^177) possible answers - this is not possible in general.
Now if the range of x_i were [0,1] (and not [0,80]) and we add an extra term that is equal to y (and change y to 0), than the problem becomes find a subset of a set of integers that add up to zero. This is a well known NP complete problem, and it seems even easier than yours (although I don't have a clear reduction).
There may be a dynamic programming solution, but it may be too slow:
```set<float> X;
X.insert(0)
for i = 1 to 28
for f = -4.0 to 4.0 step 0.1
for x in X
X.insert(x + a_i * f)
for x in X
if (x == y)
return true;
return false;
```
You can do better than this by passing back the feasible range (of [y + a_i*(-4.0), y + a_i*4.0]) and prune infeasible partial solutions outside those bounds.
Comment for this answer: You can't really knapsack a problem like this. What you're doing above is adding -4.0*x1,-3.9*x1 etc which violates the constraints (not to mention you'll run out of memory :))
Comment for this answer: @dfb: I agree depending on the a_i it is exponential in space, but how does it violate the constraints?
Here is another answer: You can program it in prolog (SICStus prolog engine and for example SPIDER IDE on Eclipse). This problem is state space searching problem. And use clpfd library (Constraint Logic Programming over Finite Domains). Then you just do one constraint, X1 to X28 will be domain variable and given constraint y #= a1*X1 + ... + a28*X28. There is also few ways to optimalize searching of state space.
/edit:
Or you can try do it in any imperative language. Also use some heuristics - for example, choose some points of execution, where you can check current result (for example, you have some tmp. sum and you had already count with 15 from 28 values. If y minus temp sum is lesser than MIN_VARIABLE_VALUE * i, where i is index and x_i belongs to remaining variables, you can safely decide, that you won´t continue, bcs. you can´t get equality). This heuristic get on my mind first. Use can also use some substitution in this. But there should be done "research" on some test data how much efficient it is.
|
Title: Does updating a MongoDB record rewrites the whole record or only the updated fields?
Tags: mongodb
Question: I have a MongoDB collection as follows:
```comment_id (number)
comment_title (text)
score (number)
time_score (number)
final_score (number)
created_time (timestamp)
```
Score is and integer that's usually updated using $inc 1 or -1 whenever someone votes up or down for that record.
but time_score is updated using a function relative to timestamp and current time and other factors like how many (whole days passed) and how many (whole weeks passed) .....etc
So I do $inc and $dec on db directly but for the time_score, I retrieve data from db calculate the new score and write it back. What I'm worried about is that in case many users incremented the "score" field during my calculation of time_score then when I wrote time_score to db it'll corrupt the last value of score.
To be more clear does updating specific fields in a record in Mongo rewrites the whole record or only the updated fields ? (Assume that all these fields are indexed).
Here is the accepted answer: By default, whole documents are rewritten. To specify the fields that are changed without modifying anything else, use the $set operator.
Edit: The comments on this answer are correct - any of the update modifiers will cause only relevant fields to be rewritten rather than the whole document. By "default", I meant a case where no special modifiers are used (a vanilla document is provided).
Comment for this answer: Actually literally every update operator only modifies the field it is applied on. Overwriting the whole document is the exception rather than the rule as very few people want to overwrite the entire document in real world scenarious.
Comment for this answer: this is not accurate - when you use various operators (like $inc) only the specified field is changed. the whole document is rewritten only when you pass in a full document for the update without any update operators.
Comment for this answer: Can anyone of you please post a link for me to verify that this is how the updates are done !!
Here is another answer: The algorithm you are describing is definitely not thread-safe.
When you read the entire document, change one field and then write back the entire document, you are creating a race condition - any field in the document that is modified after your read but before your write will be overwritten by your update.
That's one of many reasons to use $set or $inc operators to atomically set individual fields rather than updating the entire document based on possibly stale values in it.
Another reason is that setting/updating a single field "in-place" is much more efficient than writing the entire document. In addition you have less load on your network when you are passing smaller update document ({$set:{field:value}}, rather than entire new version of the document).
Comment for this answer: the algorithm you describe is not thread safe for any operation that doesn't perform an atomic update. $inc is safe but $set that's based on a possibly stale value is not safe.
Comment for this answer: No, you're wrong you didn't get my question I'm not saying I'll write the whole document I'm saying I don't wanna do this and the answer above is correct.
Comment for this answer: what if value is a calculation not a specific number ?, can I do something like this in mongo :
$set:{field: equation * field - another_field} ?
|
Title: Groovy script from docker container
Tags: curl;docker;groovy
Question: I'm trying to get the html response from my web page using docker and groovy script. Normally I could use curl as below:
```curl 972-254-1311:1410
```
...and get the response "OK"
But when I'm trying to get the same with starting docker and groovy:
```[mycomp@my-host script] cat run.sh
#!/bin/bash
docker run \
--rm \
-e TZ=Europe/Warsaw \
-v /home/user1/monitoring/:/home/user1/monitoring/:Z \
-w /home/user1/monitoring/script \
--name groovy2 groovy:2.4.11-jdk8 \
groovy run.groovy
[mycomp@my-host script] cat run.groovy
def server = "972-254-1311"
println "http://$server:1410/".toURL().text
```
... I'm getting such an Timeout error (after many seconds...):
```[mycomp@my-host script] ./run.sh
Caught: java.net.ConnectException: Connection timed out (Connection timed out)
java.net.ConnectException: Connection timed out (Connection timed out)
at run.run(run.groovy:2)
```
I don't know what I'm doing wrong. Maybe you can tell me? Maybe you can propose my something other solution (but still using docker and groovy)
EDIT:
Program is ok, I had a problem with connection to this ip address.
Comment: What is your base image?
Comment: What is the output of command on host machine | docker container ? - `telnet {{PHONE+SOCIAL_SECURITY_NUMBER}}`?
Comment: @Rao: groovy:2.4.11-jdk8
Comment: I guess it might related to network configuration. More or less you need to add you docker container to local network. It also shouldn't work with curl.
Comment: What is this IP for 972-254-1311? what is the network infra?
Comment: Thanks you all for suggestion about infrastructure and telnet'ing this addres. Of course I had an limitiation of network connection. I added some rule and now everything is ok.
|
Title: How to remove fragment item in ArrayAdapter in android
Tags: android;android-fragments;android-arrayadapter
Question: We have a Array Adapter with fragment items.
```@Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null){
view = new FrameLayout(mContext);
view.setId(View.generateViewId());
}
Fragment fragment = getItem(position);
mFragmentManager.beginTransaction()
.replace(view.getId(), fragment)
.commit();
return view;
}
```
We want to remove one item from list.When we remove last item of list it works well, but for removing a middle or first item in the list a error was occurred.
We know the problem is in replace method, it gets wrong id!!!
The removing item code is this:
```int count = mAdapter.getCount();
for (int i = count - 1; i >= 0; --i) {
Fragment fragment = mAdapter.getItem(i);
if (fragment.getClass().equals(aClass)) {
mAdapter.remove(fragment);
mAdapter.notifyDataSetChanged();
}
}
```
The error is :
```java.lang.IllegalStateException: Can't change container ID of fragment ScheduleD{b3087758 #2 id=0xf}: was 15 now 14
```
Comment: What error do you get?
Comment: post code where you are removing
Comment: @tpA I added the removing code,thx.
Comment: @Jörn Buitink I added the error,thx.
|
Title: Can we drag and drop md-list item or md-cards in angular material design
Tags: angularjs;angularjs-material
Question: Can we drag and drop md-list item or md-cards in angular material design using jQuery or other framework?
Comment: Have you made any research on this subject?
Comment: I think I can clarify this question a little. "Motion provides meaning" is supposed to be a core principles of Material Design, and Angular Material is supposed to implement those principles. So one would expect to find support built into Angular Material for dragging cards around in an `md-list` for example. Reading through all the documentation on http://material.angularjs.org, I (probably like the original poster) find no hint of that though. It's such a startling omission I feel I must have missed something.
Comment: This tool is not really an answer - but maybe an alternative in some use cases: https://www.npmjs.com/package/angular-material-widget-engine (widget with drag-n-drop support)
Here is another answer: I can give a partial answer to this. It is not recommended to add jQuery to an Angular project. Angular is controller-centric while jQuery is focused on manipulating the DOM. They are really different approaches, and while you could possibly get something to work using jQuery and Angular together--it would tend to be a fragile and overly complex solution.
The same holds for Angular Material. It's not a great basis for jQuery operations.
That having been said, see also my comment on your question. I read through all the documentation on http://material.angularjs.org and found nothing that suggests built-in support for drag/drop operations in general nor for dragging cards around in a list.
I realize the framework is still pretty new but I am surprised to find that something as essential to the Material Design concept as dragging cards around a list simply wasn't addressed. So perhaps you and I both are confused or missing something that should be glaringly obvious.
|
Title: CSS bootstrap navbar overriding colors for text/links of login drop down
Tags: html;css;twitter-bootstrap
Question: So I have a website I'm working on, and I chose to use bootstrap to assist in the styling. The problem I have is that now I'm trying to add a drop down login form to the navbar links and it seems as though bootstrap is overriding my color settings for the text/links. For example, this allows the drop down to pop up and everything shows up correct except the "Forgot your password" and the "Register" part. The rest shows up fine, but for some reason in the css under the
.navbar-nav li a:hover, .navbar-nav li.active a part the color set for that shows as the color for when I hover over those to links. Otherwise it shows up as white which is another part of the navbar css for my font color. I dont understand why it wont recognize the dropdown styling.
Ill paste the css and code below.
```.navbar {
background-color: blue;
z-index: 9999;
border: 0;
font-size: 12px;
line-height: 1.42857143;
letter-spacing: 4px;
}
.navbar li a,
.navbar .navbar-brand {
color: #fff !important;
}
.navbar-nav li a:hover,
.navbar-nav li.active a {
color: #000000 !important;
background-color: #fff !important;
}
.navbar-default .navbar-toggle {
border-color: transparent;
color: #fff !important;
}
.navbar .form-group {
color: black;
}
#login-dp {
min-width: 250px;
padding: 14px 14px 0;
overflow: hidden;
background-color: #ffffff;
}
#login-dp .help-block {
font-size: 12px;
color: black !important;
}
#login-dp .bottom {
background-color: rgba(255, 255, 255, .8);
border-top: 1px solid #ddd;
clear: both;
padding: 14px;
color: black;
}
#login-dp a:link {
color: black;
}
#login-dp .social-buttons {
margin: 12px 0
}
#login-dp .social-buttons a {
width: 49%;
}
#login-dp .form-group {
margin-bottom: 10px;
color: black;
}
.btn-fb {
color: #fff;
background-color: #3b5998;
}
.btn-fb:hover {
color: #fff;
background-color: #496ebc
}
.btn-tw {
color: #fff;
background-color: #55acee;
}
.btn-tw:hover {
color: #fff;
background-color: #59b5fa;
}
@media(max-width:768px) {
#login-dp {
background-color: inherit;
color: #000000;
}
#login-dp .bottom {
background-color: inherit;
border-top: 0 none;
color: black;
}
}```
```<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="aboutus.php">ABOUT</a>
</li>
<li><a href="services.php">SERVICES</a>
</li>
<li><a href="portfolio.php">PORTFOLIO</a>
</li>
<li><a href="order.php">ORDER</a>
</li>
<li><a href="contactus.php">CONTACT</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><b>LOGIN</b></a>
<ul id="login-dp" class="dropdown-menu">
<li>
<div class="row">
<div class="col-md-12">
<form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Password</label>
<input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>
<div id="help-block text-right"><a href="">Forgot your password?</a>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
</div>
<div class="bottom text-center">
New here? <a href="register.php">Register</a>
</div>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>```
Here is another answer: Is this what you want?
```.navbar li a, .navbar .navbar-brand {
color: #fff !important;
}
.navbar-nav li a:hover, .navbar-nav li.active a {
color: #000000 !important;
background-color: #fff !important;
}
To:
.navbar .nav>li>a, .navbar .navbar-brand {
color: #fff !important;
}
.navbar-nav li a:hover, .navbar-nav li.open a {
color: #000000 !important;
background-color: #fff !important;
}
```
Comment for this answer: not quite i dont think. My issue isnt the navbar colors specifically. The navbar css is perfect to my knowledge. The issue is that it overrides the css for the dropdown form.
Here is another answer: It looks like the issue is you're using an ID for your help-text when it should be a class:
```id="help-block text-right"``` should be ```class="help-block text-right"``` (though I used ```text-center``` in my example for consistency).
Also, you shouldn't need to use !important for any of this, just use a stronger selector and I doubt you need the form inside of any row/column format.
Hopefully this helps.
Working Example:
```.navbar.navbar-default {
background-color: blue;
z-index: 9999;
border: 0;
font-size: 12px;
line-height: 1.42857143;
letter-spacing: 4px;
}
.navbar.navbar-default .navbar-nav > li > a,
.navbar.navbar-default .navbar-brand {
color: #fff;
}
.navbar.navbar-default .navbar-nav > li > a:hover,
.navbar.navbar-default .navbar-nav > li.active > a {
color: #000000;
background-color: #fff;
}
.navbar.navbar-default .navbar-toggle {
border-color: transparent;
color: #fff;
}
.navbar.navbar-default .form-group {
color: black;
}
.navbar.navbar-default #login-dp {
min-width: 250px;
padding: 14px 14px 0;
overflow: hidden;
background-color: #ffffff;
}
.navbar #login-dp .help-block {
font-size: 12px;
color: black;
}```
```<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="aboutus.php">ABOUT</a>
</li>
<li><a href="services.php">SERVICES</a>
</li>
<li><a href="portfolio.php">PORTFOLIO</a>
</li>
<li><a href="order.php">ORDER</a>
</li>
<li><a href="contactus.php">CONTACT</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><b>LOGIN</b></a>
<ul id="login-dp" class="dropdown-menu">
<li>
<form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Password</label>
<input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>
<div class="help-block text-center"><a href="">Forgot your password?</a>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
<div class="form-group">
<div class="text-center">
New here? <a href="register.php">Register</a>
</div>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>```
Here is another answer: Try to include bootstrap CSS before your own CSS like so:
```<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/YOUR CSS FILE.css">
```
Including your CSS like this means that bootstrap CSS get executed first. After that it applies your CSS which means that your CSS will be leading.
Comment for this answer: Allright. Try to check your console (right-click in browser > inspect) Maybe you can see there why your css is overwritten. If that does not work, try make a jsfiddle and see if you can reproduce your errors there
Comment for this answer: I did it but it didnt work. Thanks for that information though I had forgotten about that entirely.
Comment for this answer: im not sure i know how to do that jsfiddle thing, or if it would work. If it requires any javascript theres none in the site. I went to console but theres nothing going on in it.
|
Title: JavaScript breadcrumbs for urls that DON'T use slashes between folders
Tags: javascript;html;css
Question: So I have a somewhat unusual issue. I have found lots of js code for breadcrumbs, and lots of help; however, the company I work for does NOT use slashes between folders and file names in the page urls. Instead, they are using a slash after the main website url and then underscores between the folder levels and file names... Honestly, I've never run across this before, and since I'm not as comfortable with js as I could be, I'm not sure how to handle the issue. If they used all slashes or all underscores, I might be less confused, but since it's a combination of the two -- well, here I am.
So, I found some clientside code I liked with some modification in a different question on here, which I think works out to something like this:
```$(document).on("pageshow", "#breadcrumb", function breadCrumb(){
document.getElementById('ID').innerHTML = '<span>' + part[i] + '</span>';
var here = location.href.split('/').slice(3);
var parts = [{ "text": 'Home', "link": '/' }];
for( var i = 0; i < here.length; i++ )
{
var part = here[i];
var text = part.toUpperCase();
var link = '/' + here.slice( 0, i + 1 ).join('/');
parts.push({ "text": text, "link": link });
}
});
```
Suggestions? Ideas? Help? I don't mind creating a separate js file and pulling from the server, but in general I've discovered that things tend to work better on the web pages (at least on this particular site) if I can include the code in the page.
Worse, I have no access to the header information other than through some fields that pop up in the browser editor. All I can do is insert content into a container within the body. Generally speaking this is working just fine, even when I need to add script code with css or javascript. I just wanted to mention it. ...And in case anyone needs to know, we're using OpenCMS through an external company for website management (a more terrible arrangement I never saw! and many of the functionalities that should work in this do not).
p.s. internal href values look like this: /know-how_Chicken-Care_poultry-breed-research-guide.html
Comment: http://www.companyname.com/know-how_Chicken-Care_poultry-breed-research-guide.html
Comment: /know-how_Chicken-Care_raising-chickens-tips-and-advice.html -- The folders themselves don't use index pages, so you can't simply delete the file name to get back to the parent level.
Comment: So, for example, the top level page is located at /know-how_Main_know-how-central.html
Comment: can you provide an example of the urls structure? you can change the domain name for privacy purposes
Comment: What's the url to access the prior category? For example is it ```/know-how_Chicken-Care/``` or ```/know-how_Chicken-Care.html``` ?
Here is another answer: Ok, how about this
```jQuery(document).ready(function() {
var here = location.href.split('/').pop().split('_');
var parts = [{ "text": 'Home', "link": '/' }];
console.log(here);
for( var i = 0; i < here.length; i++ )
{
var part = here[i];
var text = part.toUpperCase();
var link = '/' + here.slice( 0, i + 1 ).join('_');
parts.push({ "text": text, "link": link });
}
console.log(parts);
for(var j=0;j<parts.length;j++) {
var item=parts[j];
jQuery('#breadcrumb').append(' / <a href="'+item.link+'">'+item.text+'</a>');
}
});
```
I extract the query string (know-how_Chicken-Care_poultry-breed-research-guide.html) and split it using underscores. Then in the for loop I join the parts with an underscore.
The result is
```0: Object
link: "/"
text: "Home"
1: Object
link: "/know-how"
text: "KNOW-HOW"
2: Object
link: "/know-how_Chicken-Care"
text: "CHICKEN-CARE"
3: Object
link: "/know-how_Chicken-Care_poultry-breed-research-guide.html"
text: "POULTRY-BREED-RESEARCH-GUIDE.HTML"
```
Edit: see the first part of my answer, I included the insertion of the link elements to the #breadcrumbp container. Also, the pageshow event wasn't triggering, so I used the document ready instead.
Comment for this answer: Let me give this a shot and see what happens. THANK YOU! I'll be back a few to let you know how it worked.
Comment for this answer: my brain is trying to shut down with a migraine (which hopefully won't succeed). I am not comprehending what you said in the last comment.
Comment for this answer: fyi. Still working on it. I did this:
[code]
$(document).on("pageshow", "#breadcrumb", function breadCrumb(){
var here = location.href.split('/').pop().split('_');
var parts = [{ "text": 'Home', "link": '/' }];
console.log(here);
for( var i = 0; i < here.length; i++ )
{
var part = here[i];
var text = parts.toUpperCase();
var link = '/' + here.slice( 0, i + 1 ).join('_');
parts.push({ "text": text, "link": link });
};
document.getElementById('breadcrumbs').innerHTML = parts[i];
[code]
then added document.write(breadcrumb()); in the div below
Comment for this answer: Still no luck. Still invisible.
Comment for this answer: Well, it worked. Although there's a slash showing up in front of the Home link. I really appreciate your patience and time on this.
Comment for this answer: it's telling me that an upvote requires a 15 reputation. I haven't gotten there yet, I'm afraid. I am sorry.
Comment for this answer: you still need to iterate over the ```parts``` array to draw the breadcrump. Your question doesn't have that function yet.
|
Title: Fetching data from C# Asp Server with a Windows Service
Tags: c#;tcp
Question: I have a Windows service that loops every second and polls a server (in ASP WebForms Framework 4, not MVC) for new informations by connecting in HTTPS and sending a 'home-made' ciphered data and receiving the response, ciphered as well.
The issues of this method are both resource and time consumptions.
Every second, the service has to create a connection, cipher a data and decrypt the response.
I was thinking about using TcpConnections to :
Connect to the server once and for all
Receive new informations from the server when they come and treat them locally in my service
I was trying to do so, like this :
Server side code (in the Global.asax for now)
```protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Task.Run(Run);
}
public static async Task Run()
{
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8080); //Any IPAddress that connects to the server on any port
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Initialize a new Socket
socket.Bind(ip); //Bind to the client's IP
socket.Listen(10); //Listen for maximum 10 connections
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "Welcome"; //This is the data we we'll respond with
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome); //Encode the data
client.Send(data, data.Length, SocketFlags.None); //Send the data to the client
}
catch(Exception e)
{
Console.WriteLine($"Error : {e.Message} {e.StackTrace}");
}
}
```
(a method is also created to send data to the client out of the task above).
Client side Code
```const int PORT_NO = 8080;
const string SERVER_IP = "localhost";
static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("(902)965-4041"), 8080);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ip); //Connect to the server
}
catch (SocketException e)
{
Console.WriteLine($"Unable to connect to server : {e.Message} {e.StackTrace}");
return;
}
Console.WriteLine("Type 'exit' to exit.");
while (true)
{
string input = "aaaaa";
if (input == "exit")
break;
server.Send(Encoding.ASCII.GetBytes(input)); //Encode from user's input, send the data
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data); //Wait for the data
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); //Decode the data received
Console.WriteLine(stringData); //Write the data on the screen
System.Threading.Thread.Sleep(5000);
}
}
```
The connection seems to work for the first message, I manage to send/receive data from the client and the server. But then the 'client' server-side object disposes itself (becomes null).
Is it because the Tcp Connection is not persistant ?
If so, I tried to add this line :
```socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
```
But then I get the following exception :
```An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
```
How can I prevent my TcpConnection from closing after the client receives the data sent from the server ?
Is there a more secure way to exchange data from server to client ? Maybe by using an SSL TLS Connection like this : C# TcpClient reading multiple messages over persistent connection ? I was thinking of SignalR but I'm not sure it works on Framework 4 Web App environment
Comment: SignalR is a nice workaround and is available with the .NET 4.0 framework -> official documentation https://msdn.microsoft.com/en-us/library/microsoft.aspnet.signalr(v=vs.100).aspx
Comment: Is there a specific reason you are writing your own custom server and not just using the built in WebApi/MVC 5 services that come with modern .net?
Comment: The reason is mostly historical, this server was designed 5 years ago and served as interface between smartphones and software clients (based on encrypted XML exchanges)
Comment: Thanks a lot. Seems like SignalR was what i was looking for after all!
Comment: the sockets are created in your methods and as soon as the methods terminate the sockets will close. The sockets need to be in global space to stay open. You application also needs to block so it doesn't close after processing one message.
|
Title: Calling the instance of a static method
Tags: java;static
Question: Good day!
I am a little bit confused. I want to use a calendar so I searched it in the internet and encountered the following code:
```Ca1endar c = Calendar.getlnstance();
c.set(2011,2, 5,1,25);
```
But I learned that this is a static method:
```Calendar.getlnstance();
```
How come I can get the Instance of the Calendar(Abstract Class) if the method called is static?
I really want to understand it. So next time I can also create a Static method that can create an instance.
Thank you.
Comment: Thats a static builder method. Its a replacement for using contructor.
Here is the accepted answer: It's the static factory method. The idea is the method is the one calling the constructor and it returns the constructed object.
The body of ```Calendar.getInstance()``` is perhaps something like this:
```return new SomeCalendar(now);
```
where ```SomeCalender``` is an concrete implementation of the abstract class ```Calendar```. Some of the advantages are: you don't have to care about the underlying class (as far as you know it's just a Calendar), and the underlying implementation can change without affecting you (for example, the code can be changed to ```return new AnotherCalendar()``` and you don't have to change anything in your code)
Since it is a static method, you can call it on the type itself (```Calendar.getInstance();```) as opposed to an instance of that type (```Calendar c = ...; c.getInstance();```).
Comment for this answer: Hum I am surprised this is marked as the answer seeing as Calendar is abstract and most certainly the body of the method is not new Calendar(). The reason the method exists is so that you the underlying system can swap out the raw implementation of Calendar while maintaining the same interface which is Calendar.
Here is another answer: The fact the factory method is static does not infer that the Calendar is static - it just provides an access mechanism to create a Calendar.
Check out this post about how to use this pattern yourself:
http://today.java.net/pub/a/today/2005/03/09/factory.html
It also explains a bit more about the principles behind the pattern.
I second the recommendation to read Effective Java though - it's a great book despite it's age!
Here is another answer: An instance method requires that you already have an instance to call the method on.
Being static does not mean that you can't take instances as a parameter, return an instance as a result or create an instance. It just means that the method can be called without first having an instance, and that in the method there is no such thing as ```this```.
You generally wouldn't want this sort of factory method to be an instance method (non-static) because it would mean you'd need to already have an instance to create a new one. How would you create the first one?
(Non-static factory methods do exist, but they are more commonly used for creating a different type of object. For example, a Builder or Factory class will typically have a method that creates instances of some other class.)
Here is another answer: Its a alternative way to create a new object in java. Traditionally constructors are the way to go, but since there are some advantages for using a static factory, its preferred over plain vanilla constructors.
You should really pick up Effective Java by Joshua Bloch. Its the first item in the book. Preferring static factory for contructor. The advantages he mentions are:
1_ Since static factory have names that could be descriptive.
2_ Then can be made to return any subtype, not just the type of the particular class.
3_ You can handle concepts like caching and singletons with in a factory method. (you do not have to blindly create new object).
4_ To reduce the initialization code. For instance instead of List newList = new ArrayList, we can have a method like getStringList();
The fourth advantage is something I am not very particular about, but I see Google Guava framework has implemented it.Please pick up the book. Its one of the best programming book for java.
Comment for this answer: @newbie: How about you go buy the book.
Comment for this answer: @Shakedown I don't have money. :( So I'll download it instead!
Comment for this answer: Actually, Item #1 is *consider* static factor methods instead of constructors. But in any case, I don't think this really answers the OP's question which seems to be more of a "how does this work" rather than a "why did they do it this way" sort of question.
Here is another answer: Java does this sort of thing all over the place. Look at the XML API.
This is a way to maintain a single interface into a ```Calendar``` system even if the underlying implementation is changed. Yes the method is a factory method, however, the point some of the other answers seem to miss is that it can return different implementations of ```Calendar```.
That is how Calendar can be returned even if it is abstract. A overly simplified implementation of ```getInstance()``` could be
```Calendar getInstance()
{
return new GregorianCalendar();
}
```
The caller of ```getInstance()``` does not need to know the implementation type in order to get the current date and time.
I recommend looking through OpenJDK
|
Title: How to average every 7 cells without repeating the same cells
Tags: excel;excel-formula;excel-2010;excel-2007
Question: I have a long row of data that I am averaging week-by-week. I would like to grab the first 7 cells with data and be able to drag my formula over so that it grabs the next 7 days of data. Every time that I try this it always grabs the adjacent cell and averages numbers that I have already averaged in the previous formula:
So what happens is that when I drag to the right it grabs D60:K60 and I want it to grab L60:R60 instead.
How would I accomplish this?
Comment: **7** cells, **8** cells or **9** cells? You've mentioned 7 cells and and referred to *a week's data* but C:K from your formula is 9 cells and D:K is 8. Only L:R is 7 cells.
Here is another answer: This formula uses ```OFFSET``` to both stagger and shape the range which is calculated by ```AVERAGE```.
```=AVERAGE(OFFSET($C60, 0, (COLUMN(A:A)-1)*7, 1, 7))
```
Fill right as necessary. It will process ```AVERAGE(C60:I60)``` then ```AVERAGE(J60:P60)```, etc.
EDIT:
As ```OFFSET``` is a volatile function that re-calculates whenever any calculation cycle occurs within the workbook, here is a non-volatile equivalent.
```=AVERAGE(INDEX(6:6, 1, (COLUMN(A:A)-1)*7+3):INDEX(6:6, 1, (COLUMN(A:A)-1)*7+9))
```
|
Title: Blueimp/jQuery File Upload autoUpload fail when one of the selected files is not image
Tags: jquery;jquery-file-upload;blueimp
Question: My acceptFileTypes option is standard ```/(\.|\/)(gif|jpe?g|png)$/i```. The problem is, autoUpload fires correctly only if all the selected files are ```gifs/jpgs/pngs```. The moment there's a file that isn't an image, autoUpload doesn't fire.
```jqXHR = $('#button').fileupload({
url: uploadURL,
dataType: 'json',
formData: {
'data': myData
},
autoUpload: true,
sequentialUploads: true,
singleFileUploads: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
disableImageResize: true,
previewMaxWidth: 240,
previewMaxHeight: 240,
previewThumbnail: false,
previewCanvas: true,
previewCrop: true
})
.on('fileuploadadd', function(e, data) {
//nothing here
})
.on('fileuploadprocessalways', function(e, data) {
var index = data.index,
file = data.files[index];
if (file.error) {
console.log(file.error);
}
else {
var node = $('<li/>').addClass('node').prependTo($(data.context)),
inner = $('<div/>').addClass('node-inner').appendTo(node),
controls = $('<div/>').addClass('node-controls').appendTo(inner);
if (file.preview) {
inner.append(file.preview);
}
inner.append(nodeProgress.clone());
controls.append(cancelBtn.clone(true).data(data));
}
});
```
I'm open to all suggestions. Basically I want the user to select files, and once selected, it will start uploading. I tried setting ```autoUpload``` to ```false``` and do all the validation and error handling manually in ```fileuploadadd```, but the problem is it throws all kinds of errors when I do a ```data.files.splice(index, 1);```. I'm guessing it's because the array pointer gets messed up and the script is written to handle that. I also tried firing ```data.submit()``` manually everytime an image is selected, which was pretty dumb of me because then ```data.submit()``` gets fired as many times as there are images selected.
|
Title: Sudarsana Homam - Timings for conducting
Tags: mantras;tradition;sudarsana;homam
Question: I learnt from pundits and scholars that poornahuthi for sudarsana homam should be put within 12 noon. It takes six hours to perform sudarsana homam. Normally homams should be done from 5 am and finish within 12 noon. [at the max]. But nowadays I observe that the sudarsana homam is being carried out by few people in the evening; starting from 6 pm and ending by 9 pm. If the homam is performed by an individual it will benefir the whole universe. On the other hand if it is done after sunset will it cause retro effect? Presently the whole world is reeling in pandemic. Can this be answered by appropriate citings?
Note: My company sent an invitation for puja for day after tomorrow.. In that it is mentioned Mahasudarsana Homa starts from 7/30 pm and ends by 10pm?
Comment: ashvameda and other yagna conducted yearly long also, its deemed asupucious based on region you live, andhra prefers night time as there is no rahu, yama, goolikai or ketta kala falling in the night..reference SM Bhagavatam Krishna performed ashvemeda he went vaikuta and came back to complete ashwameda
Comment: @Prasanna Pl note that homams and yagnas are different. Homam timing I refer to IST.
Comment: homa is short form of yagna Andhra and Karanataka preference is given in night.. please check the marriage rituals. Yes its asupicios to conduct homam without having food.. other than this only region based difference only i see
Comment: @ prasanna Poornahuthi should be put by noon.
|
Title: One edit to record trigger PBR multiple times?
Tags: workflow;process-builder
Question: Will a PBR be triggered multiple times if multiple qualifying changes occur in a single transaction? For example:
PBR triggers off an edit to a Contact
First criteria is "First Name IS NULL false"
Second criteria is "Last Name IS NULL false"
Each criteria has a different set of actions
If I open a Contact that has no First Name or Last Name, then add values to them both at the same time and save it, will the PBR fire twice -- once for each criteria -- or will it only fire once and only run through the first choice?
Here is the accepted answer: In that circumstance, you're not looking at Order of Execution and potential recursion during a transaction, but looking rather at how Process Builder evaluates its criteria.
The process itself will fire only once in the situation you described. However, you can configure whether the individual criteria nodes, when they execute, result in ending the process execution or continuing to evaluate the next criterion node and potentially executing its associated actions.
Configure this by clicking the "Stop" icon at the end of the pipeline for one criterion, and choosing to continue to evaluate the next criterion.
Remember, though, that this all takes place in one Process Builder execution. It is possible to invoke the process itself twice in a transaction, if a record update results in further updates to that record, for example.
A final note: ```Contact.LastName``` is a required field. It'll never be ```null```.
Reference
Execute Actions on More Than One Criteria
Comment for this answer: Thanks for the insight -- and sorry for the bad example re: Last Name, that's not the actual field in question, just the first ones that came to mind when trying to explain.
|
Title: va-args not resolving correctly
Tags: c;variadic-functions
Question: I have the following function:
```void Register(Data* _pData, uint32 _Line, const char* _pFile, ...)
{
va_list Args;
va_start(Args, _pFile);
for(uint i = 0;i m_NumFloats; ++i)
{
_pData->m_Floats[i] = va_arg(Args, fp32);
}
va_end(Args);
}
```
Which is called by the macro:
```#define REG(_Name, ...)\
{\
if(s_##_Name##_Data.m_Enabled)
Register(&s_##_Name##_Data, __LINE__, __FILE__, ##__VA_ARGS__);\
}\
```
With the usage:
```REG(Test, (fp32)0.42f);
```
The Data-struct looks like:
```
struct Data
{
int m_NumFloats;
fp32 m_Floats[4];
}
```
The creation-macro of Data creates the static ```Data g_YourName_Data``` and initializes it correctly with a maximum of 4 m_NumFloats.
The va_arg call resolves to 0.0. s_Test_Data exists and the Register-function is called appropriate. va-list just simply won't let me resolve the first argument into the float that I passed it into. Is there anything specific that I'm missing?
Comment: @AndreyT "What is ## doing in front of `__VA_ARGS__`?" - it is making it possible for a variadic macro to receive zero arguments.
Comment: @AndreyT This is a special construct, I'm not sure whether or not it is standard. The preprocessor will elimate the trailing comma if `__VA_ARG__` is preceded by the token pasting operator and there are no variadic arguments.
Comment: There is no `_Name_Data`. It's a macro using `_Name` to find a statically declared object which in this case expands to `_Test_Data`. So the macro does use `_Name`. The `##` Is used to strip the `,` if no actual extra parameters are passed.
Comment: What is `_Name_Data`? Why are you declaring `_Name` parameter in your macro, when your macro definition does not use `_Name` anywhere at all? What is `##` doing in front of `__VA_ARGS__`?
Comment: @H2CO3: Could you elaborate a bit on that? What difference does it make (compared to the same thing without the `##`)? And how will it help with the issue of trailing `,`?
Here is the accepted answer: Try:
```#define REG(_Name, ...)\
{\
if(s_##_Name_Data.m_Enabled)\
Register(&s_##_Name_Data, __LINE__, __FILE__, __VA_ARGS__);\
}
```
Get rid of the token-pasting operator. You we're also missing a '\' in your macro (maybe a copy-n-paste error?).
Also, use ```va_arg()```, not ```va_args()```. And I'm not sure if you meant for ```_Name``` to be ```_Name_Data``` or the other way around.
Finally, I assumed that ```fp32``` was an alias for ```float```; GCC had this to say to me:
```C:\TEMP\test.c:22: warning: `fp32' is promoted to `double' when passed through `...'
C:\TEMP\test.c:22: warning: (so you should pass `double' not `fp32' to `va_arg')
C:\TEMP\test.c:22: note: if this code is reached, the program will abort
```
You should heed that warning. The program does crash for me if I do not.
Comment for this answer: @Zack - thanks for that information. I knew the GCC had a way to deal with empty `__VAR_ARGS__`, but didn't remember that that was it.
Comment for this answer: @Simon: "I'm using Microsoft's compiler and not GCC" - I was really, really surprised that GCC diagnosed that problem in a warning. I doubt that it's something I would have figured out on my (at least not without quite a debugging effort). This is one reason I try to compile snippets with problems using several compilers. Kudos to GCC for diagnosing that.
Comment for this answer: Thanks for the answer Michael, and sorry for the copy-and-paste errors. I'll edit the post to make it correct. I'm not getting any such warnings. The real code handles the case where no va-args are present, the number of arguments expected are defined earlier.Should you really append an extra `\ ` on the last line of the macro? I'm quite certain that you don't need that (since I have several macros which don't have it and it would have caused some compiler errors if it didn't). `_Name` is inserted into the identifier that we're accessing. In this case the identifier would become `s_Test_Data`.
Comment for this answer: Oh, I'm using microsoft's compiler and not GCC.
Comment for this answer: Changing it into reading a `double` made it work though! Thanks a ton!
Comment for this answer: @Michael: Indeed, GCC tend to warn about a lot more than MSVC so I should probably try to set up my build-system to work with GCC as well just to catch more errors. Thanks again!
Comment for this answer: The `, ## __VA_ARGS__` thing is a GCC extension which makes the comma go away if `__VA_ARGS__` expands to no tokens (i.e. if REG() is called with only one argument). In *this case* it's inappropriate because Register() must receive at least one anonymous argument, and you'd like that to be a compile error rather than garbage at runtime, but it's not automatically wrong.
Comment for this answer: You definitely don't want a backslash on the last line of the macro, it'll suck whatever's on the *next* line of source into the macro as well. Probably right now that's a blank line and so it's harmless, but then someone comes along and decides that the code would look better without the blank line and hilarity ensues.
|
Title: Dynamic array of *points crashing & leaking memory after reallocation - why?
Tags: c;memory-leaks
Question: Edit: To clarify, I'm after an array of pointers, of type ```Point3d``` structs.
I messed up something that seemed so simple. I've read several posts here on dynamically allocated arrays, but I still can't see where I went wrong.
In the code below I'm trying to make a dynamically allocated pointer array of Point3d structs. That's all. But I'm messing up the memory allocation (valgrind reports 40 bytes lost etc) and when reallocating the array more than once (ALLOC_COUNT > 1) it crashes on deallocation. Where am I doing it wrong?
I aim for C99 only. Did this on Windows, CLion with valgrind on WSL.
The complete program:
```#include <stdio.h>
#include <stdlib.h>
typedef struct Point3d_t {
double X;
double Y;
double Z;
} Point3d;
size_t increment_size = 0;
size_t vertex_count = 0;
size_t current_size = 0;
```
```
void *destructVertices(Point3d **vertices) {
if (vertices != NULL && ((current_size > 0) || (vertex_count > 0))) {
for (int i = 0; i < current_size; ++i) {
free(vertices[i]);
vertices[i] = NULL;
}
}
return NULL;
}
size_t allocateVertices(Point3d **vertices) {
const size_t new_size = current_size + 1 + increment_size;
Point3d **expanded_items = realloc(*vertices, new_size * sizeof(Point3d *));
if (!expanded_items) { // Allocation failed.
free(*vertices); fprintf(stderr, "RIL: Error reallocating lines array\n");
expanded_items = NULL; exit(0);
}
else if (expanded_items == vertices) {
expanded_items = NULL; // Same mem addr, no need to change
}
else {
vertices = expanded_items; // mem allocated to new address, point there
}
current_size = new_size;
return current_size;
}
```
```/// returning the last item count, which can also be interpreted
/// as true (>0) or false (0) by the caller
size_t addVertex(Point3d point, Point3d **vertices) {
if (vertex_count == current_size) {
if (!allocateVertices(vertices)) return 0;
}
Point3d* p = malloc(sizeof(Point3d));
if (!p) exit(99);
p->X = point.X;
p->Y = point.Y;
p->Z = point.Z;
vertices[vertex_count] = p;
vertex_count += 1;
return vertex_count; // last item count
}
Point3d *m_vertices[1];
```
Increasing ALLOC_COUNT to something larger than 1 (causing realloc) will crash on deallocate.
```#define PT_COUNT 4
#define ALLOC_COUNT 1
int main() {
increment_size = PT_COUNT;
current_size = 0;
vertex_count = 0;
printf("Size of Point3d = %zu\n", sizeof(Point3d)); // fake error
printf("Size of *Point3d = %zu\n", sizeof(Point3d *)); // fake error
printf("Size of **m_vertices = %zu\n", sizeof(m_vertices)); // fake error
printf("Size of *m_vertices = %zu\n", sizeof(*m_vertices)); // fake error
printf("Size of *m_vertices[0] = %zu\n", sizeof(*m_vertices[0])); // fake error
printf("---------------------------\n"); // fake error
m_vertices[0] = NULL; //malloc(sizeof(Point3d*));
// new points
for (int i = 0; i < (PT_COUNT * ALLOC_COUNT); ++i) {
Point3d p;
p.X = 1.0 + (i * 0.001);
p.Y = 2.0 + (i * 0.001);
p.Z = 3.0 + (i * 0.001);
const size_t n = addVertex(p, m_vertices);
if (!n) exit(1);
}
printf("vertices.Capacity = %zu\n", current_size);
printf("vertices.Count = %zu\n", vertex_count);
destructVertices(m_vertices);
//free(*m_vertices);
return 0;
}
```
Here is the accepted answer: The final code (some fwd declarations and function prototypes omitted).
As indicated earlier, the aim was managing a dynamic array of pointers, without the leaks. Tested with Valgrind (which complains only on the uninitialized space resulting from ```realloc```, although I actually assign ```(void*)NULL``` to the newly (re)allocated space, but anyway).
Some function pointer prototypes (```fn_...```) omitted. The code style is odd, but I need to paste in a lot of code from some existing C# prototyping so I use C# style in part to make it easier to copy-paste in both directions.
```typedef struct Point3d_t Point3d;
typedef struct Point3d_t
double X;
double Y;
double Z;
} Point3d;
// This "list owner" was omitted in the OP.
typedef struct MeshVertexList_t {
size_t AllocationsCount;
size_t Capacity;
size_t Count;
size_t Increment;
f_Add Add;
f_allocateVertices allocateVertices;
f_Destroy Destroy;
Point3d **Items; // array of ptr
} MeshVertexList;
```
```MeshVertexList *New_MeshVertexList(size_t increment) {
MeshVertexList *mvlist = malloc(sizeof(MeshVertexList));
mvlist->AllocationsCount = 0;
mvlist->Capacity = 0;
mvlist->Count = 0;
mvlist->Increment = increment;
mvlist->Add = Add;
mvlist->Destroy = Destruct_MeshVertexList;
mvlist->allocateVertices = allocateVertices;
mvlist->Items = NULL;
return mvlist;
}
```
```// Assigned to function pointer
size_t Add(MeshVertexList *self, Point3d *point) {
if (self->Count == self->Capacity) {
int res = (int) allocateVertices(self);
if (!res) return 0;
}
self->Items[self->Count] = point;
self->Count++;
return self->Count; // last item count
}
```
```// Assigned to function pointer
size_t allocateVertices(MeshVertexList *Vertices) {
size_t new_capacity = 1;
if (Vertices->Capacity > 0) new_capacity = Vertices->Capacity + Vertices->Increment;
void *items_tmp = realloc(Vertices->Items, sizeof(*Vertices->Items) + new_capacity * sizeof(Point3d*));
if (!items_tmp) {
Destruct_MeshVertexList(Vertices);
perror("RIL: Error reallocating lines array\n");
exit(EXIT_ALLOC_ERROR);
} else if (items_tmp == Vertices->Items) {
items_tmp = NULL; // Same mem addr, no need to change
} else {
Vertices->Items = items_tmp;
}
for (int i = Vertices->Capacity; i < new_capacity; ++i) {
Vertices->Items[i] = (void *)NULL; // Valgrind doesn't detect this!
}
Vertices->AllocationsCount++;
Vertices->Capacity = new_capacity;
return Vertices->Capacity;
}
```
```// Assigned to function pointer
void Destruct_MeshVertexList(MeshVertexList *Vertices) {
for (int i = 0; i <= Vertices->Capacity; ++i) {
if (Vertices->Items[i] != NULL) {
free(Vertices->Items[i]); // deallocating point
Vertices->Items[i] = NULL;
}
}
Vertices->Capacity = 0;
Vertices->Count = 0;
Vertices->Increment = 0;
Vertices->Add = NULL;
Vertices->allocateVertices = NULL;
free(Vertices->Items);
Vertices->Items = NULL;
free(Vertices);
Vertices = NULL;
}
```
```
typedef struct MeshObj_t {
MeshVertexList *Vertices;
} MeshObj;
#define ALLOC_INCREMENT 1 // <-- debug: realloc for each added pt
#define PT_COUNT 10
int main() {
const clock_t start = clock();
MeshObj m;
m.Vertices = New_MeshVertexList(ALLOC_INCREMENT);
printf("Size of Point3d = %zu\n", sizeof(Point3d));
printf("Size of *Point3d = %zu\n", sizeof(Point3d *));
printf("Size of m_vertices = %zu\n", sizeof(m.Vertices));
//printf("Size of *m_vertices[0] = %zu\n", sizeof(*m_vertices[0]));
printf("---------------------------\n");
for (int i = 0; i < (PT_COUNT); ++i) {
Point3d *p = malloc(sizeof(Point3d));
p->X = 1.0 + (i * 0.001);
p->Y = 2.0 + (i * 0.001);
p->Z = 3.0 + (i * 0.001);
size_t n = m.Vertices->Add(m.Vertices, p);
p = NULL;
if (!n) exit(1);
}
```
``` const clock_t stop = clock();
const double elapsed_time = (double) (stop - start) / CLOCKS_PER_SEC;
printf("Vertices->Capacity : %zu\n", m.Vertices->Capacity);
printf("Vertices->Count : %zu\n", m.Vertices->Count);
printf("Elapsed time : %lf ms\n", elapsed_time);
printf("---------------------------\n");
for (int i = 0; i < m.Vertices->Count; ++i) {
printf("%f %f %f\n", m.Vertices->Items[i]->X, m.Vertices->Items[i]->Y, m.Vertices->Items[i]->Z);
}
m.Vertices->Destroy(m.Vertices);
m.Vertices = NULL;
return 0;
}
```
|
Title: android app crashes on launch when i try to declare an intent in kotlin
Tags: android;kotlin;android-intent;android-pendingintent
Question: please help
```val snoozeIntent = Intent(this, SnoozeReceiver181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16lass.java).apply {
action = "ACTION_SNOOZE"
putExtra("EXTRA_NOTIFICATION_ID", 0)
}
```
i'm trying to follow the documentation here:
https://developer.android.com/training/notify-user/build-notification#Actions
my broadcast class:
```class SnoozeReceiver: BroadcastReceiver() {
private val REQUEST_CODE = 0
override fun onReceive(context: Context, intent: Intent) {
val triggerTime = SystemClock.elapsedRealtime() + DateUtils.MINUTE_IN_MILLIS
val notifyIntent = Intent(context, AlarmReceiver181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16lass.java)
val notifyPendingIntent = PendingIntent.getBroadcast(
context,
REQUEST_CODE,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager,
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerTime,
notifyPendingIntent
)
val notificationManager = ContextCompat.getSystemService(
context,
NotificationManager181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16lass.java
) as NotificationManager
notificationManager.cancelAll()
}
}
```
Android manifest :
```<receiver
android:name=".receiver.SnoozeReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="ACTION_SNOOZE"/>
</intent-filter>
</receiver>
```
Comment: Thanks so much @Md.Asaduzzaman it worked but now it's happening with the next line of code which is
```
val snoozePendingIntent: PendingIntent =
PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)
```
can you also tell ne the reason why is this happening i'm new to android environment
Comment: Are you initializing this variable outside of a method? If so, that's your problem. You need to initialize the variable after your `Activity` (or whatever) has been completely constructed (ie: after `onCreate()` has been called).
Comment: Use `Intent().apply` instead
Comment: From where you try to implement this? Please add more details of your implementation
|
Title: Restore program from system tray clicking shortcuts in desktop in c#
Tags: c#;system-tray
Question: Im using Visual studio 2012, windows form. I need restore application from system tray when I click shortcut on desktop.
Im using this code that prevent double istance of same application, but not open application from system tray.
```[STAThread]
static void Main()
{
string mutex_id = "my application";
using (Mutex mutex = new Mutex(false, mutex_id))
{
if (!mutex.WaitOne(0, false))
{
Form1 fForm;
fForm = new Form1();
fForm.Show();
fForm.WindowState = FormWindowState.Normal;
fForm.ShowInTaskbar = true;
// MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
```
I readed some questions here in stackoverflow, without luck. What I need modify in this code? thanks in advance!
Comment: http://stackoverflow.com/a/14326291/17034
Comment: I think this should answer your question: http://stackoverflow.com/questions/4592852/restoring-window-from-the-system-tray-when-allowing-only-one-instance-of-that-pr
Here is the accepted answer: You could use Mutex to accomplish this. Here is a bolt-on solution from CodePlex, that is very easy to incorporated into your program. The solution does provides the following features:
If the First Instance is Minimized to the System Tray (aka
"Notification Area"), Restore It
Activating the First Instance
Prevent a Second Instance from Opening
Here is another answer: Check this question and answers with different ideas on getting instance of app that is already running. And check this link - http://msdn.microsoft.com/en-us/magazine/cc163741.aspx (look fo mutex).
|
Title: How to apply paired t.test or Wilcoxon test to my data
Tags: r;usage-statistics
Question: Let's start with a data:
```structure(list(Group = c("Mark", "Matt", "Tim", "Tom"), `1` = c(0.749552072382562,
1.06820497349356, 1.00116263663573, 0.864987635002866), `2` = c(1.00839505250436,
0.796306651704629, 1.02603677593328, 1.00321936833133), `3` = c(0.736638669191169,
0.973483626272054, 1.14805519301778, 0.899272693725192), `4` = c(0.728882841159455,
0.871211836418332, 1.0442119745299, 0.859935708928745), `5` = c(0.749552072382562,
1.06820497349356, 1.00116263663573, 0.864987635002866), `6` = c(1.00839505250436,
0.796306651704629, 1.02603677593328, 1.00321936833133), `7` = c(0.736638669191169,
0.973483626272054, 1.14805519301778, 0.899272693725192), `8` = c(0.728882841159455,
0.871211836418332, 1.0442119745299, 0.859935708928745), `9` = c(0.749552072382562,
1.06820497349356, 1.00116263663573, 0.864987635002866), `10` = c(1.00839505250436,
0.796306651704629, 1.02603677593328, 1.00321936833133), `11` = c(0.736638669191169,
0.973483626272054, 1.14805519301778, 0.899272693725192), `12` = c(0.728882841159455,
0.871211836418332, 1.0442119745299, 0.859935708928745), `13` = c(0.749552072382562,
1.06820497349356, 1.00116263663573, 0.864987635002866), `14` = c(1.00839505250436,
0.796306651704629, 1.02603677593328, 1.00321936833133), `15` = c(0.736638669191169,
0.973483626272054, 1.14805519301778, 0.899272693725192), `16` = c(0.728882841159455,
0.871211836418332, 1.0442119745299, 0.859935708928745), `17` = c(0.766036811789943,
0.871085862829362, 1.02210371210681, 0.937452345474458), `18` = c(1.0357237385154,
1.02805558505417, 0.946794300033338, 1.04688545274238), `19` = c(0.763210436944137,
0.801397021884422, 0.952553568039278, 0.990226493248718), `20` = c(0.789338028300063,
0.822815644347233, 0.958462750269733, 1.04183361434861), `21` = c(0.766036811789943,
0.871085862829362, 1.02210371210681, 0.937452345474458), `22` = c(1.0357237385154,
1.02805558505417, 0.946794300033338, 1.04688545274238), `23` = c(0.763210436944137,
0.801397021884422, 0.952553568039278, 0.990226493248718), `24` = c(0.789338028300063,
0.822815644347233, 0.958462750269733, 1.04183361434861), `25` = c(0.766036811789943,
0.871085862829362, 1.02210371210681, 0.937452345474458), `26` = c(1.0357237385154,
1.02805558505417, 0.946794300033338, 1.04688545274238), `27` = c(0.763210436944137,
0.801397021884422, 0.952553568039278, 0.990226493248718), `28` = c(0.789338028300063,
0.822815644347233, 0.958462750269733, 1.04183361434861), `29` = c(0.766036811789943,
0.871085862829362, 1.02210371210681, 0.937452345474458), `30` = c(1.0357237385154,
1.02805558505417, 0.946794300033338, 1.04688545274238), `31` = c(0.763210436944137,
0.801397021884422, 0.952553568039278, 0.990226493248718), `32` = c(0.789338028300063,
0.822815644347233, 0.958462750269733, 1.04183361434861), `33` = c(0.937894856206067,
NA, 1.00383773624603, 1.04181193834546), `34` = c(1.03944921519508,
NA, 0.983868286249464, 1.10409633668759), `35` = c(0.949802513948967,
NA, 1.06522152108054, 1.04376827636719), `36` = c(0.965871712940006,
NA, 1.18437146805406, 1.01355356488254), `37` = c(0.937894856206067,
NA, 1.00383773624603, 1.04181193834546), `38` = c(1.03944921519508,
NA, 0.983868286249464, 1.10409633668759), `39` = c(0.949802513948967,
NA, 1.06522152108054, 1.04376827636719), `40` = c(0.965871712940006,
NA, 1.18437146805406, 1.01355356488254), `41` = c(0.937894856206067,
NA, 1.00383773624603, 1.04181193834546), `42` = c(1.03944921519508,
NA, 0.983868286249464, 1.10409633668759), `43` = c(0.949802513948967,
NA, 1.06522152108054, 1.04376827636719), `44` = c(0.965871712940006,
NA, 1.18437146805406, 1.01355356488254), `45` = c(0.937894856206067,
NA, 1.00383773624603, 1.04181193834546), `46` = c(1.03944921519508,
NA, 0.983868286249464, 1.10409633668759), `47` = c(0.949802513948967,
NA, 1.06522152108054, 1.04376827636719)), .Names = c("Group",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34",
"35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45",
"46", "47"), row.names = c(NA, 4L), class = "data.frame")
```
Each row is a collection of ratio which I got from comparison of two groups. I would like to know if the ratios are significantly different than 1. So, I would like to test if each row (vector) is different than 1 by using two tests mentioned in a title. How to apply those test to my data ? Please consider that each row may have a different length. ```NAs``` should be ignored. As and output I would like to have a table with 3 columns: ```Group name```, ```p-value t-test```, ```p.value Wilcoxon```.
Can someone help mi with that ?
Here is the accepted answer: There might be a way to use the rows of the original data frame you have, but I'd strongly recommend to work with columns (tidy data frame).
```library(dplyr)
library(tidyr)
# assuming this is the name of your original dataset
dt
# reshape to create a column for each name
dt2 = data.frame(t(dt), stringsAsFactors = F)
names(dt2) = dt2[1,]
dt2 = dt2[-1,]
dt2[,names(dt2)] = sapply(dt2[,names(dt2)], as.numeric)
# reshape to create a column of names and values
dt3 = dt2 %>%
gather(name,value,Mark:Tom) %>%
filter(!is.na(value)) # remove NAs
dt3 %>%
group_by(name) %>% # for each name
summarise(pval_ttest = t.test(value, mu=1, data=.)$p.value, # calculate t test p value
pval_wilc = wilcox.test(value, mu=1, data=.)$p.value) # calculate Wilcoxon p value
# # A tibble: 4 × 3
# name pval_ttest pval_wilc
# <chr> <dbl> <dbl>
# 1 Mark 4.408038e-09 1.020895e-06
# 2 Matt 6.679416e-06 2.502045e-04
# 3 Tim 1.777060e-02 6.932590e-02
# 4 Tom 2.433548e-01 5.148382e-01
```
Some additional info about how a paired t test "understands" the measurements you give it and why differences and ratios might give different results.
Consider the following examples:
```# paired t test of 2 vectors of same size (before and after treatment)
# it compares the means of those vectors
t.test(1:10, 13:4, paired = T)
# Paired t-test
#
# data: 1:10 and 13:4
# t = -1.5667, df = 9, p-value = 0.1516
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
# -7.331701 1.331701
# sample estimates:
# mean of the differences
# -3
# t test that compares one vector's mean to 0
# that vector is the differences of the two initial vectors
t.test(1:10 - 13:4, mu=0)
# One Sample t-test
#
# data: 1:10 - 13:4
# t = -1.5667, df = 9, p-value = 0.1516
# alternative hypothesis: true mean is not equal to 0
# 95 percent confidence interval:
# -7.331701 1.331701
# sample estimates:
# mean of x
# -3
# t test that compares one vector's mean to 1
# that vector is the ratios of the two initial vectors
t.test(1:10 / 13:4, mu=1)
# One Sample t-test
#
# data: 1:10/13:4
# t = -0.46036, df = 9, p-value = 0.6562
# alternative hypothesis: true mean is not equal to 1
# 95 percent confidence interval:
# 0.3229789 1.4480623
# sample estimates:
# mean of x
# 0.8855206
```
You can see that the paired t test is a simple t test of the differences' vector, which is possible as you have 2 vectors of the same length (before after treatment). It's not the same with a simple t test of the ratios' vector.
So, it's reasonable to have different results, but in some applications the ratio test is better. Check your bibliography on that.
Comment for this answer: The statistical test we're using here is not a paired t-test or Wilcoxon test, as both tests compare a set of values to 1 (pre-defined value). Paired test requires a direct comparison of a set of measurements of person X with another set of measurements of the same person X. Maybe the bibliography mentions that as a paired test, but it's not. The statistical tests have no idea about what those (ratio) values represent.
Comment for this answer: Practically you can compare each user's values with a vector of 1s. But, theoretically, what does this vector represent? You never measured those 1s. Also, still not paired test. See more about paired t tests here: http://www.biostathandbook.com/pairedttest.html . It seems to me that you can do a paired t test before you divide your measurements and compare the ratios to 1.
Comment for this answer: Also have a look at this: http://www.graphpad.com/support/faq/the-ratio-paired-t-test/ to see whether is better to consider differences or ratios. I'm sure that if the bibliography considers ratios there should be a good reason behind it.
Comment for this answer: Well, now I'm confused even more, as in the link you sent you mention "two group of people. One is a control group the other one was treated with a drug". That's definitely not a paired test, unless I'm missing something in the experiment design. In paired test you need one measurement or person X before the drug and one after the drug (same person). Then, it's a different story whether you'll investigate the difference of those values or the ratio. One story is "experiment design" and the other is "method of comparison".
Comment for this answer: If they represent the same "person" (double check that with someone that has experience on biological applications) then it's correct to use a paired t test to compare the differences of those measurements. Or, you can get the ratios and compare them to 1.
Comment for this answer: I've added a practical example of how things work with t test, paired t test and ratio t test. Hope it helps a bit more! :-)
Comment for this answer: Can we make a vector of `1` with the same length as each of the row to compare the results using paired tests ?
Comment for this answer: I explained my experiment under this link: http://stats.stackexchange.com/questions/258295/ratio-between-control-and-treatment-siginificantly-different-than-1/258955#258955 . BTW. how to attach links in a nicer way ?
Comment for this answer: Just the last question if you do not mind. I will read attached documents. Can I use paired t-test before calculating ratio if I have let's say a pair of genes which first of all are done in four replicates and in general I would like to know how the specific group of genes change under a treatment.
Comment for this answer: I used group of people as an example. Clearly not a good one. I would refer cell cultures which were divided into two groups and one was used as a control a second was used for treatment. We can say that both groups represents the same "person". In that case I think paired test is the one which should be used.
Comment for this answer: Thanks, I really appreciate your help!
Comment for this answer: how do i include rowname such as each observation in my case the gene name if i have three comparison then what is the calculated p value between those comparison ? is there way to report it
|
Title: How to persist auto-generated OWL rules or at least not hold them all in memory at once?
Tags: sparql;jena;graph-databases;fuseki;reasoner
Question: I have a data set with about 9 million triples in it and the owl reasoner enabled.
When the first sparql query is sent I get a seemingly endless stream of lines in the log file that look similar this:
```Adding rule [ (<http://example.org/cat3> ?P ?V) ->(<http://example.org/cat2> ?P ?V) ]
```
These lines keep appearing until my JVM runs out of memory and the fuseki server stops functioning.
Working with a smaller data set, I can see that the rules are only generated once. Subsequent queries do not re-log the creation of these rules, unless I bounce the server process.
Is there a way to generate these rules only once and have them persisted in the database? Or some other way to avoid loading them all into memory at once?
I very much appreciate any help I can get.
Comment: the phrase "generate rules" is a bit misleading. What do you mean by this? The idea should be to materialize the triples inferred by a reasoner. Your whole setup would be interesting to know. Which reasoner? Which Fuseki version. And then you could think about whether you need the reasoning profile that you"re using
Comment: The `OWLMicroFBRuleReasoner` reasoner just supports RDFS plus the various property axioms, `intersectionOf`, `unionOf` (partial) and `hasValue`. It omits the cardinality restrictions (`owl:minCardinality, owl:maxCardinality, owl:cardinality`) and equality axioms (e.g. `owl:sameAs, owl:differentFrom, owl:distinctMembers`) as well as property restrictions `owl:someValuesFrom, owl:allValuesFrom`, which enables it to achieve much higher performance.
Comment: And yes, you have to write the materialized triples once to the triple store. That would allow to disable the reasoner for later querying and you can directly execute queries on the inferred RDF graph.
Comment: Thanks. I switched the reasoner from OWLFBRuleReasoner to OWLMicroFBRuleReasoner and this seems to have fixed the issue. I don't understand the limitations of the "micro" reasoner, so I don't know if it will suffice for our needs or not. All I meant by generating rules was that I see log lines like the above appear. My assumption was it's figuring out the things it needs to do reasoning. I see none of those "adding rule" log lines if the reasoner is disabled. It maybe it's materializing triples but it's not storing them - it re-materializes them when fuseki is restarted. Fuseki version 3.10
Comment: How do you write them to the triple store?
|
Title: Objective C: UIScrollView inside a UIScrollView
Tags: objective-c;ios;uiscrollview
Question: Is it possible to put another scrollview inside a scrollview??
because in one page of my scrollview i need to put scrollable images.
I already tried it but it's not scrolling.
Can it be done? or is there another way??
Here is the accepted answer: Yes, sure.
I suggest you to see PhotoScroller sample in Apple doc.
Hope it helps.
Edit
If you provide some code, maybe it is possible to help you.
Here is another answer: You can add a scrollView on a scrollView, it doesn't matter.
the scrollView is not scrolling, did you call setContentSize?
Here is another answer: You can add a scroll view inside another scroll view. But image scrolling is possible with a single scroll view itself. You must have missed to set the delegate or set contentSize. Please check.
|
Title: PHP object is null after initialization
Tags: php;class;object
Question: I have the class file:
```class Settings
{
public $siteName;
public $siteAddr;
public $dbUrl;
public $dbName;
public $dbPass;
public function __construct()
{
$siteName = 'Welcome';
$siteAddr = 'http://site.com';
$dbUrl = 'test';
$dbName = 'base';
$dbPass = '123';
}
}
```
Trying to use it in other file:
```require_once('settings.php');
$cfg = new Settings();
var_dump($cfg); // <--- everywhere is null...
```
Why does it contain only nulls?
Here is the accepted answer: Instead of
```$siteName = 'Welcome';
```
you need
```$this->siteName = 'Welcome';
```
otherwise you just created variables in scope of your constructor, not initialized object members.
Here is another answer: The variables you're using in your constructor are local scope variables. To refer to class fields use ```$this->fieldname```.
|
Title: Defining functions with GUI buttons (Python\Tkinter) _beginner level_ (issue: "function; not definded)
Tags: python;tkinter;notepad
Question: Currently studying Python for class, I am creating a number guessing game.
objectives of code:
a user rolls a dice, that determines how many attempts they get to guess a number between 1 to 100
results are saved in a notepad.
I am able to get the guessing game working in shell. However, i am trying to convert game to GUI.
CURRENT ISSUE
I have assigned a tk.Button to run function when pressed. However, I am receiving an error.
Code below;
```import random
import tkinter as tk
import time
import sys
window = tk.Tk()
window.title("Shanes Number Guessing Game")
window.geometry("900x500")
diceResult = random.randrange(1,6)
print (diceResult)
tries= 0
correct = 0
logo = tk.PhotoImage(file="C:\Python-Tkinter pics\\numberguess.png")
photo1 = tk.Label(image=logo)
photo1.image = logo
photo1.pack()
#gui buttons and lables
enterGuessLabel = tk.Label(window, text="enter guess below")
enterGuess = tk.Entry(window)
diceButton = tk.Button(window, text="roll dice", command=throwDice)
diceResultLabel = tk.Label(window, text="you rolled a: ")
#Number guess code
def throwDice():
count = diceResult
while not count == 0:
input1 = int(input("guess a number 1,10 "))
randNum1 = random.randrange(1,10)
if (input1 == randNum1):
print("correct")
correct += 1
else:
print ("incorrect")
tries += 1
print (randNum1)
print (count -1)
count -= 1
print ("computer", (tries) ,(userName),(correct))
#GUI pack
enterGuessLabel.pack()
enterGuess.pack()
diceButton.pack()
diceResultLabel.pack()
window.mainpack()
```
Here is the output
``` 5
name 'throwDice' is not defined
Stack trace:
> File "C:\Users\shane\source\repos\ICT30118 CertIII Assessment\ICT30118 CertIII Assessment\ICT30118_CertIII_Assessment.py", line 31, in <module>
> diceButton = tk.Button(window, text="roll dice", command=throwDice)
Loaded '__main__'
Loaded 'runpy'
```
I have assigned a "tk.Button" to run the command "throw dice" when pressed.
I have assigned a "def function" as "throwDice():"
When I run the program, I receive an error that "throwDice" is not defined
Any help will be appreciated.
Comment: I am unsure of how to define a function with the same name, i have attempted to use the global function. will post results in main post.
Comment: It worked, I will edit post, thanks.
Comment: You need to define your function before you use it as a command. Usually you define your global function right after you imported your stuff. Keep in mind that your interpreter reads your code left to right and up to down.
Comment: Also take a look at this https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions
Comment: I see I had confused you. What I mean by a global function is that your function is in the global namespace. You dont need to define that function twice, you need to place it at the right spot. Again your Intepreter reads your code up to down. Your function is on the very bottom of your code and your button is in the middle. How should your Interpreter know your funtion at this point? Link for global namespace https://[email protected]/understanding-python-namespaces-through-recursion-c921cbd4e522
Comment: Congratulations! :)
Here is the accepted answer: Define the throwDice() function before defining the button
Because the python interpreter reads from the top
Here is another answer: As per the advise of Stack Overflow user "Atlas435" I have simply moved the tk.Button line of code under the "def function" code. The interpreter reads code from top to bottom, so for the tk.Button(command=xyz) to work the interpreter first needs to read the function.
Code below:
```def throwDice():
count = diceResult
while not count == 0:
input1 = int(input("guess a number 1,10 "))
randNum1 = random.randrange(1,10)
if (input1 == randNum1):
print("correct")
correct += 1
else:
print ("incorrect")
tries += 1
print (randNum1)
print (count -1)
count -= 1
print ("computer", (tries) ,(userName),(correct))
diceButton = tk.Button(window, text="roll dice", command=throwDice)
#GUI
enterGuessLabel = tk.Label(window, text="enter guess below")
enterGuess = tk.Entry(window)
diceResultLabel = tk.Label(window, text="you rolled a: ")
enterGuessLabel.pack()
enterGuess.pack()
diceButton.pack()
diceResultLabel.pack()
```
|
Title: Reference request: Oldest books on analytic geometry with unsolved exercises?
Tags: ag.algebraic-geometry;reference-request;algebraic-curves;textbook-recommendation;analytic-geometry
Question: Per the title, what are some of the oldest books on analytic geometry out there with unsolved exercises? Maybe there are some hidden gems from before the 20th century out there.
Comment: You ask the same question repeatedly but just change the subject area. Please consider posting a big-list question "Oldest books in different areas of math with unsolved exercises". And these don't seem like research-level questions. Consider posting on math.stackexchange
Comment: Have you tried [this](//mathoverflow.net/questions/337524/reference-request-oldest-books-on-algebraic-curves-with-unsolved-exercises#comment845862_338204)?
Comment: (Also, one “[out there](//doi.org/10.1017/S026607840100205X)” might suffice.)
Here is the accepted answer: As requested, here are some late 19th century and early 20th century textbooks on analytic geometry that contain unsolved exercises (an example page is shown for each entry). The list is not exhaustive, you can find more by querying Archive.org .)
An elementary treatise on solid geometry, by W. Steadman Aldis (1880)
Elements of analytic geometry, by Simon Newcomb (1884)
Elements of analytic geometry, George A. Wentworth (1886)
New Analytic Geometry, by Percey F. Smith (1912)
Analytic Geometry, by Maria M. Roberts and Julia T. Colpitts (1918)
|
Title: Redmine search results shortens the subject of an issue (...)
Tags: redmine
Question: I would like to change the layout of the search results for issues. If the subject of an issue is long, it gets shortend with ...
How and where can I change the behaviour? I would like to have always the full title of an issue.
Thank you for your help!
|
Title: Using jupyter R kernel with visual studio code
Tags: r;visual-studio-code;jupyter
Question: For python jupyter notebooks I am currently using VSCode python extension. However I cannot find any way to use alternative kernels. I am interested in jupyter R kernel in particular.
Is there any way to work with jupyter notebooks using R kernel in VSCode?
Comment: Folks at Microsoft are on it. https://github.com/Microsoft/vscode-python/issues/5078#issuecomment-608175269
Comment: Is there any update to this?
Here is another answer: Agreed with @essicolo, if you are 100% stuck on using vscode this is a no-go.
```
[About kernels] Sorry, but as of right now this feature is only supported with Python. We are looking at supporting other languages in the future.
Yeah, that's the case for now, even if you start an external server. I hate having to say that, as we really want to support more of the various language kernels. But we started out with a Python focus and we still are pretty locked into that for the near future. Polyglot support is coming, but it won't be right away
```
per Microsoft Employee IanMatthewHuff
https://github.com/microsoft/vscode-python/issues/5109#issuecomment-480097310
preface - based on the phrasing of your question, I am making the assumption that you are trying to perform ```IRkernel``` in-line execution from your text ide without having to use a jupyter notebook / jupyterlab.
That said, if you're willing to go to the dark side, there might be some alternatives:
nteract's Hydrogen kernel for Atom IDE - the only text ide that I'm aware of that still supports execution against ```IRkernel```. I know, I know - it's not ```vscode``` but it's as close as you'll probably get for now.
TwoSigma's Beaker notebook - it's been a lonngggg time for me but this a branch of jupyter that used to support polyglot editing, I'm not sure if that's still supported and it seems like you aren't that interested in notebooks anyway.
Here is another answer: Yes, it is possible. It just requires an additional configuration to connect with the R kernel in VSCode.
It's worth noting that, if you prefer, you can use the notebook in VSCode Insiders where there is native support for notebooks in many languages, including R.
If you're using Jupyter in VSCode, firstly install IRkernel (R kernel).
According to the docs, run both lines to perform the installation:
```install.packages('IRkernel')
IRkernel181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16installspec() # to register the kernel in the current R installation
```
Now, you should:
Reload Window Ctrl + R
Type Ctrl + Shift + P to search for "Jupyter: Create New Blank Notebook"
Click on the button right below ellipsis in upper right corner to choose kernel
Switch to the desired kernel, in this case, R's
That's it!
Comment for this answer: could you provide some info or link why is buggy about vs code and the integration with R kernel ? Maybe just not the case anymore ? Looks to me it works pretty well
Comment for this answer: Just in case that someone has the same trouble as me following the instructions without getting it to work: it might be necessary to call `IRkernel181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16installspec(user = FALSE)` , for me it did not show up in the list of kernels before.
Comment for this answer: Does this still work?
Comment for this answer: The integration had some bugs by the time I wrote (I couldn't even plot a table correctly). Nevertheless, nowadays they seem to have **fixed** most [issues](https://github.com/microsoft/vscode-jupyter/issues?q=is%3Aissue+is%3Aopen+R+label%3Alanguage-R).
Here is another answer: @testing_22 it works with me too
just add some note from my experience
It will failed If you run ```IRkernel181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16installspec()``` from RStudio or from Jupyter Conda environment failed way
Please run this syntax with VSCode terminal
```install.packages('IRkernel')
IRkernel181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16installspec()
```
The rest is same, please restart VSCode and select "R" kernel from VSCode
|
Title: Status bar icon indicators disappear when waking from suspend
Tags: unity;suspend;icons;16.10
Question: So, when I wake up from suspend, this happens:
The missing icons are Skype and Mega. When I close one of those programs, the other icon appear, like this:
How can I fix this or make a script that refreshes the status bar?
Here is the accepted answer: As a temporary solutions until the bug is fixed, you can create a file f.e. icons.sh (dont't forget to give it execution rights with chmod +x) at any location:
```#!/bin/bash
dbus-monitor --session "type=signal,interface=com.canonical.Unity.Session,member=Unlocked" |
while read MSG; do
LOCK_STAT=`echo $MSG | awk '{print $NF}'`
if [[ "$LOCK_STAT" == "member=Unlocked" ]]; then
killall unity-panel-service
/usr/lib/x86_64-linux-gnu/unity/unity-panel-service&
fi
done
```
After saving the script, open Ubuntu Startup Applications from Apps menu and configure this script to run after you login:
Every time you unlock the screen, unity panel service will be automatically killed and started, keeping your icons in place.
Comment for this answer: @SergeiMorozov It took some searching, but it appears that this is being tracked as https://bugs.launchpad.net/ubuntu/+source/unity/+bug/1628383
Comment for this answer: If this is fixed, it isn't in yakkety stable (or whatever it should be called) yet. I'm on 16.10/yakkety with latest updates, and I still have the problem.
Comment for this answer: Works for me as well, thank you. Is this bug filed anywhere so that one could track its progress?
Comment for this answer: @joelittlejohn, thanks. From here https://bugs.launchpad.net/ubuntu/+source/unity/+bug/1635625, it looks the issue has just been fixed in yakkety.
Comment for this answer: *Excellent* answer! +10 now and tomorrow +50!!!
|
Title: Application has iAd Configuration error
Tags: ios;iphone;objective-c;ios5;iad
Question: I am developing a simple application in that one i implemented iAd Banner View. and I have no errors in my code if i run that code i got error
"The Operation Could n't be Completed.Application has iAd Network Configuration error" i want to know what is reason behind the error. and i'm using XCode 4.2 and iOS 5 Simulator.
This is the Code What i wrote.
```-(void)moveBannerViewOffScreen
{
CGRect originalTableViewFrame = self.tableView.frame;
CGFloat newTableHeight = self.view.frame.size.height;
CGRect newTableFrame = originalTableViewFrame;
newTableFrame.size.height = newTableHeight;
CGRect newBannerFrame = self.bannerView.frame;
newBannerFrame.origin.y = newTableHeight;
self.tableView.frame = newTableFrame;
self.bannerView.frame = newBannerFrame;
}
-(void)moveBannerViewOnScreen
{
CGRect newBannerFrame = self.bannerView.frame;
newBannerFrame.origin.y = self.view.frame.size.height - newBannerFrame.size.height;
CGRect originalTableFrame = self.tableView.frame;
CGFloat newTableHeight = self.view.frame.size.height - newBannerFrame.size.height;
CGRect newTableFrame = originalTableFrame;
newTableFrame.size.height = newTableHeight;
[UIView beginAnimations:@"BannerViewIntro" context:NULL];
self.tableView.frame = newTableFrame;
self.bannerView.frame = newBannerFrame;
[UIView commitAnimations];
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
[self moveBannerViewOffScreen];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner
{
[self moveBannerViewOnScreen];
NSLog(@"Success");
}
```
Comment: @Suresh I think App / iAd are having issues. You should still be seeing a test ad regardless of if your contract is completed. I've been having the same issue.
Comment: @ahmedalkaff No What are the Agreements Can u please explain?
Comment: I Developed this Application By watching WWDC iAD integration Video Tutorial.
Comment: is it necessary to join in iAd Network for showing a small demo.?
Comment: Did you complete the agreements required for iAd in itunes?
Comment: Look at the get started steps and follow themL: https://developer.apple.com/iad/resources/
Comment: "To Use iAd In Your Application, You Must Join the iAd Network" This is from: https://developer.apple.com/library/ios/documentation/userexperience/Conceptual/iAd_Guide/Introduction/Introduction.html
|
Title: Why does this init method when loading a nib return an object out of scope?
Tags: iphone;ios;uiview;bundle;nib
Question: Why does this init method return an object out of scope?
Using XCode 4.2, base SDK of 4.3, and ARC, I'm trying to load an UIView from a nib (not a UIViewController). I need to not use a UIViewController at all in the process.
After reading this answer to an S.O. question here, it looks like it can be done:
How to load a UIView using a nib file created with Interface Builder
(The answer by user "MusiGenesis" describes the process)
I created a sub-class of UIView with a single label:
```@interface MyView : UIView
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *textLabel;
@end
```
In the implementation I override initWithFrame:
```- (id)initWithFrame:(CGRect)frame
{
//self = [super initWithFrame:frame];
self = [JVUIKitUtils initWithNibName:@"MyView" withOwner:self];
if( self )
{
NSLog(@"Created");
}
return self;
}
```
In I.B. I created a file named "MyView.xib" with a single view. It has a label as a sub-view, and I created the label property by dragging it to the h file.
And in another file, I created this re-usable static method:
```+ (id)initWithNibName:(NSString*)nibName withOwner:(id)uiView
{
id object = nil;
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName owner:uiView options:nil]; // 1 object, out of scope
for( id tempObject in bundle)
{
if( [tempObject isKindOfClass:[uiView class]] ) object = tempObject;
break;
}
return object;
}
```
As you can see in the following screen shot, the bundle has one object reference, but it's out of scope.
And debugging:
This is my code for instantiation:
```subView = [[MyView alloc] initWithFrame:CGRectZero]; // ok
NSAssert(subView != nil, @"MyView was nil"); // fail
```
Any ideas on why the other S.O. poster was able to get it to work but this does not?
Comment: I have no idea what you're trying to do with `self = [JVUIKitUtils initWithNibName:@"MyView" withOwner:self]` but that is absolutely *WRONG*.
Comment: There's a difference between base SDK and deployment target. ARC works with a deployment target of iOS 4, but does it work with a base SDK of iOS 4? You shouldn't be using a base SDK of iOS 4 in any case.
Comment: Also, you can't use ARC with a base SDK of 4.3.
Comment: I'm trying to load the nib from a static class. Why is this wrong?
Comment: @hwaxxer ARC works with any SDK down to iOS 4.
Comment: My mistake, base sdk is 5, but deployment target is 4.3.
Here is the accepted answer: The use of the owner seems a bit confusing in the way that you are loading a nib. It appears that you are trying to use the view as both the owner of the nib and the first object in it.
Are you trying to load MyView from your nib (i.e. is the class of the view inside your nib files defined as MyView) or are you trying to load a subview of MyView from the nib?
If the view inside your nib is a MyView, here's how to load it. Create this static method as a category on UIView:
```@implementation UIView (NibLoading)
+ (id)viewWithNibName:(NSString*)nibName
{
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
if ([bundle count])
{
UIView *view = [bundle objectAtIndex:0];
if ([view isKindOfClass:self])
{
return view;
}
NSLog(@"The object in the nib %@ is a %@, not a %@", nibName, [view class], self);
}
return nil;
}
@end
```
That will let you load any kind of view from a nib file (the view needs to be the first item defined in the nib). You would create your view like this:
```MyView *view = [MyView viewWithNibName:@"MyView"];
```
If the view inside the nib is not a MyView, but you want to load it as a subview of MyView, with MyView defined as the file's owner in the nib file, do it like this:
```@implementation UIView (NibLoading)
- (void)loadContentsFromNibName:(NSString*)nibName
{
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
if ([bundle count])
{
UIView *view = [bundle objectAtIndex:0];
if ([view isKindOfClass:[UIView class]])
{
//resize view to fit
view.frame = self.bounds;
//add as subview
[self addSubview:view];
}
NSLog(@"The object in the nib %@ is a %@, not a UIView", nibName, [view class]);
}
}
@end
```
Using that approach, just create your view as normal using initWithFrame, then call loadContentsFromNibName to loa the contents from a nib. You would load your view like this:
```MyView *view = [[MyView alloc] initWithFrame:CGRect(0,0,100,100)];
[view loadContentsFromNibName:@"MyView"];
```
Comment for this answer: You don't need to combine them. They are both slightly different variations of the same approach. Either should work (although mine is less code to implement ;-))
Comment for this answer: Because when you load the view from the nib, it's not the same as the view that you create with initWithFrame. Nib files actually contain their own copies of objects, which are loaded into the file's owner. When you initialise a view controller with a nib, you are actually loading the view controller's view object from within the nib, but when you initialise a view from a nib, you either have to get the whole object from the nib and return it (as in my first example) or you have to load a subview from the nib and then add that subview to the view you've created (as in my second example).
Comment for this answer: Don't use the file's owner for the first solution. In your nib file, you must set the view in your nib to be of class MyView, and then bind all the outlets from the sub-controls to your view itself, not to the file's owner. This is what I was trying to explain. The file's owner is the class that loads the view, which in the second case is MyView, but in the first case in *nothing* because you are loading and returning the entire view directly from the nib - you aren't loading it *in to* anything.
Comment for this answer: Yeah, it took me a while to get my head around it.
Comment for this answer: Will try this in a moment by combining it with clairware's answer.
Comment for this answer: The second implementation is what I'm after, will respond in a moment.
Comment for this answer: I tried out the second method, and the nib loads (thank you VERY much). I'm able to print out the text I assign to the label. I'm curious though, why do you use the line [self addSubview:view]; ? It seems like it's adding another subview to the already created uiview.
Comment for this answer: I've converted my code to use the first (static) method you proposed, as I don't want the subview effect. But for some reason the bundle loading throws an NSUnknownKey exception (this class is not key value-coding compliant for the key textLabel). However, I created the view with a drag from the label to the file's owner and I can clearly see the connection in the connections inspector.
Comment for this answer: Sweeeeet, thank you so much. I'm surprised after all my searching there isn't and easy-to-find tutorial to load a UIView from a nib without a UIViewController.
Here is another answer: Your ```[JVUIKitUtils initWithNibName:@"MyView" withOwner:self]``` approach is all wrong. When an init method is called, the object is already allocated by the call to ```[MyView alloc]```. The reason why you chain the calls to the super init method is so that this will daisy chain all the way down to the NSObject init method, which simply returns the instance it is.
By setting "self" to the (autoreleased) instance value returned by your ```JVUIKitUtils```, you are effectively setting it to a memory address other than what was allocated by the call to ```[MyView alloc]```, which generates the out of scope error.
Instead, don't create the init method your are trying to create. You already have the method to create and initialize your nib-based view in your state method. I would change the name and do something like:
```+ (UIView)newViewWithNibName:(NSString*)nibName withClassType:(Class)uiView
{
id object = nil;
// you need some object to assign nib file owner to. use an NSObject.
NSObject* owner = [[NSObject alloc] init];
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil]; // 1 object, out of scope
for( id tempObject in bundle)
{
if( [tempObject isKindOfClass:] ) object = [tempObject retain];
break;
}
[owner release];
return object;
}
```
and then call it like:
```MyView* subView = [JVUIKitUtils viewWithNibName:@"MyView" withClassType:[MyView class]];
```
I haven't tested this code. Your milage might vary.
|
Title: DS-2019 and J1 visa different 212(e) status
Tags: chinese-citizens;j1-visas;canadian-residents
Question: I am a University Student in Canada working in the US next term, as I was preparing my documents for departure. I noticed that my DS-2019 said my country of permanent residence is China, though I am a Chinese citizen, I also have Canadian PR, does that matter?
I also noticed that the DS-2019 form said I am subject to 212(e) the two year residency requirement, but on my J1 visa it said that I am not subject to it. I'm not planning on working in the US after this internship but I was just wondering if this will cause me trouble at the border this time.
Does any of this matter or at the border they just check if your Visa is fake and if you have criminal intentions? I have never been to the US on a J1 before so I am really nervous. Thank you!
Comment: This probably fits better on [Expatriates.SE], but if I were you I would ask the school to give you a corrected DS-2019.
|
Title: String searching algorithm for Chinese characters
Tags: python;unicode;cjk;string-search
Question: There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese characters? I am referring to this:
http://en.literateprograms.org/Boyer-Moore_string_search_algorithm_(Python)#References
Here is another answer: As long as all your text is in unicodes it should work just fine. The algorithm looks sequence-independent, provided each "element" is one sequence-unit in length.
|
Title: Anthology of stories beginning with the protagonist checking into the suicide clinic
Tags: story-identification;anthology-book
Question: I'm trying to remember the title of an anthology of SF stories that all started with the same premise: a few paragraphs in which the male protagonist checks into the suicide clinic, has a brief discussion with the harried technician, then settles in to wait for the end.
All the stories proceed to tell what happens from there. The initial chunk is extremely simple and feels like John Campbell-era writing. I scanned a list of Groff Conklin anthologies, as that would have been my first guess, but didn't see anything promising. And I tried to find it on my disorganized shelves with no luck; it's not clear to me if I ever owned it.
Of course none of the stories end with "and then there was nothing" or "you're in the waiting room for heaven/hell". In every case, if there is death, there's interesting life beyond it.
I probably read this in the late 1970s or early 1980s, but I feel like it wasn't new then, perhaps a paperback picked up at The Paperback Exchange.
I don't recall if the writers were well-known, entirely unknown, or a mix. It feels like an Ursula Le Guin writing workshop kind of book, but it doesn't feel like her sort of opening, and I think the stories were probably too long for that. But no authors' names stand out.
I have vague senses of three of the stories:
In one, in one the hero's consciousness ends up in the body of some avian race, possibly in a gladiatorial contest.
In another, while the protagonist does die, this is just a regular occurrence for this two-part being that reunites after each death (perhaps sampling various sentient species?)
In a third, the super-competent hero somehow ends up in some urban noir landscape, enters an exclusive gaming club, wins some complex strategy game in a single move, all steps in trying to uncover the person at the center of some plot.
That's about all I remember. I don't know the editor, publisher, or any of the stories' authors. I don't know how many stories there were; although I'd guess it was something between six and ten. I can't even picture the cover. I'm sure the clinic had some innocuous "Eternal Rest" sort of name, but I don't know what it was. Almost certainly there was some explanatory text about seeing how differently authors will treat the same prompt, but I recall none of it.
Is this familiar?
Comment: Hi, welcome to SF&F. When did you read this?
Comment: Thanks, @DavidW: edited to mention likely first read in the late 1970s. That is a guess, though, and probably doesn't reflect publication date.
Here is the accepted answer: Five Fates.
This was published in 1970 so it fits with your memory of the date you read it. The book is a collection of five novellas, each of which explores what happens when William Bailey checks into a euthanasia clinic. The introduction is:
```
In Poul Anderson’s THE FATAL FULFILLMENT Bailey is discovered practicing the secret device of painting, is committed to Hospital to be saved and made sane . . . but that is only the beginning.
Frank Herbert’s foray into Euthanasia in MURDER WILL IN gives Bailey the realization of the Tagas/Bacit occupying his body and the tremendous battle they must face for survival.
MAVERICK by Gordon R. Dickson is a beautiful story of a parallel world where men have wings and will die for their guilds. Bailey slips through a portal of time and in a battle for life discovers a profitable black market operation.
Utilizing some remarkable storytelling devices Harlan Ellison’s THE REGION BETWEEN stuns and dazzles as Bailey’s soul is stolen by an enigmatic, omnipotent Succubus—sending it on a series of extra-galactic journeys that culminates finally in a memorable nightmare.
Keith Laumer’s OF DEATH WHAT DREAMS is a particularly powerful story of the ultimate in gambling—Booking the Vistat Run, a game based on the nightly fluctuations of life and death among the countless millions of poor and wretched in the world.
```
The avian race story is Maverick, the two part being reunited is Murder Will In and the strategy game story is Death What Dreams.
Comment for this answer: Ah, perfect. Thank you. That cover is not even slightly familiar, but that is so clearly it. I think my mind somewhat combined the Herbert and Ellison stories. Don't remember the Anderson [email protected]. And I'm sure I must have picked it up when I was 14 or 15 and after reading *Dune*, went to find all the Herbert I could. Kudos! And again, thank you!
|
Title: Validate Yii2 Activeform on simple button click
Tags: php;yii2;yii2-basic-app;yii2-validation
Question: I want to validate my Yii2 activeform on simple button click which is not submitButton. I tried ```$('#formId').yiiActiveForm("validate")``` but it is not working.
I also tried - ```$('#formId').yiiActiveForm('submitForm')``` it validates form but it also submit it if everything is ok. I don't want to submit that form. I just want to validate it on button click and if everything is ok than i want to open a modal popup.
What are possible ways to validate this activeform on button click
Here is the accepted answer: To validate your form perform ajax validation only inside your action as follows. This will only validate your form
```public function actionValidateForm() {
$model = new Form();
if (Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16$app->request->isAjax && $model->load(Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16$app->request->post())) {
Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16$app->response->format = Respons181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16FORMAT_JSON;
return ActiveForm181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16validate($model);
Yii181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16$app->end();
}
}
```
Comment for this answer: Thanks Nitin. Almost done can u suggest one more thing. It is not removing error class from field. even after entring correct data. Validation is working fine just error message is not getting removed
Comment for this answer: I tried validateOnChange and validateOnBlur but error message is still displaying.
Comment for this answer: it is set to value true
Comment for this answer: you need to set form properties like
`enableAjaxValidation,enableClientValidation,validateOnChange,validateOnSubmit` to `true`
Comment for this answer: what about `enableAjaxValidation` ? is it set to true
Here is another answer: You have to set ```enableClientValidation = false,``` in you'r form's options .
|
Title: How to change material UI select border and label
Tags: reactjs;material-ui
Question: I am trying to change the border of a ```select``` component from Material-UI.
So far I've tried:
```const styles = theme => ({
root: {
display: "flex",
flexWrap: "wrap",
backgroundColor: "lightgrey"
},
formControl: {
margin: theme.spacing.unit,
minWidth: 120
},
selectEmpty: {
marginTop: theme.spacing.unit * 2
},
cssLabel: {
color: "pink",
"&$cssFocused": {
color: "pink"
}
},
cssFocused: {
color: "pink"
},
underline: {
"&:after": {
borderBottom: "1px solid pink",
borderTop: "1px solid pink"
}
}
});
```
I can customise ```TextField``` etc., but after many many hours, I still can not customise the Select. I tried to pass also an ```Input```, but then you have to customise the ```Input```, which is even worse.
Could someone help me with this sandbox?
https://codesandbox.io/s/material-demo-ecj1k
I would really appreciate it.
Here is the accepted answer: Below is an example of overriding the colors of the border (```MuiOutlinedInput-notchedOutline```), label (```MuiInputLabel-root```), and selected item text (```MuiOutlinedInput-input```) for default, hover, and focused states.
```import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import MenuItem from "@material-ui/core/MenuItem";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles({
root: {
width: 200,
"& .MuiOutlinedInput-input": {
color: "green"
},
"& .MuiInputLabel-root": {
color: "green"
},
"& .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
borderColor: "green"
},
"&:hover .MuiOutlinedInput-input": {
color: "red"
},
"&:hover .MuiInputLabel-root": {
color: "red"
},
"&:hover .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
borderColor: "red"
},
"& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-input": {
color: "purple"
},
"& .MuiInputLabel-root.Mui-focused": {
color: "purple"
},
"& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: "purple"
}
}
});
function App() {
const [age, setAge] = React.useState("");
const classes = useStyles();
return (
<div className="App">
<TextField
className={classes.root}
value={age}
onChange={e => setAge(e.target.value)}
variant="outlined"
label="My Label"
select
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</TextField>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```
Related answers:
Change border color on Material-UI TextField
Is there a way to style the border color and text color of <TextField/> in Material-UI without using makeStyles
Global outlined override
Comment for this answer: beautiful answer. How did you decide to not use the Select component and yes the TextField componenet with the select prop? Because it's easier to style? thanks for your help
Comment for this answer: `TextField` is just easier to use in general since it takes care of ensuring the correct structure of `FormControl`, `InputLabel`, `Select`, and some of the accessibility ties between them. Unless you need to customize that structure, I [recommend using TextField](https://stackoverflow.com/questions/56122219/in-material-ui-when-do-we-use-input-vs-textfield-for-building-a-form/56135272#56135272).
Comment for this answer: The styling approach will work exactly the same when using the lower-level pieces. You would then apply this class to the `FormControl` (which is the [root component](https://github.com/mui-org/material-ui/blob/v4.9.5/packages/material-ui/src/TextField/TextField.js#L157) rendered by TextField).
Comment for this answer: @iphonic See my answer here: https://stackoverflow.com/questions/54789989/global-outlined-override/54794340#54794340.
Comment for this answer: How do you setup the above styles in global theme? Any pointer? Thanks.
Comment for this answer: I have to use select since mine is multiple select I want to give border to the pop over menu I tried "& .MuiMenu-paper" and other classes for that matter did not work any idea on how to give border/styling to that ?
Here is another answer: Okay in my style overrides for the theme I put this in...
```MuiOutlinedInput: {
root: {
'&$focused $notchedOutline': {
borderColor: 'inherit !important'
}
}
}
```
It seemed to the trick. It didn't address the Label... but it did address the border. I've spent WAY too many hours on this. So it will do for now.
Here is another answer: I also spent too long with this problem. In the end I just used a TextField and give it select prop. Then you can style it as the regular textfield.
Comment for this answer: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Here is another answer: You can override styling of child element classes e.g.
```selectBorder: {
'& .MuiOutlinedInput-notchedOutline': {
borderColor: 'red'
}
}
```
If you apply ```className={classes.selectBorder}``` to your ```Select``` component, it will change the border color to red.
Comment for this answer: actually what i want is not the border, but when I click the the dropdown, the focused border. Where I can get the name of the class that I have to point?
|
Title: How to add a white surface with the shape of my original image in pygame?
Tags: python;image;pygame;transparent
Question: I am making a game in python using pygame. I have an image, and I used ```set_colorkey()``` for the color ```(0,0,0)```. I did not add alpha channel. It works fine.
I want to add a white transparent surface on it when it is selected. I used the following code, but it makes the corners of the image white, too. How can I add a white surface which has the shape of the main image?
```window.blit(obj.get_image(),obj.get_pos())
if obj.selected:
white_surface = pygame.Surface(obj.size,pygame.SRCALPHA)
white_surface.fill((255,255,255))
white_surface.set_alpha(128)
window.blit(white_surface,obj.get_pos())
```
From my game:
What I want:
Comment: write out what the shape is? (in your program)
Here is the accepted answer: Create a ```pygame.Mask``` form the surface and convert the mask to a white shape. A mask can be created with ```pygame.mask.from_surface```. The ```pygame.Mask``` can be converted to a black and white ```pygame.Surface``` with the ```to_surface``` method:
```def create_white_surf(surf, alpha):
mask = pygame.mask.from_surface(surf)
white_surface = mask.to_surface()
white_surface.set_colorkey((0, 0, 0))
white_surface.set_alpha(alpha)
return white_surface
```
See also Selection and highlighting
Minimal example:
repl.it/@Rabbid76/PyGame-PyGame-HighlightObject
```import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
class TestObject:
def __init__(self, x, y):
self.image = pygame.Surface((64, 64), pygame.SRCALPHA)
pygame.draw.circle(self.image, (0, 0, 0), (32, 32), 32)
pygame.draw.rect(self.image, (0, 0, 0), (0, 0, 32, 64))
pygame.draw.circle(self.image, (0, 128, 0), (32, 32), 30)
pygame.draw.rect(self.image, (0, 128, 0), (2, 2, 30, 60))
self.rect = self.image.get_rect(center = (x, y))
self.size = self.rect.size
self.selected = False
def get_image(self):
return self.image
def get_pos(self):
return self.rect.topleft
def create_white_surf(surf, alpha):
mask = pygame.mask.from_surface(surf)
white_surface = mask.to_surface()
white_surface.set_colorkey((0, 0, 0))
white_surface.set_alpha(alpha)
return white_surface
obj_list = [TestObject(100, 150), TestObject(200, 150)]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for obj in obj_list:
obj.selected = obj.rect.collidepoint(pygame.mouse.get_pos())
window.fill((127, 127, 128))
for obj in obj_list:
window.blit(obj.get_image(), obj.get_pos())
if obj.selected:
white_surf = create_white_surf(obj.get_image(), 128)
window.blit(white_surf, obj.get_pos())
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
```
|
Title: short links with htaccess - two arguments
Tags: regex;apache;.htaccess;mod-rewrite
Question: I've got little problem that I am not sure how to fix. I am using htaccess file to rewrite my url to shorter links. For example I am using this rule:
```RewriteEngine On
RewriteRule ^client/(.*)/?$ pages/client.php?action=$1 [L,QSA]
```
but I wanted to also pass second argument to that URL so I made this:
```RewriteRule ^client/(.*)/(.*)/?$ pages/client.php?action=$1&view=$2 [L,QSA]
```
so I could access URL like:
```/client/action_1/view_2
```
without any problems but when I skipped second argument and only accessed:
```/client/action_1/
```
then it was impossilbe and resulted in 404.
How to make a change to that RewriteRule so I can access both:
```/client/action_1/view_2
/client/action_1/
```
and it would rewrite to:
```pages/client.php?action=$1&view=$2
```
Here is the accepted answer: You can have 2 separate rules to handle 2 clean URLs:
```RewriteEngine On
RewriteRule ^client/([^/]+)/?$ pages/client.php?action=$1 [L,QSA,NC]
RewriteRule ^client/([^/]+)/([^/]+)/?$ pages/client.php?action=$1&view=$2 [L,QSA,NC]
```
Comment for this answer: Thank you @anubhava - that is what I needed!
Comment for this answer: I gave you plus 1 for the answer but someone downgraded before your reply so now it's [0]. I am sorry for that but it was not me. Anyway, thank you again!
Comment for this answer: There was a typo, it is fixed now. Please test again.
Comment for this answer: Yes I know it wasn't you. It was from someone who didn't understand the solution. I am seeing many downvotes on my answers without any explanation actually. btw I upvoted your question too.
|
Title: Appcelerator / Titanium - Is this way of saving models from a JSON response too memory intensive?
Tags: javascript;backbone.js;underscore.js;appcelerator;titanium-alloy
Question: In my app I'm pulling in a JSON structure using ```Ti.Network.createHTTPClient``` and then looping through the objects and saving each one as a new model. Is this an inefficient way of doing it? I'm new Titanium and Alloy so I'm not sure of best practices. Is there a better way of achieving this?
```var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
Ti.API.debug(this.responseText);
var repsonseJSON = JSON.parse(this.responseText); // parse response as JSON object
// loop through the data and create/save a model for each one
_.each(repsonseJSON.brands, function (i) {
var brand = Alloy.createModel('brands', i);
theBrands.add(brand);
brand.save();
});
_.each(repsonseJSON.videos, function (i) {
var video = Alloy.createModel('videos', i);
theVideos.add(video);
video.save();
});
if (callback) callback(); // callback used to open app in init function
},
onerror: function(e) {
Ti.API.debug(e.error);
console.log('Error while loading data', e.error);
},
timeout: 5000
});
xhr.open("GET", this.data_url); // open the request
xhr.send(); // request is actually sent with this statement
```
Comment: this is more of a backbone specific question than a titanium question, however without writing or modifying your sync adapter this is the best solution
|
Title: Using converter in JavaServer Faces
Tags: jsf;converter;label
Question: I have that converter:
```public class PollConverter implements Converter {
private static PollanswersDao pollsDao = new PollanswersDao();
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return pollsDao.read(Long.parseLong(value));
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
return String.valueOf(((PollanswersEntity)value).getId());
}
}
```
In faces-config.xml:
```<converter>
<converter-id>PollsConverter</converter-id>
<converter-class>org.test.majas.converters.PollConverter</converter-class>
</converter>
```
So, I can unique identify poll only by ID. Ok I use this converter:
```<h:form>
<h:selectOneRadio layout="pageDirection" value="#{votesBean.answer}">
<f:converter converterId="PollsConverter"/>
<f:selectItems value="#{pollsBean.selectItems}" var="item" itemLabel="#{item.value.title}" />
</h:selectOneRadio>
<h:messages/>
<h:commandButton value="#{msgs.vote}" action="#{votesBean.addVote}"/>
</h:form>
```
But this itemLabel="#{item.value.title}" not working. My selectItems itemlabels are ID values... How can I show itemLabels as objects "title" fields.
PollsBean:
```@Named
@SessionScoped
public class PollsBean implements Serializable {
...
private List<SelectItem> selectItems;
...
public List<SelectItem> getSelectItems() {
return selectItems;
}
public void setSelectItems(List<SelectItem> selectItems) {
this.selectItems = selectItems;
}
...
}
```
Thanks.
Comment: Not working - displayed items ID, without this attribute items ID are displayed too. I have added PollsBean structure to question.
Comment: Select item is javax.faces.model.SelectItem :)
Comment: Yes value is object of a class with title field.
Comment: Showed item ID (from converter getAsString)
Comment: _"Not working"_ means nothing is displayed or a thrown exception ?
And how does `PollsBean`'s structure look like ?
Comment: What's the purpose of using this predefined class as an ordinary class, as object in the code ? Does it contain `Value` composite class which has `title` as a field ?
Comment: What's showed instead of what is desired to be ?
|
Title: How to reuse AEM SPA components from one project in another?
Tags: reactjs;single-page-application;aem
Question: How do I reuse one AEM SPA project's components in another SPA project? Assuming both projects in this example use the AEM Maven Archetype 25 with React:
Project A has a header component in ui.front-end that has the proper mapping to the AEM component under its ui.apps.
How would I reuse this header component in Project B? It seems like the header component needs to also exist in Project B and be imported into the imported-components.js file to work. If I wanted to instead turn project A into an AEM SPA component library and use those components in Project B. How could I make this work?
Here is the accepted answer: ```
If I wanted to instead turn project A into an AEM SPA component library and use those components in Project B.
```
You can do this - just create ```project-a``` as a regular React App and export your components from it, then use it as a dependency in ```project-b``` (the ```ui.frontend``` part of your AEM project) and map those React components to their AEM counterparts.
Here's an example component from :
```const Header = (props) => {
return <h1>{props.title}</h1>
}
export default Header
```
Then in your project-b you'd do something like:
```import {Header} from 'project-a'
import {MapTo} from '@adobe/aem-react-editable-components'
...
MapTo('my-aem-app/components/header')(Header)
```
|
Title: Converting ú to u in javascript
Tags: javascript;unicode;character-encoding
Question: How would I convert ú into u in javascript. I might possibly need it for other non-english characters too.
Here is another answer: MovableType has a function called dirify that does that. Here's a PHP version. These are essentially big lookup tables, so it should be pretty easy to move them across to JavaScript.
In theory you could parse the Unicode tables and follow character references until you hit ASCII, but that might not be practical for you.
Here is another answer: A similar question has been asked (but in a .NET context): How do I remove diacritics (accents) from a string in .NET?
I think the simplest solution would be to make a mapping table and just do a lookup for each character. You can build a table of characters with their diacritics to their corresponding "base" character, wrap the lookup into a function and you're good to go.
Here is another answer: check this Englishizer
```function Englishizer(var strIn)
{
var strOut
var strMid
var n
For int (n = 1; n<strIn.Length;n++)
{
strMid = substring(strIn, n, 1)
Select Case strMid.charCodeAt(0)
Case 192 To 197:
strMid = "A"
Case 198:
strMid = "AE"
Case 199:
strMid = "C"
Case 200 To 203:
strMid = "E"
Case 204 To 207:
strMid = "I"
Case 208:
strMid = "D"
Case 209:
strMid = "N"
Case 210 To 214, 216:
strMid = "O"
Case 215:
strMid = "x"
Case 217 To 220:
strMid = "U"
Case 221:
strMid = "Y"
Case 222, 254:
strMid = "p"
Case 223:
strMid = "B"
Case 224 To 229:
strMid = "a"
Case 230:
strMid = "ae"
Case 231:
strMid = "c"
Case 232 To 235:
strMid = "e"
Case 236 To 239:
strMid = "i"
Case 240, 242 To 246, 248:
strMid = "o"
Case 241:
strMid = "n"
Case 249 To 252:
strMid = "u"
Case 253, 255:
strMid = "y"
Englishizer = Englishizer + strMid;
}
}
```
Here is another answer: Here's one version of a function that does that in Ruby, that I did. Should be pretty straightforward to convert javascript.
http://snippets.dzone.com/posts/show/2384
|
Title: Stored Procedure with less parameters than associated object
Tags: c#;entity-framework;stored-procedures;entity-framework-6
Question: I have a stored procedure (```sp_create_user```) in my database that creates a user in my ```Users``` table. This is my stored procedure definition:
```ALTER PROCEDURE sp_create_user
@Username nvarchar(50),
@Password nvarchar(50),
AS
BEGIN
-- SQL STATMENTS
END
```
My ```User``` object in c# is this:
```public partial class User
{
public User()
{
}
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
```
And this is my EF mapping the User entity insert to that stored procedure:
```modelBuilder.Entity<User>().MapToStoredProcedures(
s =>
s.Insert(i => i.HasName("sp_create_user"))
);
```
When I try to execute a new creation of user I get an exception that the number of parameters sent to the stored procedure is too big. After tracing the query, I see that it sends to the stored procedure all the fields that the ```User``` class has.
How can I tell EF to send only the relevant fields for the stored procedure?
Comment: That's what I ended up doing :(
Comment: Side note if this is for **SQL Server**: you should **not** use the `sp_` prefix for your stored procedures. Microsoft has [reserved that prefix for its own use (see *Naming Stored Procedures*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx), and you do run the risk of a name clash sometime in the future. [It's also bad for your stored procedure performance](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix). It's best to just simply avoid `sp_` and use something else as a prefix - or no prefix at all!
Comment: Can't you just add the parameters to the SP? :)
Here is another answer: ```...
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string FirstName { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public string LastName { get; set; }
...
```
You can also try the following if you don't want to modify the class:
```modelBuilder.Entity<User>().Ignore(u => u.UserId);
```
Comment for this answer: is there a way to define it in the mapping without interfering with the entity class?
Comment for this answer: What will "Ignore" do? will it have effects later on on regular EF update? because on update I would like to send some of the fields I don't send on SP insert
|
Title: generate Class diagram for iphone app
Tags: iphone;xcode;class;uml;class-diagram
Question: i know how to generate class diagram in Xcode for iPhone app.
but i am searching for alternate way to represent it, because my app is very much big and it will difficult to put diagram and explanation in my thesis report.
any idea how to represent all classes or app in short manner so i can put into my thesis report.
thank you very much
Comment: like if u right click in .net and select View Class diagram its so simple to see and read and easily understandable but this is not in the case with Xcode....it create so huge class diagram which is not possible to documentation
Comment: not really tool or software i just need advice how other people do if they want to document their apps in class diagram representation
Comment: i am also thing to create it manually..thanks for advice
Comment: "Short manner" can be very subjective. Also are you looking for a free tool/software?
Comment: It all depends on the tool and medium you want to display the information. On the web I can generate a very large paper size. But for psychical pager you have to break it down to concrete area. For example one page would just deal with storing user settings. And for your thesis, you will have to manually generate them yourself.
Here is another answer: Select the "FirstDemo.xcdatamodeld".Goto the "File" select the "print" option save as pdf formate in "ERD diagram".
Any screen issue faced goto the "File" select the "Page Setup"manage the custom sizes.
Here is another answer: OmniGraffle only works with projects that have an Objective-C hierarchy! Do not waste time trying this for Swift!
Edit: I ended up using LucidChart instead. Their trial version was good enough for writing my class diagram
https://www.lucidchart.com/pages/
Comment for this answer: This is already mentioned in the comments to the highest-voted answer. However, if you are able to add additional details, this answer could meaningfully stand on its own.
Here is another answer: Just download OmniGraffle and then go to ```File->Open->Select your XcodeProject file``` and that's it you'll have a class diagram.
Comment for this answer: Will not work for swift, me too looking for alternative solution., if any one find please let us all know. Thanks
Comment for this answer: Yes, It won't work for Swift, I am also searching for similar tool, will inform if found some reliable tool.
Comment for this answer: It crashed for me as well if I opened the XCode project directly from OmniGraffle. My project is quite big, so I guess that is the problem. But if I used https://github.com/nst/objc_dep to generate the .dot file and then open it with OmniGraffle it worked, but not for CircleGraph type.
Comment for this answer: This link is invalid but I searched OmniGraffle 7 in mac's app store and I got that.
Comment for this answer: Seems to be unable to handle larger projects. "Not Responding" every time.
Here is another answer: A Ruby script created by 'yoshimkd' that scans all swift code from the specified folders and files and automatically generates an entity diagram (similar to a class diagram) which can be viewed in a browser.
Usage:
https://martinmitrevski.com/2016/10/12/swift-class-diagrams-and-more/
Comment for this answer: A link to a potential solution is always welcome, but please [add context around the link](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259) so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. Take into account that being barely more than a link to an external site is a possible reason as to [Why and how are some answers deleted?](http://stackoverflow.com/help/deleted-answers).
Here is another answer: You can use Omnigraffle to generate UML diagrams directly from Xcode.
Have a look at this SO answer.
|
Title: count() returning 1 when thousands of records
Tags: php;count;directory
Question: this count is onyl returning 1, when there are thousands of records in this folder.
```// TV Shows
$dir = 'G:/TV';
if ($handle = opendir($dir)) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
$check = mysql_query("SELECT * FROM tv_shows WHERE title = '$file'");
$checkcount = mysql_num_rows($check);
if ($checkcount == 0) {
mysql_query("INSERT INTO tv_shows (id, title) VALUES ('', '$file')");
}
}
echo count($dir)." Records Traversed!<br/>";
closedir($handle);
}
```
Table Structure: id, title
Folder Structure: Sub folders in the main one
``` G:\TV
G:\TV\24
G:\TV\Family Guy
```
Comment: ofcourse because $dir="G:/TV" and its one
Comment: So there are thousands of records in the folder, and you're looping through each one of them and running 1 or possibly 2 queries for each file? That's going to absolutely wreck your database.
Comment: Hm, I think we need some more information to help you. Can you show us your folder structure and your database table layout please?
Comment: The value of $dir is string which is "G/TV";so it will return 1
Here is the accepted answer: You can't use ```count()``` on a folder. Try this one instead
```// TV Shows
$dir = 'G:/TV';
$count = 0;
if ($handle = opendir($dir)) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
$count++;
$check = mysql_query("SELECT * FROM tv_shows WHERE title = '$file'");
$checkcount = mysql_num_rows($check);
if ($checkcount == 0) {
mysql_query("INSERT INTO tv_shows (id, title) VALUES ('', '$file')");
}
}
echo $count." Records Traversed!<br/>";
closedir($handle);
}
```
```
how about returning the number of new records inserted?
```
Check this out, just moved ```$count++```
```// TV Shows
$dir = 'G:/TV';
$count = 0;
if ($handle = opendir($dir)) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
$check = mysql_query("SELECT * FROM tv_shows WHERE title = '$file'");
$checkcount = mysql_num_rows($check);
if ($checkcount == 0) {
$count++;
mysql_query("INSERT INTO tv_shows (id, title) VALUES ('', '$file')");
}
}
echo $count." Records Traversed!<br/>";
closedir($handle);
}
```
Comment for this answer: how about returning the number of new records inserted?
Comment for this answer: hmm i tried that before i asked and it didnt seem to work... il ltry again... it always returns 34 this way.
Here is another answer: You are calling ```count()``` on a string, not an array.
CodePad.
Here is another answer: Also a good alternative to this is using the php glob function.
```$dir_path = "/full/directory/path/";```
```$count = count(glob($dir_path . "*"));```
This will also optimize your code !!
|
Title: Power BI - Slow DAX in Event Hub
Tags: azure;powerbi;dax;azure-eventhub
Question: I apologize for the for the vague question. I'm working with a data engineer on a project and I'm coming at this with limited knowledge of the backend.
We are using Azure Event Hub to stream data in Power BI. The data roughly follows this path, Azure Event Hub > Streaming dataflow > Dataset > Power BI. The problem is that any DAX query run in Power BI (or directly in the model) has very bad performance.
It doesn't seem to be a problem with the DAX itself. The same DAX code run with an Azure Analysis Services connection on a similar number of rows runs fine. But when it's run with an Event Hub connection, the performance drops considerably (~3 sec vs >1 min). Visuals loaded without DAX involved have pretty good performance actually, which makes me think that this issue has to do with the DAX interaction rather than the connection as a whole.
Has anyone experienced anything similar with an Event Hub connection in Power BI? Is there a way to address the DAX performance issue with this connection?
Here is another answer: Write optimized DAX expressions and design reports using below suggestions:
DAX Measures
DAX with Variables
SELECTEDVALUE () vs HASONEVALUE ()
A common scenario is to use HASONEVALUE() to check if there is only one value present in a column after applying slicers and filters, and then use the VALUES(column name) DAX function to get the single value.
SELECTEDVALUE () performs both the above steps internally and gets the value if there is only one distinct value present in that column, or returns blank in case there are multiple values available.
DISTINCT () vs VALUES ()
Power BI adds a blank value to the column in case it finds a referential integrity violation. For direct queries, Power BI by default adds a blank value to the columns as it does not have a way to check for violations.
DISTINCT (): does not return blank when encountering an integrity violation. It returns blank only if it is in part of the original data.
VALUES (): includes blank, as it’s added by Power BI due to referential integrity violations.
The usage of either of the functions should be the same throughout the whole report. Use VALUES () in the whole report if possible so that blank values are not an issue.
Ratio Calculation efficiently
Use (a-b)/b with variables instead of (a/b)-1. The performance is the same in both cases usually, but under edge cases when both a and b are blank values, the former will return blanks and filter out the date whereas the latter will return -1 and increase the query space.
Avoid IFERROR () and ISERROR ()
IFERROR () and ISERROR () are sometimes used in measure. These functions force the engine to perform a step by step execution of the row to check for errors. So wherever possible, replace with the in-built function for error checking.
Example: DIVIDE () and SELECTEDVALUE () perform an error check internally and return expected results.
For more, you can refer Power BI Performance Tuning Workflow.
|
Title: perl regex for {8} character string with decimal digits AND letters and nothing else
Tags: regex;string;perl
Question: I'm trying to build a Perl regex that matches an 8 character string that requires a length of exactly 8 consisting of at least one letter A-F (uppercase) AND *at least one decimal digit (0-9)*
I'd like the regex to catch:
A13B4D90
13CF928B
A2F1C3D5
But not:
1392857
2962219
3945580
ASFLEAN
-MLQORNA
Right now I have
[\dA-F]{8}
and it's allowing all of the above. I don't want fields that are all digits or all letters- only want it to match ones with digits AND letters.
Thank you!
Comment: Well, can you write regexes for the other conditions as well? After that, we can join them into a single regex.
Here is the accepted answer: You can make use of lookaheads:
```^(?=.*\d)(?=.*[A-F])[\dA-F]{8}$
```
```(?= ... )``` makes sure there's a match ahead before continuing the match of the rest of the pattern,
```(?=.*\d)``` basically makes sure there's a digit matching any number of characters from where the lookahead is, in this case from the start of the pattern.
```(=.*[A-F])``` acts the same way, thus it acts as a check to make sure there's a letter between A and F somewhere ahead after any number of characters.
Comment for this answer: PERFECT. I'll have to do some research on look aheads.
Comment for this answer: Note that `$` (as opposed to `\z`) allows for a trailing newline.
Comment for this answer: @user1694958 Could you please mark my answer as accepted? :) Also, I added a few more detail about the lookaheads.
Comment for this answer: @n0741337 You have put a white space after `13CF928B` which naturally makes the string invalid :)
Comment for this answer: @n0741337, looks like fiddle.re's implementation of Perl-compatible regular expressions, is not in fact Perl-compatible. Jerry's regexp works fine in Perl.
Comment for this answer: @Jerry Your regex doesn't appear to work for `13CF928B` according to regexplanet's [Perl beta](http://fiddle.re/tkyyn) ( or its [Java tester](http://fiddle.re/0keyn) ). I'm trying to learn from your answer and I'm trying to interpret the results from regexplanet.
Comment for this answer: @Jerry - Thanks for looking! Now I've learned to pay more attention to the subtle boxes from rexplanet's output as well as my copy/pasting :)
Comment for this answer: Depending on the circumstances, `\d` should be `[0-9]` instead.
|
Title: Why am I seeing the 'title' in Web-page's body (Not only in Title Bar)?
Tags: html;hyperlink;stylesheet;title
Question: ```<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
</body>
</html>
```
When I run this code, I see 'My Page' in my Browser's Title Bar and in Body too!
Why am I getting this?
Comment: I have cleared everything from main.css - No Problem!
But, when I add `* { display: block; }` I get that. @lc.
Comment: Well [clearly](https://jsfiddle.net/ecr1hbcb/) your main.css looks like: `body:after { content: 'My Page' }`.
Here is another answer: Because ```<head>``` and ```<title>``` are just tags, like anything else. And the ```*``` selector picks them up too.
For kicks, take a look at this fiddle, which clearly demonstrates when you give ```head``` and ```title``` a ```display:block``` style, they indeed show up as text on the page:
HTML
```<body>
<p>hi</p>
</body>
```
CSS
```head, title {display:block}
```
Output
```
- jsFiddle demo
hi
```
For a bit more fun, we can color things too. And we even learn something about the inner workings of JSFiddle in the process. It looks like they inline your style in a ```<style>``` tag inside the ```<head>```. Ha!
Comment for this answer: Are meta tags (meta title) also affected the same way? I've never had a meta title show on the page, only in the title bar. Just out of curiosity and for future reference. Thanks.
Comment for this answer: Oh you beat me to it! Cheers
Comment for this answer: reset css is a much better option than `*`.
Comment for this answer: yeah, thats true! What if we add `*{color: blue;}` ?
Does that apply to title, head,... tags too ?
Comment for this answer: That's going crazy ! @lc.
Comment for this answer: @SathyamoorthyR It's funny you should mention that. Take a look at my last link (https://jsfiddle.net/ecr1hbcb/3/)
|
Title: Not sure how to use System.nanoTime() for my program
Tags: java;fibonacci
Question: I need to measure the time in nanoseconds for my project but I'm not sure how to properly implement it into my program. I know I need to use something like:
```long startTime = System.nanoTime();
...
long endTime = System.nanoTime();
long timeElapsed = endTime - startTime;
```
but I'm not sure where I have to implement it so my program works properly. Here is my code:
```import java.util.*;
public class fiboSeriesRec
{
public static void main(String[] args)
{
//Scanner allows input from user, int in this case
Scanner sc = new Scanner(System.in);
long n; //declare n as a long since numbers get too large for int
System.out.println("How many numbers 'n' do you wish to see?"); //Prompts the user to input a number
n = sc.nextInt();
System.out.println("The first " + n + " Fibonacci numbers are:");
for (long i=0; i < n; i++) //Adds each 'n' to a list as the output
{
System.out.println(fibonacci(i)); //Prints out the list
}
}
//Recursive function for fibonacci sequence
public static long fibonacci(long num) {
if (num == 0) {
return 0;
}
else if(num == 1)
{
return 1;
}
return fibonacci(num-1) + fibonacci(num-2);
}
```
}
Comment: You would wrap the code you want to time with the lines you have indicated. Probably this would be either `main` as a whole or each iteration of the loop that calls `fibonacci`.
Here is another answer: I assume you are profiling how long your code takes?
If so, you start the timer before everything you want to measure, then you record after you want to measure, and then you find the difference. Just pretend you are using a stopwatch to time someone... same thing here.
This means you can do:
```import java.util.*;
public class fiboSeriesRec {
public static void main(String[] args) {
//Scanner allows input from user, int in this case
Scanner sc = new Scanner(System.in);
long n; //declare n as a long since numbers get too large for int
System.out.println("How many numbers 'n' do you wish to see?"); //Prompts the user to input a number
n = sc.nextInt();
System.out.println("The first " + n + " Fibonacci numbers are:");
long startTime = System.nanoTime();
for (long i=0; i < n; i++) { //Adds each 'n' to a list as the output
System.out.println(fibonacci(i)); //Prints out the list
}
long endTime = System.nanoTime();
System.out.println("It took " + n + " iterations: " + (endTime - startTime) + " nanoseconds");
}
//Recursive function for fibonacci sequence
public static long fibonacci(long num) {
if (num == 0) {
return 0;
}
else if(num == 1)
{
return 1;
}
return fibonacci(num-1) + fibonacci(num-2);
}
}
```
Note however that this code is timing the printing, which is probably a pretty slow operation and not a good measurement of how long the function is taking. If you want to time it, you should only time the function, and then add the difference to a sum, and then report the sum at the end.
In pseudocode, this means:
```long sum = 0;
for (int i = 0 ...) {
long start = recordTime();
Object result = doCalculation();
sum += recordTime() - start;
// Do something with result here, like print it so you don't time printing
}
// `sum` now contains your time without interference of the loop or printing
```
|
Title: Removing the extra space from Top of BottomSheet
Tags: android;android-layout
Question: I added bottomsheet in my application.ii work good but only problem is extra space it cover and I just want to remove those extra spaces on the top of Bottomsheet layout.
I want to remove the highlighted part:
How I can remove those extra spaces?
Here is my XML
```<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
android:id="@+id/coordinatorLayout"
tools:context=".MainActivity">
<include layout="@layout/content_main" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:orientation="horizontal"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
android:id="@+id/bottom_sheet"
android:background="@android:color/white"
app:layout_behavior="@string/bottom_sheet_behavior">
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_photo_camera"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_image_gallery"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_video_camera"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_video"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
```
Here is my Java code
```public class MainActivity extends AppCompatActivity {
BottomSheetBehavior behavior;
View bottomSheet;
CoordinatorLayout coordinatorLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
bottomSheet = findViewById(R.id.bottom_sheet);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
// React to state change
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
// React to dragging events
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
}
// Snackbar.make(coordinatorLayout,item + " is selected", Snackbar.LENGTH_LONG).setAction("Action", null).show();
// behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (behavior.getState()==BottomSheetBehavior.STATE_EXPANDED) {
Rect outRect = new Rect();
bottomSheet.getGlobalVisibleRect(outRect);
if(!outRect.contains((int)ev.getRawX(), (int)ev.getRawY()))
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
return super.dispatchTouchEvent(ev);
}
}
```
Comment: Remove the top margin/padding from your BottomSheet or give it a negative value.
Here is another answer: I think I have got the answer. Just need to remove the ```android:fitsSystemWindows="true"``` from bottom_sheet i.e the LinearLayout.
Just in case I am putting the xml code below.
```<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
android:id="@+id/coordinatorLayout"
tools:context=".MainActivity">
<include layout="@layout/content_main" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
android:id="@+id/bottom_sheet"
android:background="@android:color/holo_orange_light"
app:layout_behavior="@string/bottom_sheet_behavior"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_photo_camera"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_image_gallery"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_video_camera"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
<ImageView
android:layout_weight="1"
android:layout_margin="@dimen/five"
android:padding="@dimen/ten"
android:src="@drawable/ic_video_camera"
android:layout_width="@dimen/fifty"
android:layout_height="@dimen/fifty" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
```
Just for my use, I have used different drawable you need to change it back to the original one.
Hope it helps!
Here is another answer: ``` android:fitsSystemWindows="false"
```
Will work!
Here is another answer: I had the same problem. What worked for me was moving ```android:layout-behaviour``` from the ```LinearLayout``` to the ```coordinatorLayout```. Or just removing it all together.
|
Title: What are the reasons why volume control wouldn't work for Chromecast?
Tags: android;google-cast
Question: I'm using the MediaRouter library to change the volume of a Chromecast Device. After some time the volume commands don't work anymore.
```mRoute.requestSetVolume(volume);
```
There is a selected route.
Tracing the code I found that it does send the volume change packet.
It also doesn't work from the System UI. Changing from the volume buttons will move the Seek pointer of the volume dialog, but after 3 or 4 seconds it reverts to it's previous position.
It only does seem to work from the Google Cast app.
Does the Google Cast app use a different protocol or api to change the volume of the Chromecast?
This was tested with Chromecast Audio and Chromecast v2.
Comment: Google Cast App uses Cast SDK to manage that.
|
Title: HaxeFlixel how to fire touch event to fire when touching sprite
Tags: haxe;haxeflixel
Question: I have a sprite on the screen that I want to fire a event when touched. I managed it with the mouse event but can't get it work with touch input.
```//This works for mouse. eg.
import flixel.input.mouse.FlxMouseEventManager;
...
add(sprite);
FlxMouseEventManager.add(sprite, onMouseDown, onMouseUp, onMouseOver, onMouseOut);
// Need to work out how to fire event for touch.
I would like the touch equivalent for a sprite.
FlxTouch???? (needs to be fixed)
```
Comment: Hey Lee, I think the haxeflixel community is not that active in StackOverflow to get an answer in just one day. Btw you might get better response posting in their forum http://forum.haxeflixel.com/
Comment: Woow, I am surprised that no one seem to know the anwer to this seemingly simple question, but I think I know why now. I think I have the answer I was looking for.
Comment: ANSWER: The onMouseOver works on the mobile devices. I have tested this on Android & IOS and it Works!! I hope this helps someone else out there with the same problem. Happy coding Lee
Comment: If there is a better way of doing this then please let me know. thanks
|
Title: Retrieving value from HTML5 local storage
Tags: javascript;html;jquery-mobile;local-storage
Question: I have multiple JQM pages and in need to retrieve the active page ID i already stored and add it as a link to a button on the first page.
I am trying to achieve a "continue" function that allows you to not lose your progress.
In the example below I managed to store the active page ID and whenever the page is refreshed you will get an alert with the last page ID stored (first time it will alert #null cause no id is stored at the time).
It's basically ok but i can't seem to make that ID as the button link even though I tried ```$("#resume").attr("href", resume);```
I am storing the ID with this button :
```<a href="#" data-role="button" onclick='storageValue();'>Store</a>
```
And this is the function I have so far:
``` function storageValue() {
var stored = $.mobile.pageContainer.pagecontainer("getActivePage").attr('id');
alert("Your stored id is: " + stored);
localStorage.setItem('stored', stored);
checkLocalStorage();
}
var test = localStorage.getItem('stored');
var resume = "#" + test;
alert("Your stored id is: " + resume);
checkLocalStorage();
```
Optional: It would have been ideal if I didn't need to click a button to store the page. The page should be stored automatically when becoming active.
Here is a JSFIDDLE that will allow you to test/debug faster.
PS: I don't think it's of any relevance to this but I am going to turn this into an android app using XDK.
Comment: @fuzzybabybunny well, thanks for the opinion but I see no use in using a plugin for something this simple..
Comment: @fuzzybabybunny well, yes but I am building this into an android app. Therefore I won't use it on a mobile orientated website :)
Comment: I would look into using Amplify.store for your LocalStorage needs: http://amplifyjs.com/api/store/
Comment: Different browsers use different apis for their local storage. It's nice to use one code base that takes care of all the differences for you, otherwise you could be typing lots of different versions of the same code for different browsers.
Here is the accepted answer: It's more practical to use pagecontainer events to store data. In your case, use ```pagecontainerhide``` to store ID of page you're navigating to ```toPage```. And then, use ```pagecontainershow``` to update button's ```href```.
In case stored ID is equal to first page's ID, the button will be hidden.
```$(document).on("pagecontainerhide", function (e, data) {
var stored = data.toPage.attr('id');
localStorage.setItem('stored', stored);
}).on("pagecontainershow", function (e, data) {
if (data.toPage[0].id == "firstpage") {
var test = localStorage.getItem('stored');
var resume = "#" + test;
$("#resume").attr("href", resume);
if (test == "firstpage") {
$("#resume").fadeOut();
} else {
$("#resume").fadeIn();
}
}
});
```
```
Demo
```
If you want to navigate directly to last visited page, listen to ```pagecontainerbeforechange``` and alter ```toPage``` object.
```$(document).on("pagecontainerbeforechange", function (e, data) {
if (typeof data.toPage == "object" && typeof data.prevPage == "undefined" && typeof localStorage.getItem('stored') != "undefined") {
data.toPage = "#" + localStorage.getItem('stored');
}
});
```
```
Demo
```
|
Title: Text Shadows on counter or bullet in list
Tags: css;html-lists;shadow
Question: I want to know how to add text-shadow to an ordered list ```</ol>```.
I've tried, the following example but it doesn't work.
```body {
text-shadow: black 0.1em 0.1em 0.2em;
color: gray;
background: white;
}
ol {
text-shadow: black 0.1em 0.1em 0.2em;
}```
```Ordered Lists
<ol>
<li>content</li>
<li>content</li>
<li>content</li>
</ol>```
My issue it tahe the list counter doesn't have the text shadow. I need to add text shadow to the number in the ordered list, like the 1. , or 2. , etc.
By the way, I want it to still retain like a list style where the content is indented before the number.
Comment: [Fiddle for the OP stuff](http://jsfiddle.net/cE4cc/)
Here is the accepted answer: If you also want to set the text-shadow on the counter/bullet, you need to put the counter/bullet in the ```:before``` pseudo element so that the counter/bullet can have a text-shadow like the rest of the text.
To keep the position of the counter you can set ```position:absolute;``` to the pseudo element and position it outside the ```li``` on the left with ```right:100%;```.
```body {
text-shadow: .1em 0.1em 0.2em;
}
ol {
counter-reset: li;
list-style-type: none;
}
ol li{
position:relative;
}
ol li:before{
content: counter(li)'.';
counter-increment: li;
position:absolute;
right:100%;
margin-right:0.5em;
}```
```Ordered Lists
<ol>
<li>content</li>
<li>content</li>
<li>content</li>
</ol>```
Comment for this answer: @vaibhav oh sorry, I though you wanted the shadow only on the counter, here you are : http://jsfiddle.net/webtiki/Gn8dd/
Comment for this answer: @edwardtorvalds browser support is very wide : https://caniuse.com/#feat=css-counters
Comment for this answer: To start with a custom value for an ordered list when you use this, for example you want to start with 2. you should do this: content
Comment for this answer: but content shadow is now gone.
Here is another answer: For custom styles on the list decoration themselves you probably need to either fake them or use custom images (or both).
This looks semi-helpful but doesn't have different values per item.
Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image
If you know how many items you are going to have as a maximum you could create a custom rule for each n-th child of the ul.
|
Title: Smartcard authentication for .NET
Tags: .net;authentication;smartcard
Question: I have a smartcard reader and a smartcard. I have installed drivers and it works as expected. I can use this card as windows logon or for remote desktop logon.
I'm building my app which should work only when the card is inserted and I need to call web services from my app which requires a certificate from the card.
Any suggestions on how do I do that? The web is full of examples for ASP.NET and I'm building Windows forms.
As a further note: Everything must work the same even if user logs on windows without the card. The card must me present for the app to work.
Thanks.
Comment: Have a splash screen, do your attempt at authentication during the time, if the authentication fails close the application. You should be able to easily use the examples you found and apply them to your application.
Here is the accepted answer: If the Smartcard driver supports the standard Windows CryptoAPI, it will export the certificates from the card into the personal store of the user. You can access those certificates using the X509Store class. When you access the certificate, the user will be prompted to insert the card and enter his PIN.
Note: Some smartcard drivers do not automatically export the certificates. Instead, they have a tool which the user can use to do this.
Comment for this answer: I already did that, thanks. Since I have several cards for testing, all of them are in the X509Store(StoreName.My). I'm not sure what is happening when the user inserts the card. I should somehow find out which certificate is 'activated'?
Comment for this answer: I don't know which certificate I want. I want to identify the user using his smartcard.
Comment for this answer: User identification should be automatic if the smartcard is inserted. If there is no smartcard application has to display a message to insert the card into a reader. This is my task and required behaviour closely resembles Windows log on using smartcards.
Comment for this answer: I will trust all certificates. Once I have the certificate in my system I can extract required information to see if any of my users own this certificate. Then, I'll use the certificate so that user can log on with his PIN. I just don't know how to get the certificate from the smartcard.
Comment for this answer: @HenningKrause: are you trying to filter the certificates like this: http://stackoverflow.com/questions/7555281/smartcard-authentication-for-net ?
Comment for this answer: Well, since you want to authenticate the user, you should know in advance which certificate you want. When you access a certificate from a smartcard which is not attached to the computer, the user is prompted to insert the card. (Unless you specify the Silent flag in some of the crypto operations - in this case you simply get an error.)
Comment for this answer: But in the end, the user could present any certificate. You'll need to have some indication wether the certificate presented is valid or not. The usual step would be to present the user a list of certificates (using http://msdn.microsoft.com/de-de/library/system.security.cryptography.x509certificates.x509certificate2ui.aspx fore example). Then the user selects his certificates and you validate it according to your rules.
Comment for this answer: Yeah.. but the certificate used by WIndows for smartcard logon has special information in it. The user principal name, for example. And it has to be trusted by your organization. So, Windows can deduct from the certificate alone who you are. You have to establish something similar. Either by trusting all certificates form a specific CA or by some sort of sign-up procedure.
|
Title: Spring Boot and Spring Security, can't send error with custom message in AuthenticationEntryPoint
Tags: java;spring;spring-boot
Question: I'm working on a restful api using spring boot, and going to use a custom authenticationEntryPoint. Here is the code
```@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}
```
And the related part in Security configuration.
```@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/users/checkUsernameAvailability", "/api/users/checkEmailAvailability").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
...
}
```
The problem is, when I log in with a wrong credential, the error message is empty.
```{
"timestamp": "2020-09-03T17:16:28.082+00:00",
"status": 401,
"error": "Unauthorized",
"message": "",
"path": "/api/auth/signin"
}
```
However, the logger prints correct message
```c.m.p.s.JwtAuthenticationEntryPoint : Responding with unauthorized error. Message - Bad credentials
```
What may go wrong here? Thank you in advance.
Here is the accepted answer: Default value for ```server.error.include-message``` is ```"never"```.
Therefore, you just need to configure your ```application.yaml``` (or properties) like this
```server:
error:
include-message: always
include-binding-errors: always
```
Comment for this answer: A follow up question, I see other spring projects don't call this out but the error message goes along. How come they are able to send error message without configuring?
Comment for this answer: @MillerDong It depends which version of spring boot is used in project. Since Spring Boot 2.3 they changed default value of `server.error.include-message` to `never`
|
Title: Passing parameters to an anoynmous function in AJAX call
Tags: javascript;jquery;ajax;anonymous-function
Question: I'd like to load items from an XML file and display them on a webpage via AJAX and limit the output via a date range. However I am struggling to pass the parameters to the anonymous function. All tries to hand over the parameter 'displayDateLimit' have ended in syntax errors. Any idea how to do this?
In addition to that: If do not pass the the parameter I get an incremented counter for inpTest instead. Why does this happen?
```// loads XML to Div-Element.
function loadItemsToBox(id)
{
var boxElement = document.getElementById('someid');
if (!boxElement){ return;}
xmlUrl = 'someurl'];
displayDateLimit = new Date().getTime();
displayDateLimit -= 3600*1000;
$.ajax({
type: "GET",
url: xmlUrl,
dataType: "xml",
success: function (xml) {
var content = "";
$(xml).find("item").each(function (inpTest) { // or "item" or whatever suits your feed
var el = $(this);
content += "<p>";
content += el.find("title").text() + "<br>";
content += "<br>DateLimit: " + inpTest;
content += "</p>";
})(displayDateLimit);
boxElement.innerHTML = content;
},
error : function(xhr, textStatus, errorThrown )
{
// some errorhandling
}
});
}
```
Comment: You can define `displayDateLimit` outside the function, as an external var, and leave the function without parameters.
Comment: Please refer to `.each` documentation: http://api.jquery.com/each/. You don't need to invoke the function you are supplying. The documentation also answers why `inpTest` results in a counter.
|
Title: No Module named qgis
Tags: qgis;pyqgis;python-2.7;osgeo4w
Question: I installed QGIS through OSGeo4W, and I am trying to write a standalone PyQGIS script, however, I am unable to import the qgis, qgis.core, processing ect… modules, as shown in the picture, I get the ‘Import Error: No Module named qgis...
I sought help from the many examples that exist that require you to change your command line path to your python libraries, change your python path to your c:\OSGeo4W\apps\qgis\python ect…
Here is a list of the answers I tried, but, it seems myself and many others are still unable to fix this issue, as I could not get it to acknowledge the existence of those libraries:
Problem with import qgis.core when writing a stand-alone PyQGIS script:
Cannot run standalone QGIS script
Running Custom Applications:
Here is the accepted answer: I am running a batch file first.
```call "C:\OSGeo4W64\bin\o4w_env.bat"
set PATH=%PATH%;C:\OSGeo4W64\apps\qgis\bin
```
Comment for this answer: Fantastic you found your own solution, am sure this will help others
Comment for this answer: I tried to use this method as it is much easier than mine, but, I still get Import error: No Module named QGIS @okorkut
Comment for this answer: Have you verified the path of the "o4w_env.bat" in your computer. I set this according to my path. I assumed that since you installed through QSGeo4W file paths should be similar. May be your file installed in a different directory.
Here is another answer: Here is probably the best solution I have found, it has made very easy thanks to http://www.qgistutorials.com/en/docs/running_qgis_jobs.html.
First thing you need to do is create a batch file, call it "launch", and enter the following
Then you create your GIS Standalone Python script, hopefully, this is more complex than mine, but this is just to show you that the modules import correctly.
Then all you need to do is trigger the launch batch file( I just double clicked mine) and it will import the modules without issue!
Here is another answer: Here is how I solved the issue, it’s a bit of work, but you can now import the modules without hassle,
I created a Python Script, that uses the module subprocess, to write an osgeo4w command called ‘python-qgis’
Its nothing complicated, here it is
I called it NotePadPlus.py (No real reason for calling it that)
I then call this script from the osgeo4w command shell
And now I am able to call the qgis module without any issue! And just to show its not just pretending to accept it I misspelled the Tkinter module and it says it does not exist
I hope this helps, and you can adapt it to suit your needs!
Comment for this answer: Couldn't you just call `python-qgis` from the osgeo4w shell (whithout the python subprocess wrapper script)?
Comment for this answer: yes you can! what I have done is created an entire python script that does various tasks, and at the start the subprocess calls the python-qgis, and this then allows the qgis and other modules to be called in the rest of that same script
|
Title: Show Dynamic Dropdown list for Text Searchable editable WPF COMBOBOX
Tags: c#;.net;wpf;combobox
Question: I have a Combobox which is below. It is working fine. Only Problem is that when i type in it open complete list. But i want that lets say that if i type 'A' then dropdown should only show those words starting with 'A'
```<ComboBox Height="23" HorizontalAlignment="Right" Margin="0,43,140,0" Name="comboBox2" VerticalAlignment="Top" Width="169" IsEditable="True" IsTextSearchEnabled="True" PreviewTextInput="ComboBox_PreviewTextInput"/>
private void ComboBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
comboBox.IsDropDownOpen = true;
}
```
And my dropdown binding is below.
```public void BindMedicalStoreComboBox(ComboBox comboBox1)
{
SqlDataAdapter da = new SqlDataAdapter("Select medical_store_id,m_store_name FROM medical_store", con);
DataSet ds = new DataSet();
da.Fill(ds, "medical_store");
comboBox2.ItemsSource = ds.Tables[0].DefaultView;
comboBox2.DisplayMemberPath = ds.Tables[0].Columns["m_store_name"].ToString();
comboBox2.SelectedValuePath = ds.Tables[0].Columns["medical_store_id"].ToString();
}
```
Comment: https://stackoverflow.com/a/40855376/937093 According to that answer on a similiar question, setting `TextSearch.TextPath` to the same value as your `DisplayMemberPath` should work.
|
Title: Responsive Navbar - Element doesn't disappear upon resize
Tags: javascript;html;css;responsive-design;navigationbar
Question: On this page that I have been fiddling with, I have made a makeshift responsive navigation menu, when the window is made smaller, it's replaced with a standard menu button and a dropdown menu.
Trouble is, when I resize it back up again, the dropdown menu stays visible over the top of the original navigation.
I have tried using media queries and they didn't work. I did try jquery but the issue I had was that once the box was given the property "display:none" by the jquery, then the javascript for the button to reveal the dropdown ceased to work
Here is a reduced down version of the code I am working with...
```function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.hamburger')) {
var dropdowns = document.getElementsByClassName("contents");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}```
```/* header */
.header {
background:#fff;
width:100%;
height:170px;
top:0;
position:fixed;
z-index:9999;
white-space:nowrap;
clear:both;
transition:all 0.25s ease;
border-bottom:1px solid;
}
}
.navbar {
margin-top:130px;
list-style-type: none;
text-align: center;
padding: 0px 0;
color:#000;
display:inline-block;
}
.navbar ul li {
display: inline-block;
margin-right: 0px;
color:#000 ;
}
.navbar ul li a {
text-decoration: none;
/* text-transform: uppercase; */
color:#000 ;
padding: 12px 12px;
font-family: century gothic;
text-align: center;
display: block;
}
.navbar ul li:last-child {
margin-right: 0;
}
.navbar ul li a.active {
text-decoration: none;
/* text-transform: uppercase; */
color: #b1f73d;
padding: 12px 12px;
font-family: century gothic;
text-align: center;
display: block;
bottom:0px;
}
.nav_a a {
display: block;
color: #000;
text-align: center;
padding: 12px 12px;
text-decoration: none;
font-family: century gothic;
}
.nav_a a:hover {
color:#b1f73d;
}
.nav_a a.active:hover {
color:#b1f73d;
}
.hdr-bnr {font-family:century gothic;font-weight:lighter;color:#000;font-size:1.25em;}
@media (min-width:1046px) and (max-width:9999999999px) {
.hamburger {
display:none;
}
.dropdown {
display:none;
}
}
@media (max-width: 1045px) {
.header {
background:#fff;
width:100%;
height:110px;
top:0;
position:fixed;
z-index:9999;
white-space:nowrap;
clear:both;
}
.navbar {
display:none;
}
.hamburger {
display:block;
}
}
/* burger */
.hamburger {
background-color: #FFF;
color: #00811f;
padding: 14px;
font-size: 3.5em;
border: 1px;
cursor: pointer;
float:right;
margin-right:5%;
display:none
border-radius:5px;
}
.hamburger:hover, .hamburger:focus {
background-color: #FFF;
color:#000;
}
.dropdown {
position: relative;
display: block;
}
.contents {
margin-top:110px;
font-family:century gothic;
display: none;
font-size:125%;
position: absolute;
background-color: #fff;
width: 100%;
overflow: auto;
z-index: 1;
}
.contents a {
color: #000;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #00811f; }
.show {display:block; }```
```<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<div class="header">
<nav class="navbar">
<ul>
<li class="nav_a"><a class="active" href="javascript:void(0)">Home</a></li>
<li class="nav_a"><a href="#">page2</a></li>
<li class="nav_a"><a href="#">page3</a></li>
<li class="nav_a"><a href="#">page4</a></li>
<li class="nav_a"><a href="#">page5</a></li>
</ul>
</nav>
<button onclick="myFunction()" class="hamburger">☰</button>
<span class="dropdown">
<div id="myDropdown" class="contents">
<a href="#">Home</a>
<a href="#">page2</a>
<a href="#">page3</a>
<a href="#">page4</a>
<a href="#">page5</a>
</div>
</span>
</div>
<p style="color:#000;margin-top:200px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>```
Apologies I tried to cut out as much bulk as possible, can someone please tell me what I'm doing wrong?
Thanks!
Comment: If you were to click the hamburger button to reveal the dropdown menu, and then resize the window, you will notice that the dropdown menu still stays there even though I have defined it in the media query to 'display:none'.
Comment: Your hamburger button is behaving like you defined it in your CSS: it will only disappear once the width of the screen is >1370. Unless I'm confused about what you want to achieve, this is just a case of defining your media query width correctly..
Comment: I have added the explanation and solution to your problem below.
Here is the accepted answer: ok, since you told us the following in the comments:
```
If you were to click the hamburger button to reveal the dropdown menu, and then resize the window, you will notice that the dropdown menu still stays there even though I have defined it in the media query to 'display:none'.
```
This is (as far as I know) totally correct behaviour, the reason being the following:
When you click the 'hamburger' button, this click will toggle the class='show' for your menu dropdown. In this case a click on the hamburger button will change this code:
```<div id="myDropdown" class="contents">
<a href="#">Home</a>
<a href="#">page2</a>
<a href="#">page3</a>
<a href="#">page4</a>
<a href="#">page5</a>
</div>
```
to this: (adds or deleted the class='show'; depending if you are opening or closing the menu)
```<div id="myDropdown" class="contents show"> <---- Adds or removes show class
<a href="#">Home</a>
<a href="#">page2</a>
<a href="#">page3</a>
<a href="#">page4</a>
<a href="#">page5</a>
</div>
```
So since you are only setting the visibility of the hamburger button to 'display:none', the dropdown still keeps the class='show'.
In the end, you are just making the button invisible, but not the the dropdown menu.
You can simply solve your problem by changing
```@media (min-width:1046px) and (max-width:9999999999px) {
.dropdown {
display:none;
}
}
```
to be
```@media (min-width:1046px) and (max-width:9999999999px) {
.dropdown .show { <--- specify that you don't want to show the dropdown if it has the class='show'
display:none;
}
}
```
(You can also achieve this with jQuery if prefered, by adding or removing the 'show' class from the dropdown; or by triggering the 'toggle' function for the dropdown)
I hope it helps
```function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.hamburger')) {
var dropdowns = document.getElementsByClassName("contents");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}```
```/* header */
.header {
background:#fff;
width:100%;
height:170px;
top:0;
position:fixed;
z-index:9999;
white-space:nowrap;
clear:both;
transition:all 0.25s ease;
border-bottom:1px solid;
}
}
.navbar {
margin-top:130px;
list-style-type: none;
text-align: center;
padding: 0px 0;
color:#000;
display:inline-block;
}
.navbar ul li {
display: inline-block;
margin-right: 0px;
color:#000 ;
}
.navbar ul li a {
text-decoration: none;
/* text-transform: uppercase; */
color:#000 ;
padding: 12px 12px;
font-family: century gothic;
text-align: center;
display: block;
}
.navbar ul li:last-child {
margin-right: 0;
}
.navbar ul li a.active {
text-decoration: none;
/* text-transform: uppercase; */
color: #b1f73d;
padding: 12px 12px;
font-family: century gothic;
text-align: center;
display: block;
bottom:0px;
}
.nav_a a {
display: block;
color: #000;
text-align: center;
padding: 12px 12px;
text-decoration: none;
font-family: century gothic;
}
.nav_a a:hover {
color:#b1f73d;
}
.nav_a a.active:hover {
color:#b1f73d;
}
.hdr-bnr {font-family:century gothic;font-weight:lighter;color:#000;font-size:1.25em;}
@media (min-width:1046px) and (max-width:9999999999px) {
.hamburger {
display:none;
}
.dropdown .show {
display:none;
}
}
@media (max-width: 1045px) {
.header {
background:#fff;
width:100%;
height:110px;
top:0;
position:fixed;
z-index:9999;
white-space:nowrap;
clear:both;
}
.navbar {
display:none;
}
.hamburger {
display:block;
}
}
/* burger */
.hamburger {
background-color: #FFF;
color: #00811f;
padding: 14px;
font-size: 3.5em;
border: 1px;
cursor: pointer;
float:right;
margin-right:5%;
display:none
border-radius:5px;
}
.hamburger:hover, .hamburger:focus {
background-color: #FFF;
color:#000;
}
.dropdown {
position: relative;
display: block;
}
.contents {
margin-top:110px;
font-family:century gothic;
display: none;
font-size:125%;
position: absolute;
background-color: #fff;
width: 100%;
overflow: auto;
z-index: 1;
}
.contents a {
color: #000;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #00811f; }
.show {display:block; }```
```<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<div class="header">
<nav class="navbar">
<ul>
<li class="nav_a"><a class="active" href="javascript:void(0)">Home</a></li>
<li class="nav_a"><a href="#">page2</a></li>
<li class="nav_a"><a href="#">page3</a></li>
<li class="nav_a"><a href="#">page4</a></li>
<li class="nav_a"><a href="#">page5</a></li>
</ul>
</nav>
<button onclick="myFunction()" class="hamburger">☰</button>
<span class="dropdown">
<div id="myDropdown" class="contents">
<a href="#">Home</a>
<a href="#">page2</a>
<a href="#">page3</a>
<a href="#">page4</a>
<a href="#">page5</a>
</div>
</span>
</div>
<p style="color:#000;margin-top:200px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>```
Comment for this answer: Works great, although I would have liked the menu itself to close if that were possible so that if it were to be resized back down it wouldn't automatically pop up without being clicked again (haven't written that very well), but this works, thank you for your help Kevin!
|
Title: How to multiply multiple input type number with the same ID and name
Tags: php;jquery;mysql;forms
Question: This code is working fine, but mine has multiple inputs with same ID and name. I think the multiple statements don't recognize another ID.
```while($d = mysqli_fetch_array($data)){
?>
<tr>
<td align="text-center"><?php echo $no++; ?></td>
<td align="text-center"><input type="text" name="naran[]" value="<?php echo $d['naran'];?>"></td>
<td align="text-center"><input type="hidden" name="kode_sasan[]" value="<?php echo $d['kode_sasan'];?>"></td>
<td align="text-center"><input type="number" name="hamutuk[]" onfocus="sr()" onblur="psr()" id="hamutuk" ></td>
<td align="text-center"><input type="number" name="total[]" id="total" ></td>
<td align="text-center"><input type="hidden" value="<?php echo $d['folin_faan'];?>" name="folin_faan[]" onfocus="sr()" onblur="psr()" id="folin_faan""></td>
<td><a href="update.php?edit=<?php echo $d['id']; ?>"" type="button" class="btn btn-info glyphicon glyphicon-pencil"></a>
<a onclick="return confirm('Ita boot Hakarak Duni atu hamos?')" href="hamosfaan.php?hms=<?php echo $d['kode_sasan']; ?>" type="button" class="btn btn-danger glyphicon glyphicon-remove"></a>
</td>
</tr>
<?php } ?>
</table>
<button type="submit" name="sosa" class="btn btn-primary ">Processa</button>
</form>
<script type="text/javascript">
function kms(){
Interval = setInterval ("sr()",1);
}
function sr(){
folin_faan=parseFloat(document.getElementById("folin_faan").value);
hamutuk=parseFloat(document.getElementById("hamutuk").value);
total = folin_faan * hamutuk;
document.getElementById("total").value=total.toFixed(2);
}
function psr(){
clearInterval(Interval);
}
</script>
```
Comment: Any idea of id must be unique. Is anyway to use?
Comment: Multiple inputs with the same id is not valid HTML. id must be unique within the document.
Comment: You can use classes instead. You can add event listeners to the fields that are used to calculate the totals, and find the other relevant inputs in the same row as the input that caused the event.
Here is another answer: do not use the same ID.
you can make your id unique. on your while loop, you can manipulate the ID.
for example
```<td align="text-center"><input type="number" name="hamutuk[]" onfocus="sr(<?php echo $no;?>)" onblur="psr(<?php echo $no;?>)" id="hamutuk<?php echo $no;?>" ></td>
```
Comment for this answer: how about id for total to showing results :
|
Title: 64 bit c++ console application in Visual Studio
Tags: c++;visual-studio-2015;windows-10
Question: Using Visual Studio 2015 Community, I want to create a console application in C++. If I use file-->new-->project, and try to find a suitable template, I can find console application under win32. Does "win32" imply it will be for a 32 bit machine (runnable on a 64 bit machine, ub not optimum)? Is there some other route I should be taking if I'm only interested in 64 bit machines?
Comment: A 64-bit OS does not mean you should use 64-bit executables. 64-bit exes are considerably slower in most cases than 32-bit running on the same hardware. You only need to target 64-bit if you need to allocate extremely large amounts of memory (> 2GB) or have a very specific need to use 64-bit registers and operations.
Comment: You can do math on 64-bit integers without creating a 64-bit application. 32-bit applications support 64-bit integers and have for decades now.
Comment: Thanks. I won't need too much memory, but I'm interested in doing arithmetic on 64 bit integers.
|
Title: Bad words regex filter not working
Tags: php;regex
Question: I'm trying to get a bad words filter to work. So far, with the code below, no filtering happens if I type a bad word like "bad1" listed in array below and I get this error:
```
Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’
```
Here is the code:
```if (isset($_POST['text'])) {
// Words not allowed
$disallowedWords = array(
'bad1',
'bad2',
);
// Search for disallowed words.
// The Regex used here should e.g. match 'are', but not match 'care'
foreach ($disallowedWords as $word) {
if (preg_match("/\s+$word\s+/i", $entry)) {
die("The word '$word' is not allowed...");
}
}
// Variable contains a regex that will match URLs
$urlRegex = '/(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-
9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]
{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1
-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)
\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost
|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.
(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-z
A-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*/';
// Search for URLs
if (preg_match($urlRegex, $entry)) {
die("URLs are not allowed...");
}
}
```
Comment: `preg_quote()` for the words list. The error actually stems from unescaped `/` delimiters in the URL regex. Escape them.
Comment: I would use this regex: /\b$word\b/i, because it will match bad words at the end and at the beginning of string too, not just between words...
Comment: Why match it that way. You can check for matches with http://php.net/strpos. As to your question the regex fails because you are requiring white space on both side. You want `\s*` but then `notbadword` would also match...
Comment: You have two issues, missed the error [email protected]. That is from your delimiters. Check URL checker regex.
Here is the accepted answer: This is the right way of matching the words. Use this regex in your foreach loop.
```preg_match("#\b" . $word . "\b#", $entry);
```
You can also test your regular expressions here. Use ```/\bbad1\b/g```.
The code put in action:
```<?php
// delete the line below in your code
$entry = "notbad1word bad1 bad notbad1.";
$disallowedWords = array(
'bad1',
'bad2',
);
foreach ($disallowedWords as $word)
{ // use $_POST['text'] instead of $entry
preg_match("#\b". $word ."\b#", $entry, $matches);
if(!empty($matches))
die("The word " . $word . " is not allowed.");
}
echo "All good.";
```
This code doesn't match ```notbad1word``` or ```notbad2word``` (and so on) but matches only ```bad1``` or ```bad2```.
As to your urlRegex, you have to escape ```/``` with ```\``` like this: ```\/```
Here is another answer: You can do that without a slow loop:
```<?php
$_POST['text'] = 'This sentence uses the nobad1 bad2 word!';
if (isset($_POST['text'])) {
// Words not allowed
$disallowedWords = array(
'bad1',
'bad2',
);
$pattern = sprintf('/(\\s%s\\s)/i', implode('\\s|\\s',$disallowedWords));
$subject = ' '.$_POST['text'].' ';
if (preg_match($pattern, $subject, $token)) {
die(sprintf("The word '%s' is not allowed...\n", trim($token[1])));
}
}
```
You have to make sure that the catalog of words does not contain any characters of ```/```, ```(``` or ```)```.
Comment for this answer: @jvitasek And the OP said where that this should not occur?
Comment for this answer: @jvitasek Yes, but it is the OPs system, not yours. You do not know what the OP wants. At least you should not assume you do. A common mistake...
Comment for this answer: @jvitasek You are right there. Thanks for pointing that out. How good that I already added a version that considers that.
Comment for this answer: This works nicely and is much more clean and simple. Do you advise I stick the redirect to the form on the same page be added right after the die line?
Comment for this answer: I am wrong to think this is going to match `notbad1` in the string too?
Comment for this answer: A common mistake is not to read the question. It explicitly states in a comment `// The Regex used here should e.g. match 'are', but not match 'care'`
Here is another answer: You're using ```/``` as delimiting character, but don't escape its "inner" occurences:
```$urlRegex = '/(http|https|ftp)\://whatever/';
// ^ Unknown modifier ‘/’
```
Either change the delimiter, or escape the slashes.
As to your "bad words" filter:
It will fail to recognize words at the beginning and end of the string. Consider using ```\b``` (word boundary) instead of ```\s+```.
If any of the bad words in your array has an unescaped regex character, the results might be unexpected. Consider using ```preg_quote``` on each word from the array.
n ```preg_match``` calls for n words is not very efficient. I'd recommend imploding the words array into a single regex like ```'/\b(word1|word2|word3)\b/i'```.
|
Title: Why is color defined in IB different than one defined in code?
Tags: ios;objective-c;xcode;uicolor
Question: I have a single view app. I define two ```UIView``` instances inside that single view. I want both to have same color.
For first view I define it in Interface Builder and pick a color. I want ```#999999``` (grey). New color picker has possibility to enter hex color values so it is easy to enter: ```999999```.
For the second view, I define it by setting background color of second view. I set same ```#999999``` color using ```[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1]```.
Simple calculation: ```#99 -> 153 -> 153/255 == 0.6.``` So far good.
However resulting colors are different. Why? This feels like a bug in xcode. After debugging resulting colors:
Color defined in IB: ```UIDeviceRGBColorSpace 0.529648 0.529632 0.529641 1```
Color defined in code:```UIDeviceRGBColorSpace 0.6 0.6 0.6 1```
UPDATE:
I know about "duplicates" to this question. They have one thing in common. They properly identified the problem but failed miserably to solve it. It tested developer color pickers from Panic and Skala. They have same problem. And as insult to injury they offer copy color as hex values. Guest what, numbers there are not affected by color [email protected]. So for example color ```#999``` they provide exactly ```0.6``` for each color component. Unfortunately, if color is used directly it has color profile attached and resulting color is different. Only way to get exact RBG color is to use "safe web colors" where resulting color is with generic RGB color profile, in other words not affected. Problem is that safe web colors doesn't contain all colors our designers use.
Comment: Formatted code, and fixed grammar.
Comment: your calculation is wrong! #99 -> 160!
Comment: @rmaddy sorry. my bad! i added 16 accidentally!
Comment: @AndreSlotta No. #99 is 153 (9 * 16 + 9 = 153).
Here is the accepted answer: This whole issue is fixed by Apple in El Capitan. So if you are using xcode 7 on El Capitan this is no longer an issue. Entering #hex color value doesn't change color space anymore.
Here is another answer: You can do it in such way
And code for another view:
```self.testView.backgroundColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
```
UPDATE:
In Xcode, click the colorspace popup in the color picker and choose "Generic RGB", then enter the red, green and blue values from Photoshop, NOT THE HEX VALUE
And we can find so many duplicates:
Wrong color in Interface Builder's color picker
Weird colors in XCode Interface Builder?
Wrong color in Interface Builder
Xcode 6 beta color picker issue
...
Comment for this answer: If you do like i show, result will be same. If use RGB Sliders - result is not the same.
Comment for this answer: update: chose Generic RGB and change values and don't touch hex value
Comment for this answer: Sometimes it's better to do as possible, rather than seek the most convenient way.
Comment for this answer: well, question is why if you define color in IB it is not the same color as defined in code. I know how to define colors. But result is not the same. Colors from IB are a bit darker.
Comment for this answer: True, when using web safe colors it works. But how to enter my custom colors there?
Comment for this answer: yes, this kind of works. But it is far away from being convenient.
Here is another answer: Here is a category on UIColor that can create a ```UIColor``` from a hex string if it will help.
```+ (UIColor *)rz_colorFromHex:(uint32_t)hexLiteral
{
uint8_t r = (uint8_t)(hexLiteral >> 16);
uint8_t g = (uint8_t)(hexLiteral >> 8);
uint8_t b = (uint8_t)hexLiteral;
return [self rz_colorFrom8BitRed:r green:g blue:b];
}
+ (UIColor *)rz_colorFromHexString:(NSString *)string
{
NSParameterAssert(string);
if ( string == nil ) {
return nil;
}
unsigned int hexInteger = 0;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"x#"]];
[scanner scanHexInt:&hexInteger];
return [self rz_colorFromHex:hexInteger];
}
```
As to why your colors are different. I would set a breakpoint and see that the colors are in fact the same while it is running. You can even print out the rgb channels for each of the colors to make sure they aren't different.
I would be surprised if it is an Xcode bug, but let me know what happens when you inspect the colors from the debugger.
EDIT:
So looking into this more there are different color spaces that you can use for RGB. By default interface builder is using a different one that iOS uses. To switch them click the little gear when you are using the color picker and set it to Generic RGB.
Comment for this answer: Updated my answer, hopefully this helps.
Comment for this answer: Hacky, but if you set it to `A9A9A9` and then switch from sRGB to generic it should switch it to `999999` for you. Not sure why it does that.
Comment for this answer: Defined in IB: UIDeviceRGBColorSpace 0.529648 0.529632 0.529641 1
Defined in code: UIDeviceRGBColorSpace 0.6 0.6 0.6 1
Comment for this answer: Answer make sense. When I select generic RGB, it is indeed the value I see reported by debugger. I am still battling how to enter #999 with color picker. Everytime I switch to generic RGB and enter 99999 it switches to sRGB.
|
Title: Ubuntu command ln -fs
Tags: ruby;bash;shell;ubuntu;nginx
Question: on a mina-deploy script after install monit the script create a link with the monitored services like nginx etc.
but before finish the install show this error,
someone know what is
ln -fs
command on shell?
```
-----> Setting up Monit...
-----> Put monit/nginx.erb file to /shared/config/monit/nginx bash: line 82: /shared/config/monit/nginx: Is a directory $ sudo ln -fs "/shared/config/monit/nginx" "/"
-----> FAILED
```
the rest of the script
```namespace :monit do
desc "Install Monit"
task :install do
invoke :sudo
queue %{echo "-----> Installing Monit..."}
queue "sudo apt-get -y install monit"
end
desc "Setup all Monit configuration"
task :setup do
invoke :sudo
if monitored.any?
queue %{echo "-----> Setting up Monit..."}
monitored.each do |daemon|
invoke :"monit:#{daemon}"
end
invoke :'monit:syntax'
invoke :'monit:restart'
else
queue %{echo "-----> Skiping monit - nothing is set for monitoring..."}
end
end
task(:nginx) { monit_config "nginx" }
task(:postgresql) { monit_config "postgresql" }
task(:redis) { monit_config "redis" }
task(:memcached) { monit_config "memcached" }
task(:private_pub) { monit_config "private_pub", "#{private_pub_name}" }
%w[start stop restart syntax reload].each do |command|
desc "Run Monit #{command} script"
task command do
invoke :sudo
queue %{echo "-----> Monit #{command}"}
queue "sudo service monit #{command}"
end
end
end
```
Here is another answer: man-page for ```ln``` would be a good start.
```ln -fs [TARGET] [DIRECTORY]
```
Makes symbolic link between files. ```-f``` will "force" the link to be updated, if already exists.
Given the wording in your error message, I'm guessing ```/shared/config/monit/nginx``` doesn't exist, which is why the ```ln``` command fails.
|
Title: ol tag in Chrome
Tags: html;css;google-chrome
Question: I have a simple ol list in a div:
```<div class="one">Title<hr width="200px">
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ol>
</div>
```
Divs CSS:
```div.one {
float:left;
width:250px;
height:525px;
background-color:#e0e0e0;
font-size:30px;
margin:2px;
color:#6d6e71;
}
```
On FF and IE the numbers are created where the text (center alignment inherited) starts but on Chrome numbers are created where the div starts. How to solve this problem?
Here is the accepted answer: Try adding this:
```div.one ol {list-style-position:inside; margin:0; padding:0;}
```
http://jsfiddle.net/yzyXE/
|
Title: selecting a column from pandas pivot table
Tags: python;pandas;pivot-table;python-3.5
Question: I have the below pivot table which I created from a dataframe using the following code:
```table = pd.pivot_table(df, values='count', index=['days'],columns['movements'], aggfunc=np.sum)
movements 0 1 2 3 4 5 6 7
days
0 2777 51 2
1 6279 200 7 3
2 5609 110 32 4
3 4109 118 101 8 3
4 3034 129 109 6 2 2
5 2288 131 131 9 2 1
6 1918 139 109 13 1 1
7 1442 109 153 13 10 1
8 1085 76 111 13 7 1
9 845 81 86 8 8
10 646 70 83 1 2 1 1
```
As you can see from pivot table that it has 8 columns from 0-7 and now I want to plot some specific columns instead of all. I could not manage to select columns. Lets say I want to plot column 0 and column 2 against index. what should I use for y to select column 0 and column 2?
```plt.plot(x=table.index, y=??)
```
I tried with ```y = table.value['0', '2']``` and ```y=table['0','2']``` but nothing works.
Here is the accepted answer: You cannot select ndarray for ```y``` if you need those two column values in a single plot you can use:
```plt.plot(table['0'])
plt.plot(table['2'])
```
If column names are intergers then:
```plt.plot(table[0])
plt.plot(table[2])
```
Comment for this answer: Thanks. The column names are integers. When I do plt.plot(x=table.index, y=table[0]), I do not get any error but somehow plotting function does something wrong. It just shows an empty plot with x and y range of -0.5 - 0.5. However, doing print(table[0]) does show right data. Somehow, plt.plot(table[0]) and later plt.plot(table[2]) seems to work.
|
Title: Can I use comparison between two variables inside a Ruby case statement?
Tags: ruby
Question: I'm trying out this code but getting nil everytime (It's a simplyfied version of a Black Jack game):
Is it because I'm comparing two variables in a case statement?
```def end_game_message(player_score, bank_score)
message = ""
case player_score
when player_score == 21
message = "Black Jack!"
when player_score > bank_score
message = "You win!"
when player_score > 21
message = "You lose!"
when player_score < bank_score
message = "You lose"
when player_score == bank_score
message = "Push"
end
message
end
puts end_game_message(21, 15)
```
Thanks in advance for any help!
Comment: @NicolasPoletti : While the answer of Masafumi Okura is correct, it does not explain exactly why your approach failed: You `when` statements all evaluate to either `true` or `false`, and the expression after `case` is an integer value. Since an integer never matches either true or false, none of the `when` clauses succeed. Since you have provided no `else` clause, your `case` statement has no effect. In particular, it does not reassign `message`. Hence, since you return `message`, which is initially set to `""`, the function will return the null string, and not `nil`, as JörgWMittag said.
Comment: Where, exactly, are you getting `nil`? I don't see how this code can produce `nil`. (Well, the return value of `puts` is `nil`, but it is *always* `nil`, so that shouldn't be surprising.)
Here is the accepted answer: IMO, you should use ```if``` instead of ```case``` in this case. If you'd like to use ```case```, however, the code might look like this:
```def end_game_message(player_score, bank_score)
case player_score
when 21
"Black Jack!"
when -> s { s > bank_score }
"You win!"
when -> s { s > 21 }
"You lose!"
when -> s { s < bank_score }
"You lose"
when -> s { s == bank_score }
"Push"
end
end
puts end_game_message(21, 15)
```
The key point is to give ```Proc``` object to ```when``` clause. In this case, ```s``` is ```player_score``` (value given to ```case``` clause`).
(And minor improvement: ```case``` statement returns value so you don't have to assign a message to local variable)
Comment for this answer: Or use the `case\nwhen player_score == 21 ...` form (i.e. just drop the `player_score` from `case player_score`. Also worth mentioning that your proc-version works because the `case expr` form uses the `===` operator to "compare" `expr` with each of the `when`s and [evaluates the proc with `expr` as its argument](https://ruby-doc.org/core/Proc.html#method-i-3D-3D-3D).
Comment for this answer: This concludes the player loses if the player's score is no more than 21 and the dealer's score is greater than 21. Also, `when -> s { s > 21 }` must precede `when -> s { s > bank_score }`.
Here is another answer: ```def end_game_message(player_score, bank_score)
case player_score
when 21
bank_score == 21 ? "Push" : "Black Jack!"
when (22..)
"You lose!"
when (..bank_score-1)
bank_score <= 21 ? "You lose!" : "You win"
when (bank_score+1..)
"You win!"
else
"Push"
end
end
```
```end_game_message(21,18) #=> "Black Jack!"
end_game_message(21,21) #=> "Push"
end_game_message(22,22) #=> "You lose!"
end_game_message(12,22) #=> "You win!"
end_game_message(18,19) #=> "You lose!"
end_game_message(19,18) #=> "You win!"
end_game_message(18,18) #=> "Push"
```
```(..bank_score-1)``` and ```(bank_score+1..)``` are beginless and endless ranges, introduced in Ruby v2.7. They are not essential, of course, as they could be replaced with ```(0..bank_score-1)``` and ```(bank_score+1..30)```. ```(...bank_score)``` could be used in place of ```(..bank_score-1)``` but my own style guide states that three-dot ranges are to be avoided except where the end of an infinite range is to be excluded.
Here is another answer: There are actually several different questions in your question.
The first is in the title:
```
Can I use comparison between two variables inside a Ruby case statement?
```
And the answer to that is "Yes, of course, why wouldn't you?" You can use any Ruby expression.
Okay, well, if we want to be really pedantic, the answer is "No", for two reasons:
You cannot compare variables, you can only compare objects, and variables aren't objects.
Ruby doesn't have a ```case``` statement, only a ```case``` expression. (In fact, Ruby doesn't have [email protected].)
(This may sound overly pedantic, but understanding the difference between variables and objects is fundamental not only in Ruby, but in programming in general, as is the difference between expressions and statements.)
Your next question is, why you get ```nil```. The answer to that is that the last expression in your code is
```puts end_game_message(21, 15)
```
So, your code evaluates to the return value of ```Kernel#puts```, and ```Kernel#puts``` is defined to always return ```nil```.
The question that I think you are really asking but isn't actually in your question, is "Why does the ```case``` expression not work how I think it does?"
You simply need to remember how the ```case``` expression is evaluated. There are two different forms of the ```case``` expression. (See section 51.243.225.55.4 The ```case``` expression) of the ISO Ruby Language Specification, for example.
The simpler form is what the ISO Ruby Language Specification calls the ```case```-expression-without-expression, which looks like this:
```case # Look ma, no expression
when bar then :bar
when baz then :baz
else :qux
end
```
And is evaluated like this:
```if bar then :bar
elsif baz then :baz
else :qux
end
```
The other form is the ```case```-expression-with-expression
```case foo # In this case, there is an expression here
when bar then :bar
when baz then :baz
else :qux
end
```
Which is evaluated like this:
```if bar === foo then :bar
elsif baz === foo then :baz
else :qux
end
```
In your case, you are using the ```case```-expression-with-expression, so your ```case``` expression is evaluated like this:
```if (player_score == 21) === player_score
message = "Black Jack!"
elsif (player_score > bank_score) === player_score
message = "You win!"
elsif (player_score > 21) === player_score
message = "You lose!"
elsif (player_score < bank_score) === player_score
message = "You lose"
elsif (player_score == bank_score) === player_score
message = "Push"
end
```
Since ```player_score == 21```, ```player_score > bank_score```, ```player_score > 21```, ```player_score < bank_score```, and ```player_score == bank_score``` all evaluate to either ```true``` or ```false``` and ```player_score``` is a number, all the branches in your ```case``` expression are actually checking something like this:
```some_boolean === some_number
```
Which is never true!
So, how do we fix this?
The simplest fix would be to use the ```case```-expression-without-expression instead, and to do that, the only thing we need to do, is delete the expression after the ```case```:
```case
when player_score == 21
message = "Black Jack!"
when player_score > bank_score
message = "You win!"
when player_score > 21
message = "You lose!"
when player_score < bank_score
message = "You lose"
when player_score == bank_score
message = "Push"
end
```
This will be evaluated like this:
```if player_score == 21
message = "Black Jack!"
elsif player_score > bank_score
message = "You win!"
elsif player_score > 21
message = "You lose!"
elsif player_score < bank_score
message = "You lose"
elsif player_score == bank_score
message = "Push"
end
```
Which will do what you want.
If you want to keep the ```case```-expression-with-expression, you need to make sure that the ```when```-argument of each ```when```-clause is something that responds to ```===``` in a way that makes sense for your comparison.
We could, for example, use ```Range```s and ```Integer```s. The ```Range#===``` method checks whether the argument is inside the ```Range``` and the ```Integer#===``` method checks whether the argument is numerically equal, so we could re-write the ```case``` expression like this:
```case player_score
when 21
message = "Black Jack!"
when ((bank_score + 1)..)
message = "You win!"
when (22..)
message = "You lose!"
when ...bank_score
message = "You lose"
when bank_score
message = "Push"
end
```
Since the cases are evaluated top to bottom and you can evaluate multiple conditions in the same case, we can re-shuffle these a bit to make them nicer to read:
```case player_score
when 21
message = "Black Jack!"
when bank_score
message = "Push"
when 21.., ...bank_score
message = "You lose!"
when (bank_score..)
message = "You win!"
end
```
Also, remember that the ```case``` expression is an expression, meaning that it evaluates to a value, namely it evaluates to the value of the branch that was evaluated. Therefore, we can "pull out" the assignment to ```message```:
```message = case player_score
when 21
"Black Jack!"
when bank_score
"Push"
when 21.., ...bank_score
"You lose!"
when (bank_score..)
"You win!"
end
```
Note that this has slightly different semantics than what we had before: Before, the assignment was only evaluated when one of the branches was evaluated, otherwise, the value of ```message``` stayed what it was before. Whereas in this form, the assignment is always evaluated, and if none of the branches gets evaluated, the ```case``` expression evaluates to ```nil```.
However, the way the ```case``` expression is written, all cases are covered, so there will always be a non-```nil``` value assigned.
Once we have made this transformation, we notice that at the beginning of the method, message is assigned the empty string ```""``` and then immediately gets assigned a different value. So, we can get rid of the first assignment, since its effects are immediately overwritten anyway.
And once we have done that, we see that we assign to the ```message``` variable and then immediately return it. So, we might just as well return the value of the ```case``` expression instead, like this:
```def end_game_message(player_score, bank_score)
case player_score
when 21
"Black Jack!"
when bank_score
"Push"
when 21.., ...bank_score
"You lose!"
when (bank_score..)
"You win!"
end
end
```
Comment for this answer: There’s another case you need to account for: the player’s score 21. Here the player wins but you have the player losing. Dealing with that is non-trivial as you cannot merely compare the two scores. Also, the “Push” case needs to follow the “You lose!” case because the player loses if the scores are equal and greater than 21.
Comment for this answer: Thanks. I was indeed too aggressive in refactoring / simplifying.
Comment for this answer: @CarySwoveland: If only questions came with test suites :-D
|
Title: In the ground state of helium what's the differing quantum number?
Tags: quantum-mechanics;atomic-physics;quantum-spin;pauli-exclusion-principle
Question: In the ground state of the helium atom, both the electrons have the same quantum numbers $(n,l,m)$ equal to $(1,0,0)$. By Pauli's exclusion principle, the fourth quantum number must be different. What is this fourth quantum number when the electrons are actually in an antisymmetric entangled spin-singlet state?
Here is the accepted answer: The spin. Nothing more and nothing less. The fact that the electrons occupy an entangled spin singlet is the natural consequence of the antisymmetrization required by the Pauli exclusion principle when it is applied to two electrons on states that differ only by their magnetic quantum number.
Comment for this answer: Yes. The antisymmetrized version of that.
Comment for this answer: $m_{s_1}=+1/2$ and $m_{s_2}=-1/2$?
|
Title: How to sort Object properties by Key while the keys are floating numbers?
Tags: javascript;sorting;ecmascript-6;lodash
Question: I have an Object like this:
```let arr ={
1.2 : 44,
55: 41,
13: 59,
2.3 : 77
}
console.log(Object.fromEntries(Object.entries(arr).sort()))
// Result:
// {
// "13": 59,
// "55": 41,
// "1.2": 44,
// "2.3": 77
// }
// Expected Result:
// {
// "1.2": 44,
// "2.3": 77,
// "13": 59,
// "55": 41
// }```
The sort function treats keys as string and not floating point numbers.
I've tried Lodash Sort too, but no luck.
Any help would be appreciated.
Comment: @adiga you're too fast - went to edit in the ES6 ordering dupes and they were already there :D
Comment: At any rate, that's correct - keys that contain non-negative integers will always be 1. sorted first 2. sorted in order. If order is important *do not rely on object keys*. Use a different structure that defines the order via an array - using objects: `[{id: 1.2, value: 44}, { id: 2.3, value: 77}]` or using an array of pairs `[[1.2, 44], [2.3, 77]]`. The latter can be useful for directly loading into a map: `new Map([[1.2, 44], [2.3, 77]])` will create a map `{ 1.2 → 44, 2.3 → 77 }` and would 1. preserve the type of the keys (they'd be numbers) 2. preserve the insertion order.
Comment: 13 and 55 will always be on top because integer keys are enumerated in ascending order before other keys.
|
Title: XML - how to decide wether to put same nodes in parent node
Tags: xml
Question: I have an XML ```bookstore``` and I am not sure how to structure it.
The thing I am focussing on is that a book can have multiple authors.
I usually see XMLs putting elements with the same name in a parent element.
What's the idea behind that? What are the advantages and disadvantages in the following two slightly different approaches?
1) Authors are not in a parent element:
```<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="web">
<title lang="en">Superbook</title>
<author>
<name>Clark</name>
<lastname>Kent</lastname>
</author>
<author>
<name>Lois</name>
<lastname>Lane</lastname>
</author>
<author>
<name>Lex</name>
<lastname>Luther</lastname>
</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Batman</title>
<author>
<name>Bruce</name>
<lastname>Wayne</lastname>
</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
```
2) Authors are in a parent element:
```<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="comic">
<title lang="en">Superbook</title>
<authors>
<author>
<name>Clark</name>
<lastname>Kent</lastname>
</author>
<author>
<name>Lois</name>
<lastname>Lane</lastname>
</author>
<author>
<name>Lex</name>
<lastname>Luther</lastname>
</author>
</authors>
<year>2003</year>
<price>49.99</price>
</book>
<book category="comic" cover="paperback">
<title lang="en">Batman</title>
<authors>
<author>
<name>Bruce</name>
<lastname>Wayne</lastname>
</author>
</authors>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
```
Comment: That's primarily opinion based. My personal opinion is that grouping same elements in a super-element makes the XML more readable/handy. For example, you could simply "mask" the `` element (with all `` sub-elements) in a capable editor by clicking on the `+`/`-` on the left site. But this is just one minor advantage.
Comment: I really like the advantage of "masking". I've tried it with the Brackets editor and I find it surprisingly useful!
Here is another answer: It's up to you as the W3 specification sites you can use elements / attributes as you see fit.
I use an attribute based layout, and avoid "collection" elements like "authors" that really don't serve a purpose
```<xml>
<book category='web' year='2003' price='49.99'>
<title lang='en'>Superbook</title>
<author name='Clark' lastname='Kent'/>
<author name='Lois' lastname='Lane'/>
<author name='Lex' lastname='Luther'/>
</book>
<book category='web' cover='paperback' year='2003' price='49.99'>
<title lang='en'>Batman</title>
<author name='Bruce' lastname='Wayne'/>
</book>
</xml>
```
Comment for this answer: The data argument is well known, and a common approach. It extends the approach used for HTML. However, XML is much bigger than HTML. In HTML, data (elements) is "visible", and attributes are not. In a XML document, there's no distinction between "visible" and "invisible", everything is "data". With that in mind, the attribute based XML camp starts designs with everything as an attribute, and uses elements to group attributes together. There is no "right" answer here elements or attributes. Do avoid extra grouping, and never put numbers in element / attribute names : ).
Comment for this answer: I thought about the use of attributes too and came across an [IBM developer article](https://www.ibm.com/developerworks/xml/library/x-eleatt/index.html) that's worthwile reading: The takeaway for me was "`data goes in elements, metadata in attributes`", and for me "name" as well as "last name" is data.
Comment for this answer: Thank's for the insight! From some recent experience with attributes I tend to shy away from using them for names or anything I would usually put inside CDATA. Just imagine: `name='Antoine Jérôme'` or `title='Wallace & Gromit: The Curse of the Were-Rabbit (2005)'`
|
Title: Shell script to find the missing numbers in a file
Tags: bash;shell
Question: Below is the example file I have with name ```Weeks```:
```2002
2004
2005
2006
2010
```
And I wanted a simple script to display the missing number from the files. I tried the below script but didn't get expected results.
```#!/bin/bash
filename='Weeks'
Sw=2001
while read line; do
#Reading each line.
if [ $line != $Sw ]
then
Sw=$(($Sw+1))
echo "$line"
else
Sw=$(($Sw+1))
fi
done < $filename
```
Expected output is:
```2001
2003
2007
2008
2009
```
Please help me I don't why the above script is not giving me correct output.
Comment: Why is 2001 expected, but not 2011 or 9999?
Here is another answer: ```comm -13 Weeks <(seq 2001 2010)
```
That should do the trick.
```seq```:
```NAME
seq - print a sequence of numbers
SYNOPSIS
seq [OPTION]... LAST
seq [OPTION]... FIRST LAST
seq [OPTION]... FIRST INCREMENT LAST
DESCRIPTION
Print numbers from FIRST to LAST, in steps of INCREMENT.
[...]
```
```comm```:
```NAME
comm - compare two sorted files line by line
SYNOPSIS
comm [OPTION]... FILE1 FILE2
DESCRIPTION
Compare sorted files FILE1 and FILE2 line by line.
When FILE1 or FILE2 (not both) is -, read standard input.
With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files.
-1 suppress column 1 (lines unique to FILE1)
-2 suppress column 2 (lines unique to FILE2)
-3 suppress column 3 (lines that appear in both files)
[...]
```
The ```<(...)``` syntax tricks ```comm``` into believing, that the output of ```seq``` is actually a file.
In your original script there is an initial logic error, that follows execution until the end. Ask yourself, what happens in the very first iteration of the ```while``` loop: ```$Sw``` is ```2001```, ```$line``` is ```2002```. ```$Sw``` will be incremented to ```2002```, but in the next iteration compared to ```2004``` and so on.
Additionally you print ```$line```, which is the wrong variable.
A possible (albeit a bit inefficient) solution for the logic would be to nest another ```for``` loop in the while loop to look for and print items missing between the last ```$line``` value (that you need to store at the end of each loop in another variable) and the current ```$line``` value.
Comment for this answer: Hm, strange. If I do this on my machine, I get the exact result: https://i.imgur.com/kufxInT.png Are you sure, that the `Weeks` file is “clean”? That is, no whitespace at line ends or other hidden characters in it?
Comment for this answer: Hi Boldewyn, I tried this comm -13 weeks <(seq 2001 2010) for the weeks file as
2002
2004
2005
2006
2010
and below is the O/P I got
2001
2003
2004
2005
2006
2007
2008
2009
which is partially correct I didn't want 2004 2005 and 2006 also to be displayed.
And thanks for the correction on the script I will work on it.
|
Title: Allowed to use multiple YouTube API keys for 1 project?
Tags: api;google-api;youtube-data-api
Question: I am quickly reaching quota limits while using YouTube Data API v3 for searches only using 1 API key.
I have applied for Quota increase but I hear it can take some time.
However I landed on the below article which states that a max of 300 APIs can be used for 1 project. Are my really allowed to use multiple YouTube Data API v3 keys and switch between them each time quota limit is reached??
https://cloud.google.com/docs/authentication/api-keys
I had been scrambling for solutions. I hope I read it well!
Here is another answer: Keys and credentials within a project share their quota. Creating additional api keys within the same project on google developer console is not going to get you additional quota.
As seen below all the credentials her will share the same quota.
You would need to create additional projects and create a key within each project.
All of these projects have their own credentials with their own quotas.
You should wait for an extension These days it shouldn't take more then a couple of weeks to hear back about a quota increase.
Comment for this answer: Ow interesting! So creating multiple projects API keys won't jeopardize my request for quota increase? As in is it considered as cheating and could make me get penalized for abusing the system (though not sure if it's considered as that)?
Comment for this answer: Yes I see your point. However I am speaking more in terms of legality. As in would I be violating the terms of use or other, if I am doing such workaround of using multiple keys for one website just to overcome the quota limitations? Wondering in case YouTube could ban my domain for such workaround, if ever they test my website.
Comment for this answer: As explained initially, Quota extension already applied for since a few days. Default quota is slowing down development, testing and reviews as it only allows for less than 100 search requests. Too bad there is no testing mode for the API with mock data. And too poor to go through the process of hiring a lawyer to answer this one question :)
Comment for this answer: Lets try this again. Creating multiple **PROJECTS** with one key in each will give you the 10k quota for each of the projects. Creating more then one key within the same project they will all use the same quota. Creating more projects wont effect your request for quota increase as you requested quota from a single project.
Comment for this answer: Stack Overflow cant answer legal questions, contact a lawyer. However I question why you would want to do such a thing in a production environment. Just apply for a quota extension. Its reasonably painless. That's what its there for. The default quota is only intended for development not for production google expects you to request an extension.
Comment for this answer: good luck let me know when you get an extension. I am keeping count of the average response time.
|
Title: How can I compare two columns against a combination of two columns in a table in Oracle?
Tags: sql;oracle
Question: I have something of a logical puzzle I can not figure out.
I have a table with two columns representing a PK. Prods and Prod_Colour
```TableA
Prods, Date_, Prod_Colour
One | null | Red
One | null | Blue
Two | 2012-06-08| Blue
Two | null | Yellow
Three| null | Green
Three| 2012-06-08| Red
```
The date repesents that those Prods are no longer available from that date however the date can be changed once it becomes available again.
I am capable of restricting rows based on date.
```SELECT a.*
FROM TABLEA a
WHERE Date_ > '2012-06-11' or Date_ IS NULL
```
but what I need to do is use this table in a subquery where both Prods and Prod_Colour are combined in the exclusion...
that's not a good explanation but basically in the example above Prods Three where Prod_Colour = 'Red' and Prods Two where Prod_Colour = 'Blue' would be excluded but Prods One would be included for both Prod_Colour where date was > than today or null.
As always I appreciate any advice or hints.
Thanks in advance.
To try and clarify further I have a query that selects from several different tables, among one of those tables I need to include prods and prod_Colour only where prods and Prod_Colour (combined as a unique identifier for each row) are available in TableA where date_ indicates they are available. The combinations won't change but the date_ can. I would use tDate to indicate today as the date to compare against.
```Select O.Prods, O.Prod_Colour /*each combination needs to match the combination in TableA */
FROM TableB
Where O.Prods + O.Prod_C in (Select A.Prods + A.Prod_Colour
FROM TABLE A WHERE Date_ IS NULL or Date_ > tDate)
```
something like that.
Here is the accepted answer: Based on your last edit, it seems like you are looking for this construct:
```SELECT *
FROM tableB
WHERE (prods, prod_colour) IN
(SELECT prods, prod_colour
FROM tablea a
WHERE date_ > tDate OR date_ is NULL);
```
Comment for this answer: This is what I was looking for, You've no idea how convoluted my attempts had become. I'll need to test it thoroughly but initial results look exactly like what I need.
Here is another answer: ```SELECT a.*
FROM TABLEA a
WHERE (Date_ > '2012-06-11' or Date_ IS NULL)
AND not (Prods = 'Two' and Prod_Colour = 'Blue')
AND not (Prods = 'Three' and Prod_Colour = 'Red')
```
Comment for this answer: Thanks for answering SQl, unfortunately I can not exclude through hardcoded values as the dates may change for different rows on different days depending on Prods availability. so tomorrow I may only need to exclude Prods = 'Two' and Prod_Colour = 'Blue'
Comment for this answer: I added some further clairification. I'm working on a larger easier query that shows what I'm trying to achieve and will include it above soon.
Comment for this answer: @dee, You will have to define your problem better, then. What is the general condition that you are filtering for? (All you have given us are examples, so all we can create is hard-coded code.)
Comment for this answer: You will need brackets around the OR condition, otherwise it will be incorrect.
Comment for this answer: @dee: so how do you know which products to exclude based on the date? Is there a validity date stored somewhere?
|
Title: Migrating CSS from Flex 3 to Flex 4
Tags: apache-flex;flex4;flex3;flex-spark;halo
Question: Is there a guide or document that deals specifically with migrating CSS and style attributes from Flex 3 to Flex 4? I have an application that I'm keeping on the 2006 namespace, but I'm having trouble with a couple concepts, like the halo only styles, the CSS namespacing conventions, and styling child controls.
Here is the accepted answer: Here is a good start, you'll need to scroll down to the CSS part.
|
Title: asp.net textbox.text and jquery.val()
Tags: jquery;asp.net
Question: I'm reading the contents of a an asp.net TextBox on a button click event in the codebehind of a webpage.
This works fine if I type something into the box I can read whats in there via TextBox.Text.
However, if I copy into the input textbox using jquery, setting the contents using val(), I can see the text appear in the box but when the click event fires and I try to read the contents of the textbox it is always blank. There's only every anything in there if I type it in myself.
The relevant bits of code are: -
The input box
```<asp:TextBox runat="server" ID="deliveryAddress3" CssClass="required radius disabled sugestedAddressTargetCity bcity2" />
```
Javascript
```var bfields = ['.baddress', '.bcity', '.bcountry', '.bpostcode'];
var dfields = ['.baddress2', '.bcity2', '.bcountry2', '.bpostcode2'];
for (var i in dfields) {
$(dfields[i]).prev('label').hide();
$(dfields[i]).val($(bfields[i]).val());
$(dfields[i]).attr('disabled', 'disabled');
$(dfields[i]).addClass('disabled');
$(dfields[i]).attr('disabled', 'disabled');
```
Code in button click method of codebehind: -
```customer.DelTown = deliveryAddress3.Text;
```
Whats going on here is that the customer can copy their address from one set of boxes to another. If they do this (by clicking a button) the ext shows up in the boxes but in the code behind is blank. However, if I type something in to those boxes it is available in the code behind.
Comment: dynamically added content from jQuery will not show in page source. I think this is what you are asking. Try to make your question more clear, and maybe add a jsFiddle, with example.
Comment: using attr() worked once I'd removed the adding of the disabled property too.
Comment: If you set the value attribute instead, does that work? Like this: `$("yourTextBox").attr("value", "newValue");`
Comment: It's going to be difficult for us to help without seeing any of your code.
Here is the accepted answer: I started a new ASP.net application and it works if you set the text box's ```value``` attribute using jQuery ```attr()```.
The script updates the value inside the textbox and the code behind is able to read it too.
Designer HTML (added the below to the default.aspx):
```<asp:TextBox runat="server" ID="MytextBox"></asp:TextBox>
<asp:Button runat="server" ID="MyButton" Text="Click Me"/>
```
Rendered HTML output:
```<input name="ctl00$MainContent$MytextBox" type="text" value="NewValue" id="MainContent_MytextBox">
<input type="submit" name="ctl00$MainContent$MyButton" value="Click Me" id="MainContent_MyButton">
```
Script:
```$("#MainContent_MytextBox").attr("value", "NewValue");
```
Code Behind from default.aspx.cs:
```protected void Page_Load(object sender, EventArgs e)
{
// Place Debugger here:
if (MytextBox.Text == "NewValue")
{
// hurray
}
}
```
|
Title: How to point to particular folder(by default) when i click on browse button of Html file tag
Tags: javascript;jquery;html;ajax
Question: I want my browse window pointing to particular folder(for Example D:/Test) by default when i click on browse button while doing file upload.Is there any way to set it using either jQuery or JavaScript?
```<input type="file" name="myfile" id="myfile"/>
```
Comment: To put it simply, no.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.