title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Best way to get first n characters of the string in Python | <p>I need to get first <strong>n</strong> characters of the string of <strong>x</strong> characters, where <code>n = x - len(endstring)</code> and <code>endstring</code> can have any number of characters from 0 to <strong>x</strong>.</p>
<p>Is there cleaner and better performance-wise way to do it in Python beside:</p>
<pre><code>string[:len(string) - len(endstring)]
</code></pre>
<p>?</p>
<p>Main point is that <code>len(string)</code> looks a little redundant, but to account for <code>endstring</code> of 0 characters it seemed as the "smoothest" solution?</p> | 1 |
syntax error, unexpected 'else' (T_ELSE) | <p>I was coding a basic Login system with a MySQL database, and I came across this problem. Any solution? This is also a live problem. If you go to OcelaRealms.com/proxy and try to login you get this error, "Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\xampp\htdocs\proxy\login.php on line 40"</p>
<p>This is my code:</p>
<pre><code><?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("192.168.1.19","root","xxx") or die ("Couldnt connect to MySQL database. Please contact Ocela at [email protected]");
mysql_select_db("proxy") or die ("Couldn't find database. Please contact Ocela at [email protected]");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
{
if ($username==$dbusername&&$password==$dbpassword)
{
echo "Login succesful. <a href='/proxy/index.php'>Click here to enter the Premium Proxy.</a>";
$_SESSION['username']=$dbusername;
}
else
echo "Incorrect password.";
}
else
die "That login doesnt exist. To get an account please contact Dylan.";
}
else
die ("Please enter a username and password.");
?>
</code></pre> | 1 |
opengl calculate normal for face | <p>I am attempting to load models exported from Blender into OpenGL. Particularly, I followed the source code from this <a href="https://tutorialsplay.com/opengl/2014/09/17/lesson-9-loading-wavefront-obj-3d-models/" rel="nofollow">tutorial</a> to help me get started. Because the loader is fairly simple, it only read in the vertex coordinates as well as face indices, ignoring the normal and tex.</p>
<p>It then calculates the normal for each face:</p>
<pre><code> float coord1[3] = { Faces_Triangles[triangle_index], Faces_Triangles[triangle_index+1],Faces_Triangles[triangle_index+2]};
float coord2[3] = {Faces_Triangles[triangle_index+3],Faces_Triangles[triangle_index+4],Faces_Triangles[triangle_index+5]};
float coord3[3] = {Faces_Triangles[triangle_index+6],Faces_Triangles[triangle_index+7],Faces_Triangles[triangle_index+8]};
float *norm = this->calculateNormal( coord1, coord2, coord3 );
float* Model_OBJ::calculateNormal( float *coord1, float *coord2, float *coord3 )
{
/* calculate Vector1 and Vector2 */
float va[3], vb[3], vr[3], val;
va[0] = coord1[0] - coord2[0];
va[1] = coord1[1] - coord2[1];
va[2] = coord1[2] - coord2[2];
vb[0] = coord1[0] - coord3[0];
vb[1] = coord1[1] - coord3[1];
vb[2] = coord1[2] - coord3[2];
/* cross product */
vr[0] = va[1] * vb[2] - vb[1] * va[2];
vr[1] = vb[0] * va[2] - va[0] * vb[2];
vr[2] = va[0] * vb[1] - vb[0] * va[1];
/* normalization factor */
val = sqrt( vr[0]*vr[0] + vr[1]*vr[1] + vr[2]*vr[2] );
float norm[3];
norm[0] = vr[0]/val;
norm[1] = vr[1]/val;
norm[2] = vr[2]/val;
return norm;
}
</code></pre>
<p>I have 2 questions. </p>
<ol>
<li>How do I know if the normal is facing inwards or outwards? Is there some ordering of the vertices in each row in the .obj file that gives indication how to calculate the normal?</li>
<li>In the initialization function, he uses <code>GL_SMOOTH</code>. Is this incorrect, since I need to provide normals for each vertex if using <code>GL_SMOOTH</code> instead of <code>GL_FLAT</code>? </li>
</ol> | 1 |
Show Files in a ListBox Delphi | <p>Im trying to create an mp3 player that later I may used as base to create a karaoke the only problem so far is that I want to show the *.mp3 files of a directory that the users select on a ListBox without having to add then manually 1 by 1 and that it only shows the song name not the current path. I have find some ways like using large functions or instead of a ListBox using a ComboBox but it isn't a easier way or transfer the files from the ComboBox to the Listbox?</p> | 1 |
Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 | <p>I'm trying to make a new C++ empty project in Visual Studio Community 2015. However, as soon as I just hit okay, it tells me One or more errors have occured, and general exception (Exception from HRESULT:0x80131500). </p>
<p>I've been trying to look online for other results, but none have really helped so far and I was wondering if anyone here knew how to fix it. </p>
<p>I've tried re installing it and even tried Windows Ultimate 2013 and I'd still be unable to make an empty project. </p> | 1 |
UIAlert in Swift that automatically disappears? | <p>I have the following code:</p>
<pre><code> /// Creates Alerts on screen for user.
func notifyUser(title: String, message: String) -> Void
{
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)
alert.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated: true,
completion: nil)
}
</code></pre>
<p>Which shows the following Alert:</p>
<p><a href="https://i.stack.imgur.com/NXpjg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NXpjg.png" alt="enter image description here"></a></p>
<p>I would prefer the Alert to appear for maybe 1-2 seconds and auto dismiss without having to click ok or dismiss. Is this possible?</p> | 1 |
H2 Console in Spring Boot Integration Test | <p>I'm working with Spring Boot <code>1.3.1.RELEASE</code>. I enabled the H2 web console by setting <code>spring.h2.console.enabled=true</code> in the <code>application.properties</code> file. If I launch my Spring Boot application I can access the H2 Web console via <code>http://localhost:8080/h2-console/</code>.</p>
<p>However, I am not able to access the console when I perform an integration test in debug mode, where I have set a breakpoint. Unfortunately, this is not working (site is not available). The integration test is configured as follows:</p>
<pre><code>@ActiveProfiles("local,unittest")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebAppConfiguration
@IntegrationTest
public class MyResourceTest {
</code></pre>
<p>What I have not considered?</p> | 1 |
RxJava - how to invoke subscriber on 4 click events in Android | <p>In android I have a text view defined like this: </p>
<pre><code><TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColorHighlight="#000000"
android:textIsSelectable="true" />
</code></pre>
<p>My goal is that after it is clicked 4 times, I want to start a new activity. I need to do this with RXJava; this is a requirement. Or <code>rxAndroid</code>, <code>rxBinding</code>, etc. </p>
<p>My activity looks like this:</p>
<pre><code>public class MainActivity extends Activity implements onClickListener {
TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.text1);
tv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.text1){
}
}
}
</code></pre>
<p>UPDATE:
but this is just the standard way of doing it. There must be a way to do with with reactive rxJava API. </p>
<p>So instead of using a <code>onClicklistener</code> with <code>rxBinding</code> I read we can do this:</p>
<pre><code>RxView.clicks(tv).flatMap(tv -> {
// another observable which can throw onError.
return Observable.error(null);
}).subscribe(object -> {
Log.d("CLICK", "textview clicked", start activity);
}, error -> {
Log.d("CLICK", "ERROR");
});
</code></pre>
<p>Can I somehow use a command in <code>rxBinding</code> to make it execute only after 4 clicks? I'm not looking to store a static variable, or use a anonymous class and store a member variable for count in it. There should be an observable method for this. </p> | 1 |
Microservice solution structure in .NET applications | <p>I'm developing an application using the microservices approach, and I'm having a hard time defining how those microservices will look like on a visual studio project.</p>
<p>My initial approach is to create one visual studio solution for every microservice. Every solution will have the following projects:</p>
<ul>
<li>Host</li>
<li>Business API</li>
<li>Data Access Layer</li>
<li>Model</li>
<li>Interfaces (for DI) </li>
<li>Data Access Mock</li>
<li>Tests for Business API</li>
</ul>
<p>So there are 7 projects per microservice. Somehow it feels a lot of projects being reimplemented for every solution.</p>
<p>Is this approach correct? Has anybody built microservices with .net? How does your projects configuration look like?</p> | 1 |
Change the shape of floating action button | <p>I want to add a floating action button into my layout. would like to ask how to customized and change the shape of floating action button to your own icon?</p> | 1 |
Verilog Subtraction and addition | <p>I am attempting to program an addition and subtraction program in Verilog. Problem is Implementation and testing in Verilog of a module that performs Addition or Subtraction, then a Mux chooses between letting go through the result of one or the other, and then Decode the selected result from binary into a 7-segment Display format. Verilog Module will have 3 inputs: two 4-bit inputs named A and B, and a select input S. Your circuit should add the two numbers and should also subtract B from A (it is as simple as having A-B in your code). Depending on the value of S (i.e. whether it’s a one or a zero), you should let either the result of the addition or the result of the subtraction through. </p>
<p>This is the code that I have:
module AddOrSubtractThenSelectAndDecodeInto7SegmentsDisplay(A,B,S,Result,Overflow,Display);</p>
<pre><code>input [3:0] A;
input [3:0] B;
input [1:0] S;
output reg [3:0] Result;
output reg Overflow;
output reg [6:0] Display;
wire [3:0] A;
wire [3:0] B;
wire [1:0] S;
always @(A,B) begin
if (S == 0'b0)
{Overflow, Result} = A - B;
else if (S == 1'b1)
{Overflow, Result} = A + B;
end
always @(Overflow,Result) begin
case (Result)
4'b0000: Display = 7'b1111110;//0
4'b0001: Display = 7'b0110000;//1
4'b0010: Display = 7'b1101101;//2
4'b0011: Display = 7'b1111001;//3
4'b0100: Display = 7'b0110011;//4
4'b0101: Display = 7'b1011011;//5
4'b0110: Display = 7'b1011111;//6
4'b0111: Display = 7'b1110000;//7
4'b1000: Display = 7'b1111111;//8
4'b1001: Display = 7'b1111011;//9
4'b1010: Display = 7'b1110111;//A
4'b1011: Display = 7'b0011111;//B
4'b1100: Display = 7'b1001110;//C
4'b1101: Display = 7'b0111101;//D
4'b1110: Display = 7'b1001111;//E
4'b1111: Display = 7'b1000111;//F
default: Display = 7'bx;
endcase
if (Overflow == 1)begin
Result = 4'bx;
Display = 7'b0011101;
end
end
endmodule
</code></pre>
<p>When I run the instructors test bench all the lines are green except for display. It says Display[6:0] xxxxxxx and followed by red lines. I have spent 2 days looking at this trying to fix it. Any help please?</p> | 1 |
Oozie hourly coordinator timing out on future actions | <p>At the 5 minute mark of every hour, I have data from the past hour loaded into hdfs. I thought I could setup a coordinator job to run at 10 minute mark of every hour to process this data while doing a check if the directory for that hour exists. What ends up happening is the coordinator will perform normal on past hour's data at time of submission, continue working fine for the next 2 hours and then future actions will go from 'waiting' to 'timedout'. My guess is that there is a default max limit for how long an action can stay in 'waiting'. It seems a bit counterintuitive for the time out limit to apply to all actions at an absolute future time. Anyway, here's a sample of the coordinator.xml. I'm looking for any suggestions on either how to design it in a way that makes more sense or on how to raise the default timeout.</p>
<pre><code><datasets>
<dataset name="hourly_cl" frequency="${coord:hours(1)}" initial-instance="2016-02-08T11:10Z" timezone="PST">
<uri-template>hdfs://user/tzl/warehouse/incoming/logmessages.log.${YEAR}${MONTH}${DAY}/${HOUR}/</uri-template>
<done-flag></done-flag>
</dataset>
<dataset name="hourly_cl_out" frequency="${coord:hours(1)}" initial-instance="2016-02-05T11:10Z" timezone="PST">
<uri-template>hdfs://user/tzl/warehouse/output/logmessages.log.${YEAR}${MONTH}${DAY}/${HOUR}/</uri-template>
<done-flag></done-flag>
</dataset>
</datasets>
<input-events>
<data-in name="coordInput1" dataset="hourly_cl">
<instance>${coord:current(-1)}</instance>
</data-in>
</input-events>
<output-events>
<data-out name="clout" dataset="hourly_cl_out">
<instance>${coord:current(-1)}</instance>
</data-out>
</output-events>
<action>
<workflow>
<app-path>${appPath}</app-path>
<configuration>
<property>
<name>inputPath</name>
<value>${coord:dataIn('coordInput1')}</value>
</property>
<property>
<name>outputPath</name>
<value>${coord:dataOut('clout')}</value>
</property>
</configuration>
</workflow>
</action>
</code></pre>
<p>Also noticed while looking at logs that oozie checks EVERY MINUTE for each data directory. In other words at 18:01 it'll check these exists
logmessages.log.20160208/18</p>
<p>logmessages.log.20160208/19</p>
<p>logmessages.log.20160208/20</p>
<p>logmessages.log.20160208/21</p>
<p>...</p>
<p>and at 18:02 again it'll check
logmessages.log.20160208/18</p>
<p>logmessages.log.20160208/19</p>
<p>logmessages.log.20160208/20</p>
<p>logmessages.log.20160208/21</p>
<p>...</p>
<p>This is probably taking up unnecessary cpu cycles. I assumed by setting the frequency to an hour, it would be smart enough to not waste time checking for future datasets when I've defined the instance to be past hour's data: current(-1)</p> | 1 |
How do I add a font to the Divi Wordpress theme? | <p>How do I add a font to the Divi wordPress theme? The font is from fonts.com and is called Vectora. Should I use a plugin or custom code? The site I would like to add it to is stewards.degrootdesign.com</p> | 1 |
C# Parse elements from text file | <p>I've got a text file with the following content:</p>
<pre><code>139862,2 - 455452,6 - 13:24:53
139860,8 - 455452,2 - 13:25:13
139859,3 - 455452,2 - 13:25:33
</code></pre>
<p>As you can see there are 3 elements per line of the text file. I'd like to be able to save these as variables.</p>
<p>It's possible for me to put prefixes per variable that I'd like to be able to save, so that the text will look like: </p>
<pre><code>X:139862,2 - Y:455452,6 - D:13:24:53
X:139860,8 - Y:455452,2 - D:13:25:13
X:139859,3 - Y:455452,2 - D:13:25:33
</code></pre>
<p>What I've already got is the coding to read the text file line for line, which looks like: </p>
<pre><code> string line;
System.IO.StreamReader file = new System.IO.StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
// Here I'd like to parse the text file and add them to a list for example
}
</code></pre>
<p><strong>Thanks in advance!</strong></p> | 1 |
Python TypeError: 'list' object cannot be interpreted as an integer | <p>I'm new at this so bear with me, I keep getting the error <code>TypeError: 'list' object cannot be interpreted as an integer</code>. I'm not sure how to fix this error. Any help would be appreciated.</p>
<pre><code>import turtle
wn = turtle.Screen()
bob = turtle.Turtle()
List = ["red", "orange", "yellow", "green", "blue", "violet"]
List2 = [8, 7, 6, 5, 4, 3]
C = (-1)
S = (9)
bob.speed(2)
bob.penup()
bob.left(90)
bob.forward(70)
bob.right(90)
bob.pendown()
def drawAnyShape(Side):
for i in range(0,Side):
bob.forward(50)
bob.right(360/Side)
for i in range(3,9):
S = (S-1)
C = (C+1)
bob.begin_fill()
bob.color(List[C])
drawAnyShape([S])
bob.end_fill()
wn.mainloop()
</code></pre> | 1 |
MySQL: java.sql.BatchUpdateException: Duplicate entry '242-243' for key 'PRIMARY' | <p>I have a problem with MySQL, at 4.00 PM my webApp i think cannot reach MySQL because of this errors: </p>
<pre><code> com.webratio.rtx.RTXException: Unable to perform process transition 'startProcess[startActivityTypeOid:2][parameters:gruppoOid=1, idCliente=2613, scontoOcc={}, barcode=10AA1107]'
at com.webratio.units.bpm.core.ProcessController.handleProcessTransition(ProcessController.java:137)
at com.webratio.units.bpm.services.ProcessUnitService.createUnitBean(ProcessUnitService.java:151)
at com.webratio.units.bpm.services.AbstractBPUnitService.getUnitBean(AbstractBPUnitService.java:144)
at com.webratio.units.bpm.services.AbstractBPUnitService.execute(AbstractBPUnitService.java:107)
at com.webratio.struts.actions.OperationAction.executeOperation(OperationAction.java:393)
at com.webratio.struts.actions.OperationAction.doExecute(OperationAction.java:249)
at com.webratio.struts.actions.OperationAction.execute(OperationAction.java:74)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at com.webratio.struts.servlets.WRActionServlet.process(WRActionServlet.java:155)
at com.webratio.struts.servlets.WRActionServlet.doPost(WRActionServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:719)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:465)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:390)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:317)
at com.webratio.struts.chain.commands.PerformForward2.handleAsForward(PerformForward2.java:101)
at com.webratio.struts.chain.commands.PerformForward2.perform(PerformForward2.java:83)
at org.apache.struts.chain.commands.AbstractPerformForward.execute(AbstractPerformForward.java:54)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at com.webratio.struts.servlets.WRActionServlet.process(WRActionServlet.java:155)
at com.webratio.struts.servlets.WRActionServlet.doPost(WRActionServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.webratio.struts.filters.StaticResourceFilter.doFilter(StaticResourceFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: com.webratio.rtx.RTXException: Unable to start process (startEventOid:2)
at com.webratio.units.bpm.core.ProcessController$StartProcessCommand.computeOperations(ProcessController.java:557)
at com.webratio.units.bpm.core.ProcessCommand.execute(ProcessCommand.java:184)
at com.webratio.units.bpm.core.ProcessController.handleProcessTransition(ProcessController.java:107)
... 64 more
Caused by: java.lang.reflect.UndeclaredThrowableException
at com.webratio.units.bpm.core.$Proxy3.flush(Unknown Source)
at com.webratio.units.bpm.core.handlers.ProcessHandler.connectActivityInstances(ProcessHandler.java:1007)
at com.webratio.units.bpm.core.handlers.ProcessHandler.normalFlow(ProcessHandler.java:256)
at com.webratio.units.bpm.core.handlers.ProcessHandler.normalFlow(ProcessHandler.java:122)
at com.webratio.units.bpm.core.handlers.ProcessHandler.startProcess(ProcessHandler.java:109)
at com.webratio.units.bpm.core.ProcessController$StartProcessCommand.computeOperations(ProcessController.java:550)
... 66 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor234.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.webratio.units.bpm.core.TXSession$SessionInvocationHandler.invoke(TXSession.java:206)
... 72 more
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:262)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:181)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
... 76 more
Caused by: java.sql.BatchUpdateException: Duplicate entry '242-243' for key 'PRIMARY'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2020)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 81 more
</code></pre>
<p>I have no idea what it is because it is never happened to me.
I am stuck at this, so I thank you in advance for some advices.</p> | 1 |
Scala find element in nested List | <p>Consider the following example:</p>
<pre><code>case class Person(name: String, age: Int)
case class Family(surname: String, members: List[Person])
val families = List(
Family("Jones",
List(Person("Indiana", 50), Person("Molly", 20))),
Family("Black",
List(Person("Jack", 55), Person("Derek", 12))))
</code></pre>
<p>I want to write a function that finds a person with a certain name in a <code>List[Family]</code> object. This is my current solution:</p>
<pre><code>def find(name: String, families: List[Family]): Option[Person] = {
families.find(f => f.members.exists(m => m.name == name)).map(f => f.members.find(m => m.name == name).get)
}
</code></pre>
<p>Is there a more efficient and elegant (and functional) way to achieve this?</p> | 1 |
Return value of function | <p>Every function call is executed on the stack and this function is deallocated from the stack memory after the function exits.</p>
<p>Suppose a variable "return_value" is declared as non-static(normal unsigned int) in a function foo().
At the end of the function foo(), this value is returned as </p>
<pre><code>return return_value
</code></pre>
<p>This value should have been deallocated from the stack memory.
Therefore,how does the main function that is receiving this return value get the correct value returned by foo()?</p> | 1 |
VB.NET - Focus first row and first cell of DataGridView | <p>Good morning,</p>
<p>I have a form with two textbox and a DataGridView.
I'm used to fill my controls then i press Tab to switch to the next one.</p>
<p>However, when i switch from my textbox to my DataGridView, the selected cell is the second one of the first row => DTG.Rows(0).Cells(1).
I need to enter on the DTG.Rows(0).Cells(0) to fill my DTG without using my mouse.</p>
<p>I tried the code bellow :</p>
<pre><code>Public Sub txtBoxTest_Leave() Handles txtBoxTest.Leave
DTG.Focus()
DTG.CurrentCell = DTG(0, 0)
DTG.BeginEdit(True)
End Sub
</code></pre>
<p>The cell seems to be selected, but it is not in editmode.</p>
<p>Modify the edit mode to EditOnEnter does not resolve my problem :</p>
<pre><code>DTG.EditMode = DataGridViewEditMode.EditOnEnter
</code></pre>
<p>Can someone help me please ?</p>
<p><strong>EDIT :</strong>
My datagridview cells are in <code>ReadOnly = False</code>.</p> | 1 |
How to build an Entity Framework model from a PostgreSQL schema? | <p>(This question follows <a href="http://www.npgsql.org/doc/ddex.html" rel="nofollow">an excellent post on using Npgsql</a>).</p>
<p>I have a PostgreSQL (9.5.0) database with two schemas: public and nova. I then used NuGet console:</p>
<pre><code>Install-Package EntityFramework6.Npgsql -Version 3.0.5
</code></pre>
<p>Now I add the following element to the <code>app.config</code> file: </p>
<pre><code><system.data>
<DbProviderFactories>
<remove invariant="Npgsql"/>
<add name="Npgsql Data Provider"
invariant="Npgsql"
description=".Net Data Provider for PostgreSQL"
type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"
support="FF" />
</DbProviderFactories>
</system.data>
</code></pre>
<p>Then I added a new "ADO.NET Entity Data Model" to my project.</p>
<p>The following connection properties were filled in:</p>
<pre><code>Database: chaos
Host: localhost
Password: psw
Port: 5432
Search Path: nova
Username: postgres
</code></pre>
<p>The connection is then tested and everything works.</p>
<p>The Entity Framework is then built with database first. The <code>.edmx</code> file is built correctly and the VS designer is happy.</p>
<p>The problem is the <code>.edmx</code> file is built from all the tables in the database. That is, both the public and nova schema's tables are in the <code>.edmx</code> file. </p>
<p>In addition to specifying the search path in the connection properties, I have tried the following on the database--but these do not change both schemas being added to the <code>.edmx</code> file:</p>
<ul>
<li>ALTER DATABASE chaos SET search_path TO nova; </li>
<li>ALTER USER postgres SET search_path to nova; </li>
<li>ALTER SCHEMA public RENAME TO public_old;</li>
</ul>
<p>Is there any way to build the Entity Framework with only the one schema, <code>Nova</code>?</p>
<p>My components:</p>
<ul>
<li>Windows 10 Professional</li>
<li>Entity Framework 6.0.0</li>
<li>Npgsql 3.0.5</li>
<li>PostgreSQL 9.5.0</li>
<li>Visual Studio 2015</li>
</ul>
<p>TIA</p> | 1 |
How to static_assert the size of a std::array member | <p>I would like to be explicit about array size restrictions on a member variable, to stop others from accidentally making silly changes. The following naive attempt will not compile:</p>
<pre><code>struct Foo
{
std::array< int, 1024 > some_array;
static_assert( (some_array.size() % 256) == 0, "Size must be multiple of 256" );
//^ (clang) error: invalid use of non-static data member 'some_array'
};
</code></pre>
<p>Even though <code>std::array::size</code> is a <em>constexpr</em>, I can't directly use <code>static_assert</code> like that because neither the function nor my member variable is static.</p>
<p>The solution I came up with is to use <code>decltype</code> (since I don't want to typedef the array) as follows:</p>
<pre><code>static_assert( (decltype(some_array)().size() % 256) == 0, "Size must be multiple of 256" );
</code></pre>
<p>This looks like it's default-constructing an <em>rvalue</em>, which I didn't think is a <em>constexpr</em>.</p>
<p>Why does this work?</p>
<p>Is there a cleaner way to achieve the static assertion?</p> | 1 |
set max display width for a column in WPF datagrid | <p>I have a datagrid in WPF that generate the columns automatically. some columns have a width more than whole screen, I want to check the width and if it is more than 500 then set it to 500 but if it is less than 500 keep the current width. </p>
<pre><code> <DataGrid x:Name="dgLM" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding}" HorizontalAlignment="Stretch"
Margin="5" VerticalAlignment="Stretch" IsReadOnly="True" CanUserAddRows="False" AutoGenerateColumns="True" CanUserDeleteRows="False"
LoadingRow="dg_LoadingRow" AlternatingRowBackground="#FFDAD5D5"
AutoGeneratingColumn="dgMain_AutoGeneratingColumn" >
<!--<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DarkGray"/>
</DataGrid.Resources>-->
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="DarkGray" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
</code></pre>
<p>and the code is:</p>
<pre><code> private void dgMain_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(System.DateTime))
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy HH:mm:ss";
//e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
if (e.Column.Width > 500)
{
e.Column.Width = 500;
}
}
</code></pre>
<p>appreciate any help!</p> | 1 |
Post build event depending on configuration name in new ASP.NET 5 project | <p>I'm writing a unified project for 3 smart TVs. I have also 3 configurations created in <code>Visual Studio</code>. Now I want to execute some <code>CLI</code> scripts depending on selected configuration.</p>
<p>The problem is in new <code>ASP.NET 5</code> project I don't have an editor for post build events.</p>
<p>I know I have to do this in <code>project.json</code>. What I found is:</p>
<pre><code> "scripts": {
"postbuild": ""
}
</code></pre>
<p>But using this one I can't create different <code>CLI</code> scripts for different configurations.</p>
<p>I found also:</p>
<pre><code> "configurations": {
},
</code></pre>
<p>And I guess this is probably what I want, but... How to use it? Intellisense has no power here and also I wasn't lucky searching the Web...</p>
<p><strong>[edit]</strong></p>
<p>Maybe I should try with <code>.xproj</code>?</p> | 1 |
Pyodbc - print first 10 rows (python) | <p>I'm trying to print the first 10 rows using pyodbc. I know how to get the first record by using the following:</p>
<pre><code>row = cursor.fetchall()
</code></pre>
<p>I tried changing this to:</p>
<pre><code>row = cursor.fetchten()
</code></pre>
<p>but this didn't work. Is there anything else I can do?? </p> | 1 |
Add date from JXDatePicker into SQL Database in Netbeans | <p>I would like to add a date value from JXDatePicker into my SQL database, however I'm getting this error when running it: </p>
<p>java.sql.sqldataexception: the syntax of the string representation of a datetime value is incorrect</p>
<p>This is my code:</p>
<pre><code>try {
String url = "jdbc:derby://localhost:1527/Members";
String username = "admin1";
String password = "admin1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES('"+txtMemberID.getText()+"', '"+txtName.getText()+"', "
+ "'"+txtContact.getText()+"', '"+txtEmail.getText()+"', "
+ "'"+comboDate.getDate()+"', '"+comboTime.getSelectedItem()+"')";
stmt.execute(query);
JOptionPane.showMessageDialog(null, "Booking created");
txtMemberID.setText(null);
txtName.setText(null);
txtContact.setText(null);
txtEmail.setText(null);
comboDate.setDate(null);
comboTime.setSelectedItem("00");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
</code></pre>
<p>The datatype specified for the Date attribute in my database is Date.</p>
<p>Thank you.</p> | 1 |
PHP - Uploading multiple files with Javascript and PHP | <p>its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:</p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
</code></pre>
<p>So this is my HTML Code and following up my upload.php:</p>
<pre><code><?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
</code></pre>
<p>My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.</p> | 1 |
Avoid deepcopy due to performance | <p>I have a list with another 3 lists in it. I need to do some operations on the lists, as i have like 180.000 of those the step of deepcopying already takes 2,5s to copy the lists once.
The overall time including operations takes 80s out of 220s compution time.</p>
<pre><code>s = [[1,2,3],
[4,5,6],
[7,8,9]]
s1 = copy.deepcopy(s)
s1[0][0] = s[1][1]
s1[1][1] = s[0][0]
</code></pre>
<p>The shown operation needs to be repeated like a million of times. So deepcopy makes me face a performance bottleneck.</p>
<p>Is there a more performant way or a different approach to "unreference" the list <code>s</code>?</p> | 1 |
How to loop multidimensional map in javascript | <p>I am unable to loop through the multidimensional map, I have a sample map below,
here known values are its key. i.e 'one', 'two'.. Now how can I find out the inner values of it. I would like to get <strong>a,b</strong> from <strong>one</strong> and <strong>c,d</strong> from <strong>two</strong></p>
<pre><code>{
one: {
a: {
id: '6',
name: 'abc',
age: '30',
place: 'xyz'
},
b: {
id: '7',
name: 'def',
age: '31',
place: 'xyx'
},
},
two: {
c: {
id: '8',
name: 'ghi',
age: '32',
place: 'xxz'
},
d: {
id: '9',
name: 'ghi',
age: '33',
place: 'yyx'
}
}
}
</code></pre>
<p>It would be really helpful if I get any solution for this..Thanks in advance</p> | 1 |
Configuring Oracle OCI8 for windows 64 bit | <p>I have been facing problems configuring oracle oci8 for windows</p>
<p>I'm using windows 7 64 bit, xampp v3.2.2, php 5.6.15 and oracle g11 express </p>
<p>I have tried the following steps but I can't find the oci package when running phpinfo:</p>
<ol>
<li><p>I downloaded both Instant Client Package - Basic and Instant Client Package - ODBC Version 12.1.0.2.0 </p></li>
<li><p>unzip the files into one file in c to be at the following path (<code>C:\instantclient_11_2</code>)</p></li>
<li><p>add the path to environment variable (path) for oracle product (<code>C:\instantclient_11_2;C:\oraclexe\app\oracle\product\11.2.0\server\bin;</code>)</p></li>
<li><p>restart my computer</p></li>
<li><p>run the script (<code>odbc_install</code>)</p>
<p>6- removed ; infront of the extension=php_oci8_11g.dll in php.ini</p></li>
</ol>
<p>but It didn't work , can anyone tell me why?</p> | 1 |
How to force update custom user claims? | <p>I've got a custom claim added to my ApplicationUser class as follows:</p>
<pre><code>public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
if(Theme != null)
userIdentity.AddClaim(new Claim("ThemeBundle", Theme.Bundle));
return userIdentity;
}
public int? ThemeId { get; set; }
[ForeignKey("ThemeId")]
public virtual Theme Theme { get; set; }
}
</code></pre>
<p>I extended Identity like this:</p>
<pre><code>public static class IdentityExtensions
{
public static string GetThemeBundle(this IIdentity identity)
{
var claim = ((ClaimsIdentity) identity).FindFirst("ThemeBundle");
// Test for null to avoid issues during testing
return (claim != null) ? claim.Value : string.Empty;
}
}
</code></pre>
<p>I update the model behind the claim from the following Action Method:</p>
<pre><code> public ActionResult ChangeTheme(int id)
{
var theme = _db.Themes.Find(id);
if (theme == null)
return HttpNotFound();
var userId = User.Identity.GetUserId();
var user = _db.Users.Find(userId);
user.Theme = theme;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
</code></pre>
<p>I access it in a view (or elsewhere) like this:</p>
<pre><code>User.Identity.GetThemeBundle()
</code></pre>
<p>When the user updates their "Theme" property with the "ChangeTheme" action, nothing happens until they log off and log back in.</p>
<p>I've spent all day mulling over more than the following QA's with no good result:</p>
<p><a href="https://stackoverflow.com/questions/21960511/update-user-claim-not-taking-effect-why">Update User Claim not Taking Effect. Why?</a></p>
<p><a href="https://stackoverflow.com/questions/20495249/mvc-5-addtorole-requires-logout-before-it-works">MVC 5 AddToRole requires logout before it works?</a></p>
<p>And thanks to @Brendan Green: <a href="https://stackoverflow.com/questions/24570872/asp-net-identity-forcing-a-re-login-with-security-stamp">ASP.NET Identity - Forcing a re-login with security stamp</a></p>
<p>So far the best I've got is that the page will refresh and the claim returns an empty string instead of the desired result, OR I redirect the user to the login screen. At least those are less ambiguous than nothing happening.</p>
<p>How on earth can I get the claim to update globally as soon as the user changes their "Theme" property? I'd settle for a good way to fully log the user off and back on if needed. Using the AuthenticationManager.Signout and .Signin methods doesn't quite do the trick.</p> | 1 |
Long Range RFiD Reading | <p>I'm trying to set up a practical DIY method of unlocking a garage or front door by coming into the range of a reader; even if that means standing in a specific line of sight. Essentially once I reach the garage, the ID is read and raises </p>
<p>I'd prefer to have passive ID's, but the reader itself would be able to have a fixed power source that doesn't need to be changed. </p>
<p>I've done a lot of searching on google and there <em>are</em> RFiD scanners that read cars to open tolls booths, but those are commercial grade products and much more expensive than anything I'm trying to make. Should I continue looking into RFiD's, or is there a more efficient method of approaching this?</p>
<p>Also, if my tags are active, and powerful enough, would that compensate for a low frequency reader?</p> | 1 |
Limit function in Kotlin | <p>There is a stream method <code>limit</code> in Java 8:</p>
<pre><code>package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class LimitDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("AA","BB","CC","DD","EE");
list.stream().limit(3).forEach(s->System.out.println(s));
}
}
</code></pre>
<p>output:</p>
<pre><code>AA
BB
CC
</code></pre>
<p>What is the name of analog in Kotlin, or how to do it better by another way?</p> | 1 |
Define Azure AD B2C vs B2B uses and differences | <p>Could you please define cloud based authentication services Azure AD B2C and B2B with it's uses and their differences if any. Please provide list of web resources if you can.</p> | 1 |
Python-Tkinter-Basic login form | <p>I am trying to make a basic login form. I'm having trouble with passing values to my function which checks the username and password.</p>
<p>Here is my code:</p>
<pre><code>from tkinter import *
class Application(Frame):
def __init__(self,master):
super(Application, self).__init__(master)#Set __init__ to the master class
self.grid()
self.create_main()#Creates function
def create_main(self):
print("testing")
self.title = Label(self, text=" Stuck In The Circle ")#TITLE
self.title.grid(row=0, column=2)
self.user_entry_label = Label(self, text="Username: ")#USERNAME LABEL
self.user_entry_label.grid(row=1, column=1)
self.user_entry = Entry(self) #USERNAME ENTRY BOX
self.user_entry.grid(row=1, column=2)
self.pass_entry_label = Label(self, text="Password: ")#PASSWORD LABEL
self.pass_entry_label.grid(row=2, column=1)
self.pass_entry = Entry(self) #PASSWORD ENTRY BOX
self.pass_entry.grid(row=2, column=2)
self.sign_in_butt = Button(self, text="Sign In",command = self.logging_in)#SIGN IN BUTTON
self.sign_in_butt.grid(row=5, column=2)
def logging_in(self):
print("hi")
user_get = user_entry.get()#Retrieve Username
pass_get = pass_entry.get()#Retrieve Password
if user_get == 'sam':
if pass_get == '123':
print("Welcome!")
#Main
root = Tk()
root.title("Stuck in the Circle")
root.geometry("400x100")
app = Application(root)#The frame is inside the widgit
root.mainloop()#Keeps the window open/running
</code></pre>
<p>Here is my error:</p>
<blockquote>
<p>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Sam\AppData\Local\Programs\Python\Python35-32\lib\tkinter_init_.py", line 1549, in call return self.func(*args) File "C:/Users/Sam/Desktop/Computer Science/Python/Python- Modules/Tkinter/Tkinter Projects/Login Form GUI.py", line 31, in logging_in user_get = user_entry.get()#Retrieve Username NameError: name 'user_entry' is not defined</p>
</blockquote> | 1 |
Python class can't find attribute | <p>Basically, I want to run the connect function but I keep getting the CMD error message 'class StraussBot has no attribute 'connectSock' but I can obviously see it does. I've tried searching on here and I can't find any resolutions to this issue. SO it will be greatly appreciated if you could help me find why this isn't finding the 'connectSock' function.</p>
<p>Code:</p>
<pre><code>import socket
from config import HOST, PORT, CHANNEL
# User Info
USER = "straussbot" # The bots username
PASS = "oauth:sj175lp884ji5c9las089sm9vvaklf" # The auth code
class StraussBot:
def __init__(self):
self.Ssock = socket.socket()
def connectSock(self):
self.Ssock.connect((HOST, PORT))
self.Ssock.send(str("Pass " + PASS + "\r\n").encode('UTF-8'))
self.Ssock.send(str("NICK " + USER + "\r\n").encode('UTF-8'))
self.Ssock.send(str("JOIN " + CHANNEL + "\r\n").encode('UTF-8'))
if __name__ == "__main__":
print "Starting the bot..."
while True:
straussbot = StraussBot
try:
straussbot.connectSock()
except Exception as e:
print e
</code></pre> | 1 |
Inject custom service into Behat context | <p>Is it possible to build and inject my own, custom services into a Behat Context class?</p>
<p>I'm integrating Behat with Symfony2, and I can inject Symfony's services into my contexts like so:</p>
<pre><code>contexts:
- Meeebu\MyBundle\Features\Security\Context\SecurityContext:
session: '@session'
</code></pre>
<p>provided that the <code>Behat\Symfony2Extension</code> is registered.</p>
<p>I'm also using <a href="http://behat-page-object-extension.readthedocs.org/en/latest/" rel="nofollow">Behat Page Object Extension</a> that injects <code>Page</code> objects into Context constructor directly, so my constructo currently looks like this:</p>
<p><code>public function __construct(Session $session, Homepage $homepage, WelcomeAdmin $welcomeAdminPage)</code></p>
<p>Now, I'd like to use my owe custom services in the Context class. </p>
<p>How can I create, register, and inject them in Behat?</p> | 1 |
Why is LuaJIT's memory limited to 1-2 GB on 64-bit platforms? | <p>On 64-bit platforms, LuaJIT allows only up to 1-2GB of data (not counting objects allocated with <code>malloc</code>). Where does this limitation come from, and why is this even less than on 32-bit platforms?</p> | 1 |
nginx 502 bad gateway for long running request | <p>I have a request that takes "a few mins" to process. This works fine when I access it via Django's built in development server. </p>
<p>However when I access it from nginx/uwsgi I get 502 bad gateway.</p>
<p>I have tried increasing the timeout/keepalive settings in nginx.conf but to no effect.</p>
<p>Here is the relevant conf setting:-</p>
<pre><code>#keepalive_timeout 0;
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;
</code></pre>
<p>And nginx debug log errors:-</p>
<pre><code>2016/02/03 17:35:33 [notice] 12654#0: nginx/1.4.2
2016/02/03 17:35:33 [notice] 12654#0: built by gcc 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC)
2016/02/03 17:35:33 [notice] 12654#0: OS: Linux 2.6.32-358.14.1.el6.x86_64
2016/02/03 17:35:33 [notice] 12654#0: getrlimit(RLIMIT_NOFILE): 1024:4096
2016/02/03 17:35:33 [notice] 12655#0: start worker processes
2016/02/03 17:35:33 [notice] 12655#0: start worker process 12657
2016/02/03 17:35:33 [notice] 12655#0: start worker process 12658
2016/02/03 17:35:33 [notice] 12655#0: start worker process 12659
2016/02/03 17:35:33 [notice] 12655#0: start worker process 12660
2016/02/03 17:36:36 [error] 12658#0: *12 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: xxxxxxxx.in, request: "GET /long/url/with?request=params HTTP/1.1", upstream: "uwsgi://10.176.6.247:8001", host: "xxx.xxx.xxx.xxx"
</code></pre> | 1 |
SELECT, UPDATE, DELETE with one SQL query? | <p>I have a tiny statement which decrements a value:</p>
<pre><code>UPDATE cart_items SET quantity = quantity - 1
WHERE cart_id = {$cart_id} AND id = {$cart_item_id}
</code></pre>
<p>But would it be possible for SQL to DELETE the row if that value becomes 0 after the decrement? If so, I then want to recount the number of rows matching that cart:</p>
<pre><code>SELECT FROM cart_items WHERE cart_id = {$cart_id}
</code></pre>
<p>And if the number of rows is zero, I want to delete that record from another table, like so:</p>
<pre><code>DELETE FROM cart WHERE id = {$cart_id}
</code></pre>
<p>At the moment it seems like a need several queries to do this, but could it all be done in a single SQL statement?</p> | 1 |
How to store enum into Mutable Array in swift | <p>How can I store an enum in a mutable array in Swift please?</p>
<p>Below it is discussed for Objective-C and obviously it is working fine.
<a href="https://stackoverflow.com/questions/2487587/how-to-store-enum-values-in-a-nsmutablearray">How to store enum values in a NSMutableArray</a></p>
<p>It is stored for int value using <code>array.addObject(0)</code>;</p> | 1 |
Toolbar title not showing | <p>I am new to Android and creating a custom toolbar I have set a textview and some images in my toolbar but it is not visible.`Below is the code</p>
<p><img src="https://i.stack.imgur.com/BSPp2.png" alt=" and image of my emulator"></p></p>
<p>I have used this link for tutorial
<a href="http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/" rel="nofollow noreferrer">http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/</a></p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="130dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="?attr/colorPrimary">
<!--app:layout_scrollFlags="scroll|enterAlways"-->
<!--app:popupTheme="@style/ThemeOverlay.AppCompat.Light">-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ToolBarTitle"
android:layout_gravity="bottom"
android:layout_marginBottom="35dp"
android:id="@+id/toolbar_title"
android:textColor="#FFFFFF"
android:textSize="17.3sp"
android:layout_marginLeft="127dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_gravity="bottom"
android:layout_marginBottom="50dp"
android:background="@drawable/icn_dropdown" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="45dp"
android:layout_marginLeft="110dp"
android:background="@drawable/icn_options"/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f5f5f5"
app:theme="@style/TabTheme"
app:tabIndicatorColor="@color/colorPrimary"
app:tabTextColor="@color/tab_text"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code></pre> | 1 |
Text in clipboard with protractor js | <p>How can I copy a specific text with protractor ?</p>
<p>I would like to load a text to paste after with this command :</p>
<pre><code>return browser.actions().sendKeys(Keys.CONTROL, 'v').perform();
</code></pre>
<p>Sample :</p>
<p>Load my text "test" and after with this command, paste "test"</p>
<p>I would like put a text in my clipboard</p> | 1 |
SQL Server CTE error: Types don't match between the anchor and the recursive part | <p>I wrote a CTE code that parses out delimited strings (delimiter can be whatever) into a table. So "<code>MI,TX,WI</code>" would be parsed into a table with 3 rows.</p>
<p>It works as long as I do not use <code>NVARCHAR(MAX)</code> as the string input that I want to parse. </p>
<p>I want to know how I can get it to work with <code>NVARCHAR(MAX)</code> (or at very least <code>VARCHAR(MAX)</code>?</p>
<p>THIS WORKS except for comment if you change that you get this error: </p>
<blockquote>
<p>Types don't match between the anchor and the recursive part in column
"b" of recursive query "cte".</p>
</blockquote>
<pre><code>--- change this to NVARCHAR(MAX) and it fails
DECLARE @DelimitedString NVARCHAR(4000)
DECLARE @Delimiter NVARCHAR(10)
SET @Delimiter = '--'
SET @DelimitedString= '123--456--7890, 234--456--7890'
-- do here instead of in every loop below
DECLARE @DelimiterLength AS TINYINT
SET @DelimiterLength = len(@Delimiter)
;with cte as
(
select 0 a, 1 b
union all
select b, charindex(@Delimiter, @DelimitedString, b) + len(@Delimiter)
from cte where b > a
)
select LTRIM(RTRIM(
SUBSTRING(@DelimitedString,
a,
case when b > @DelimiterLength then b-a-@DelimiterLength else len(@DelimitedString) - a + 1 end
)--END SUBSTRING
))--end LTRIM/RTRIM
value
from cte where a > 0
</code></pre>
<p>I understand what the error means in a standard, the columns in the UNION datatypes have to match. I do not see how to fix the issue here.</p>
<p>I want it to work with however long of a string we need because I do not know if the usage will be limited to strings of 4000 characters or not.</p> | 1 |
How to ignore the exception which are generated during the logging in python? | <p>I am working in a big python module(Python 2.6.6) and doing logging in thousand of places and i am using logger module of python.
Now, i want to ignore the exception, which are generated during the logging.
One of the basic scenario which could be possible is</p>
<pre><code>import glob
import logging
import logging.handlers
LOG_FILENAME = '/home/abc/logging_rotatingfile_example.out'
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
</code></pre>
<p>Now suppose, during the <code>my_logger.debug('i = %d' % i)</code> some how the file is deleted from the system or permissions are changed and logger couldn't able to log due to disk failure, disk full etc. on the log file and generate the exception on the screen.
It is distributed system and n number of process are using logger module. Please note process should not be aborted due to logging exception(due to disk failure, disk full etc.).
So i want that exception to be ignored.</p>
<p>NOTE:
Now one of the way i know to make wrapper class on python logger and use try-except for the logger function.
But i have different requirements and i dont want to use that way so ,is there any other way to do this or any attribute of python logger which can be useful for my condition?</p> | 1 |
Make CSS hover state remain after unhovering | <p>How can I make the hover state remain for at least 1 second? Currently it is difficult to select the sub menu items as the hover state disappears too soon.</p>
<p>Here is the <a href="https://jsfiddle.net/sarowerj/2dmqduy2/6/" rel="nofollow">jsFiddle</a>. </p>
<p>My HTML:</p>
<pre><code><div class="container">
<div class="row">
<div class="col-md-12">
<div>
<span>Logo+Text</span>
</div>
<div class="btn-group has_dropdown" style="margin-left: 200px">
<a href="#" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Lists</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="#">Sub List 1</a>
</li>
<li>
<a href="#">Sub List 2</a>
</li>
<li>
<a href="#">Sub List 3</a>
</li>
<li>
<a href="#">Sub List 4</a>
</li>
<li>
<a href="#">Sub List 5</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</code></pre>
<p>And CSS:</p>
<pre><code>#headerDropdown .dropdown:hover .dropdown-menu,
.btn-group:hover .dropdown-menu {
display: inline-flex !important;
}
</code></pre> | 1 |
pygame - What is the code for clicking on an image | <p>I'm adding a title screen to my game, and I want to add "play" button that will launch the main game when the user clicks it. </p>
<p>I have everything set up, but I'm not sure what the command is to have the mouse interact with the play button image.</p>
<p>First, I have the play button image loaded outside of the main loop</p>
<pre><code>play = pygame.image.load("play.png").convert()
</code></pre>
<p>Then, I have it blit on the screen, with a rectangle behind it as a marker</p>
<pre><code>play_button = pygame.draw.rect(screen, WHITE, [365, 515, 380, 180])
screen.blit(play, [350, 500])
</code></pre> | 1 |
how to rename a file in android | <p>Help me in converting a file name to own file name.</p>
<p>I tried the following but it did not work:</p>
<pre><code>File file = new File("27.mp4");
File file1 = new File("abcd");
file1.rename(file);
</code></pre> | 1 |
Python times tables code with recursion | <p>I have to make a times table code using recursive functions. I have to ask the user for a number and print out the times tables from 1 to 12. And I have to use recursive functions and it is not allowed to use <code>for</code> loops or <code>while</code> loops and all variables besides the user input have to be defined inside the functions. I am having trouble defining the number that the user provided number needs to be multiplied with. E.X. 2 x <strong>1</strong> 2 x <strong>2</strong> 2 x <strong>3</strong>. </p>
<pre><code>def times_tables(num):
def multiply(x):
product = x * num
if x < 12:
print (str(multiply(x + 1)))
user = input("Enter a number: ")
times_tables(user)
</code></pre>
<p>If I define <code>x</code> in the <code>times_tables</code> function then every time the function runs it will get set back to whatever I set it to the first time. Thanks for your help. </p> | 1 |
Is it possible to update an already created job in Kue Node.js? | <p>I am creating jobs using <a href="https://github.com/Automattic/kue" rel="nofollow noreferrer">Kue</a>.</p>
<pre><code>jobs.create('myQueue', { 'title':'test', 'job_id': id ,'params': params } )
.delay(milliseconds)
.removeOnComplete( true )
.save(function(err) {
if (err) {
console.log( 'jobs.create.err', err );
}
});
</code></pre>
<p>Every job has a delay time, and normally it is 3 hours.</p>
<p>Now I will to check every incoming request that wants to create a new job and get the id .</p>
<p>As you can see from the above code, when I am creating a job I will add the job id to the job.</p>
<p>So now I want to check the incoming id with the existing jobs' job_id s in the queue and update that existing job with the new parameters if a matching id
found.</p>
<p>So my job queue will have unique job_id every time :).</p>
<p>Is it possible? I have searched a lot, but no help found. I checked the kue <a href="https://github.com/Automattic/kue#json-api" rel="nofollow noreferrer">JSON API</a>. but it only can create and get retrieve jobs, can not update existing records.</p> | 1 |
How to make a Transparent Layer over the CardIView Item? | <p>I need a transparent layer over the particular Griditem at where I click the <strong>RED MARKED icon(3 dots)</strong>. I got the transparent layer.But it is not over the grid.,I got it at the top of an activity.
How to do this?</p>
<p><a href="https://i.stack.imgur.com/d8biy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d8biy.png" alt="**Expected Result**"></a> </p>
<p><a href="https://i.stack.imgur.com/CJFJ3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CJFJ3.png" alt="enter image description here"></a></p>
<p>This is my code:</p>
<p><strong>In Adapter Class:</strong></p>
<pre><code>private void createDialogBox() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final AlertDialog dialog = builder.create();
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
View dialogLayout = LayoutInflater.from(context).inflate(R.layout.demo_dialog, null);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setView(dialogLayout, 0, 0, 0, 0);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface d) {
}
});
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
dialog.show();
}
</code></pre>
<p><strong>demo_dialog.xml:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
style="@style/LinearLayout_mm"
android:layout_gravity="center"
android:gravity="center"
android:onClick="Click"
android:orientation="vertical"
android:theme="@style/cust_dialog">
<ImageView
android:id="@+id/pullToRefresh_img"
style="@style/LinearLayout_mm"
android:onClick="Click"
android:src="@drawable/ig_dash_front1" />
</LinearLayout>
</code></pre>
<p><strong>style.xml:</strong></p>
<pre><code> <style name="cust_dialog" parent="@android:style/Theme.Holo.NoActionBar.Fullscreen">
<item name="android:textColor">@color/white</item>
<item name="android:background">#80000000</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@color/black</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">false</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:gravity">center</item>
<item name="colorAccent">#00f3f4f8</item>
</style>
</code></pre> | 1 |
Injecting Dependency into Web API Controller | <p>I want to inject unity container into WebController.</p>
<p>I have UnityDependencyResolver:</p>
<pre><code>public class UnityDependencyResolver : IDependencyResolver
{
readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
public void Dispose()
{
_container.Dispose();
}
}
</code></pre>
<p>Then, in my Global.asax I add the following line:</p>
<pre><code>var container = new UnityContainer();
container.RegisterType<IService, Service>
(new PerThreadLifetimeManager()).RegisterType<IDALContext, DALContext>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
</code></pre>
<p>Then, If I use the following in a Web Controller:</p>
<pre><code>private IService _service;
public HomeController(IService srv)
{
_service = srv;
}
</code></pre>
<p>It works fine.</p>
<p>But I want to inject it into WebAPI Controller, so if I do it the same way:</p>
<pre><code>private IService _service;
public ValuesController(IService srv)
{
_service = srv;
}
</code></pre>
<p>It does not work, it says that constructor is not defined.
Ok, I create one more constructor:</p>
<pre><code>public ValuesController(){}
</code></pre>
<p>And in this case it uses only this constructor and never the one where I should inject unity container.</p>
<p>Please advise.</p> | 1 |
Firing custom event from custom component and handle event in viewController | <p>I have created a custom component that extends from Ext.Panel. I have added a click listener to the custom component so that when it's clicked it will fire an event. I am instantiating the custom component in a view and I want to handle the event thats fired from the custom component in the viewController associated with that view.</p>
<p>However, when I fire the event, it's not bubbling up to the viewController. Is there a way to fire an event on the global scope? How do I go about handling an event in a viewController where the component that fires the event is instantiated in the view associated with the view controller?</p>
<p>My custom component looks somthing like so:</p>
<pre><code>Ext.define('MyApp.ux.CustomComponent', {
extend: 'Ext.Panel',
xtype: 'custom-component'
initComponent: function() {
var me = this;
me.callParent();
me.addListener({
'render': function(panel) {
panel.body.on('click', function() {
me.fireEvent('customEventName');
});
}
});
}
});
</code></pre>
<p>I am instantiating my custom component in a view like so:</p>
<pre><code>Ext.define('MyApp.view.main.Main', {
extend: 'Ext.container.Container',
controller: 'main'
items: [{
xtype: 'custom-component'
}]
});
</code></pre>
<p>And in my viewController (for the view that im instantiating my custom component in) I have the following listener:</p>
<pre><code>customEventName: function () {
console.log('I have been fired');
}
</code></pre> | 1 |
How to configure the time it takes for a kafka cluster to re-elect partition leaders after stopping and restarting a broker? | <p>I have the following setup:<br>
3 kafka brokers and a 3 zookeeper ensamble<br>
1 topic with 12 partitions and 3 replicas (each kafka broker is thus the leader of 4 partitions)<br></p>
<p>I stop one of the brokers - it gets removed from the cluster, leadership of its partitions is moved to the two remaining brokers</p>
<p>I start the broker back - it reappears in the cluster, and eventually the leadership gets rebalanced so each broker is the leader of 4 partitions.</p>
<p>It works OK, except I find the time spent before the rebalancing too long (like minutes). This happens under no load - no messages are sent to the cluster, no messages are consumed.</p>
<p>Kafka version 0.9.0.0, zookeeper 3.4.6</p>
<p>zookeeper tickTime = 2000</p>
<p>kafka zookeeper.connection.timeout.ms = 6000</p>
<p>(basically the default config)</p>
<p>Does anyone know what config parameters in kafka and/or zookeeper influence the time taken for the leader rabalancing ?</p> | 1 |
How to reverse the order of SortedSet | <p>I want to print an ordered list in Map using the following:</p>
<pre><code>Map<Float, String> mylist = new HashMap<>();
mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);
SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet());
for (Float i : orderlist) {
System.out.println(i+" "+mylist.get(i));
}
</code></pre>
<p>The above code prints:</p>
<pre><code>5.1 c
10.5 a
12.3 b
</code></pre>
<p>But how do I the print the orderlist in reverse order like below:</p>
<pre><code>12.3 b
10.5 a
5.1 c
</code></pre> | 1 |
Adding duplicate objects to GridPane as new row | <p>I want to dynamically add new rows based on the input number from text field. I have prepared this row (textField and comboBox) in fxml (scene builder) outside of visible scope. </p>
<p>So I have reference to these objects which I want to add:</p>
<pre><code>@FXML
private ComboBox fieldType;
@FXML
private TextField fieldName;
</code></pre>
<p>And based on number from other textField I am adding rows to gridPane:</p>
<pre><code>for (int i = 0; i < newRows; i++) {
grid.addRow(grid.impl_getRowCount(), fieldName, fieldType);
}
</code></pre>
<p>I get this exception: </p>
<pre><code>Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = Grid hgap=0.0, vgap=5.0, alignment=TOP_LEFT
</code></pre>
<p>I thought that I will clone these objects like this:</p>
<pre><code>public class CloningMachine implements Cloneable {
private Node node;
public CloningMachine() {
}
public CloningMachine setNode(Node node) {
this.node = node;
return this;
}
public Node getNode() {
return node;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
</code></pre>
<hr>
<pre><code>for (int i = 0; i < newRows; i++) {
grid.addRow(grid.impl_getRowCount(), ((CloningMachine)new CloningMachine().setNode(fieldName).clone()).getNode(), ((CloningMachine)new CloningMachine().setNode(fieldType).clone()).getNode());
}
</code></pre>
<p>However I get the same exception.</p>
<p>Is it possible to do it somehow? Thanks</p> | 1 |
very odd error in Modelsim vsim.exe and C# | <p>i'm running a command shell VSIM.exe from a software. When I run it through the software (<code>p.StartInfo.FileName = @"C:\Modeltech_pe_edu_10.2b\win32pe_edu\vsim</code>, etc...)
I'm getting this error:</p>
<pre><code> Reading C:/modeltech64_10.0d/tcl/vsim/pref.tcl
couldn't open "transcript": permission denied
Initialization problem, exiting.
while executing
"BATCHMAIN"
invoked from within
"if {[batch_mode]} {
BATCHMAIN
} else {
GUIMAIN
}"
invoked from within
"ncFyP12 -+"
(file "C:\modeltech64_10.0d\win64/../tcl/vsim/vsim" line 1)
** Fatal: Exiting VSIM license process.
</code></pre>
<p>But, for debug purposes, when I'm running it through cmd.exe, it all works fine!
In CMD I'm running this command:</p>
<pre><code>C:\Modeltech_pe_edu_10.2b\win32pe_edu\vsim.exe -c -do d:\script_tcl.tcl
</code></pre>
<p>in the tcl script I have these lines:</p>
<pre><code>cd D:/Packages
set WRK work
if {[file exists $WRK]} {
} else {
vlib work
vmap work work}
vcom abcd.vhd
quit -f
</code></pre>
<p>so, when running this command from the process.start I'm getting an error regarding the transcript - permission denied, whereas doing the same thing thru a command line- it all works fine!
I've tried that on 4 different versions of ModelSim, all the same thing!!!
Any help will do...
Thank you!</p> | 1 |
clip analysis in arcpy | <p>I have one shapefile that covers an entire city, and a list of shapefiles which are buffers in different places in the city. I want to clip the city with each buffer. I tried using ArcPy in Python but the code is not working. What am I doing wrong?</p>
<pre class="lang-py prettyprint-override"><code>import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "U:\Park and Residential Area\Test\SBA park_res_buffer_5\SBA.gdb"
infeature= "U:\Park and Residential Area\Test\park_res_merge.shp"
clipfeatture = arcpy.ListFeatureClasses("*", "polygon")
for i in clipfeatture:
outclipfeatture = arcpy.Clip_analysis(infeature,i)
outclipfeatture.save("U:\Park and Residential Area\Test\SBA park_res_buffer_5/"*i)
</code></pre> | 1 |
Fixed navbar with flexbox | <p>I found this cool framework that uses flex as it's grid. <a href="http://bulma.io/" rel="nofollow">http://bulma.io/</a></p>
<p>I have my header setup as so:</p>
<pre><code><header class="header">
<div class="container">
<!-- Left side -->
<div class="header-left">
<a class="header-item" href="#">
<!-- <h1 class="title is-1">VapesForVets</h1> -->
</a>
</div>
<!-- Hamburger menu (on mobile) -->
<span class="header-toggle">
<span></span>
<span></span>
<span></span>
</span>
<!-- Right side -->
<div class="header-right header-menu">
<span class="header-item is-active">
<a href="#" class="header-tab is-active">Home</a>
</span>
<span class="header-item">
<a href="#">Why Us?</a>
</span>
<span class="header-item">
<a href="#">FAQs</a>
</span>
<span class="header-item">
<a href="#">Medical</a>
</span>
<span class="header-item">
<a href="#">Contact</a>
</span>
</div>
</div>
</header>
</code></pre>
<p>When I give the header a position:fixed; All the items in the navbar floats to the left.</p> | 1 |
Raising error if string not in one or more lists | <p>I wish to raise an error manually if a <em>target_string</em> does not occur in one or more lists of a list of lists.</p>
<pre><code>if False in [False for lst in lst_of_lsts if target_string not in lst]:
raise ValueError('One or more lists does not contain "%s"' % (target_string))
</code></pre>
<p>Surely there is a more Pythonic solution than the one specified above.</p> | 1 |
Multiple forms in the same window in C# | <p>I'm interested in the way to make some sub-forms, like child forms (for example, helper form that shows when you click on a find button and want to search through the suppliers).
But I don't want it to create another "window" in the taskbar, but to be integrated in the main form.</p>
<p>I know about Show() and ShowDialog(), but it opens another window in the taskbar...</p>
<p>I tried with MDI and was able to make it, but I don't want to use MDI.</p>
<p>So, can someone provide some knowledge about some alternative?
I've seen examples of this in some programs, but I don't know how is this achieved. I'm pretty new to visual C#.</p> | 1 |
How to retrive text that was copied (with the CTRL + C command) | <p>I have a Windows application written in C++. I want to add a paste option, so that on request the application can retrieve whatever text the user previously copied (i.e., with the control-C command). </p>
<p>Is there a way to do this?</p> | 1 |
XCode simulator: how to make Internet work for apps? | <p>I am developing a NativeScript app (i.e. a native app compiled from web languages) and deploying it to XCode (7.2) emulator.</p>
<p>NativeScript uses the Xcode command line tools internally.</p>
<p>I am working under OS X 10.11 (El Captain) and I tried to deploy my app to iPhone 5 and iPhone6 emulators.</p>
<p>The issue I'm getting is that <strong>my app can't reach REST APIs</strong> (get/post/....).
I'm deploying my APIs using <strong>json-server</strong>.</p>
<p>On Linux with json-server + run to Android emulator it works perfectly so I'm pretty sure <strong>it doesn't depend on json-server or my app code</strong>.</p>
<p>I tried an old solution posted at: <a href="https://stackoverflow.com/questions/13542706/iphone-simulator-cannot-connect-to-internet">iPhone simulator cannot connect to internet</a></p>
<p>Specifically, I've reset simulator settings as well as enabling 'HTTP services' in settings. <strong>The issue is still there</strong>. Any clue?</p> | 1 |
How to access the values of aggregate functions in Python | <p>I created a data frame and grouped and aggregated timestamp to give me min and max value for each grouping
the resulting data frame looks like this
DF is defined to be patient_id, timestamp
I grouped the DF by patient_id
and then I wanted to get the min and max timestamp for each groups
and I did this</p>
<pre><code>bypatient_date = pd.DataFrame(byencounter.agg({'timestamp' : [np.min,np.max]})).reset_index())
patient_id timestamp
amin amax
0 19 3396-08-21 3396-08-25
1 99 2723-09-27 2727-03-17
2 3014 2580-12-02 2581-05-01
3 24581 3399-07-19 3401-04-13
</code></pre>
<p>I am trying to find the difference between the min and max of each patient_id but I am having issue trying to access the values in timestamp amin and timestamp amax
Is there a way to do this without looping but using built-in pandas or numpy</p> | 1 |
How to scroll overflow:scroll div while dragging object? | <p>Let's say I have a draggable element with id <code>#draggable</code>. I also have a div that contains a list of droppable divs with id <code>#list</code>. But the container div is limited in height, so it can display only 3 droppable divs at once (A, B and C). That container div is set to <code>overflow:scroll</code>.</p>
<p>How could I manage to get the container div to scroll when I'm dragging the <code>#draggable</code> element over it? Because right now I can't drop the element on last droppable elements that are hidden by the overflow (D, E, F, G).</p>
<p><a href="https://jsfiddle.net/v80kppez/1/" rel="nofollow"><strong>See this fiddle for demo</strong></a></p>
<pre><code><span id="draggable">draggable</span>
<hr>
<div style="height:200px;overflow:scroll">
<ul id="list">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
</ul>
</div>
</code></pre>
<p>Also, you can that if you drop the element <strong>under</strong> the <code>overflow:scroll</code> div, it actually drops on the hidden droppable divs!</p>
<p>How to deal with those issues?</p> | 1 |
SQL Get lowest level child and root node | <p>I have database schema: [Id], [ParrentId], [some more tables]</p>
<p>I have hierarchy like:</p>
<pre><code>1. a
2. aa
3. aaa_1
3. aaa_2
1. b
2. bb
1. c
2. cc
3. ccc_1
4. cccc
3. ccc_2
</code></pre>
<p>I want a (select * where X) => [X, lowest leve child] like:
[a, aaa_1] [a, aaa_2]; [cc, cccc] etc.</p>
<p>I can get lowest child with </p>
<pre><code>SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;
</code></pre>
<p>but I don't know how to join it with root node.</p> | 1 |
How can I convert a image into a byte array in uwp platform | <p>I need to convert an image into a byte array to store it in a database. and also I need to convert that array back to the image. I did google research but I couldn't find a solution because in <code>UWP</code> platform some api doesn't available.</p> | 1 |
Validation for textfield to restrict for 6 digits | <p>we need to set validation in textfield : "zip code" under checkout process in magento site.</p>
<p>i need to restrict this textfield for maximum 6 digits.</p>
<p>i am using following code for this :</p>
<pre><code> <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>"
name="billing[postcode]" id="billing:postcode"
value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
class="input-text validate-zip-international
<?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
</code></pre>
<p>please help me to give validation for <strong>Restricting only for 6 digits</strong></p> | 1 |
Spring 4 recommended replacement of JpaTemplate | <p>I have a legacy project which was using Spring 3.0.x and made use of the <code>JpaTemplate</code> implementation provided by Spring.</p>
<p>However, after upgrading to Spring 4.0.x I learned that <code>JpaTemplate</code> was deprecated as of Spring 3.2</p>
<p>I have seen suggestions to simply refactor out the use of <code>JpaTemplate</code> with <code>EntityManager</code>.</p>
<p>However, replacing <code>JpaTemplate</code> with <code>EntityManager</code> is not sufficient as I discovered this project was wrapping the <code>JpaTemplate</code> calls in a <code>JpaCallback</code>, which in turn used entitymanager. I imagine the reason callbacks were used was to allow these DAO calls to be ran asynchronously.</p>
<p>Are there any suggested recommendations on how to refactor applications which make use of JpaTemplate and the JpaCallback class when upgrading to Spring 4?</p> | 1 |
Join of two Dataframes using multiple columns as keys stored in an Array in Apache Spark | <p>How to calculate the join of two Dataframes using multiple columns as key? For example DF1 , DF2 are the two dataFrame.</p>
<p>This is the way by which we can calculate the join,</p>
<pre><code>JoinDF = DF1.join(DF2, DF1("column1") === DF2("column11") && DF1("column2") === DF2("column22"), "outer")
</code></pre>
<p>But my problem is how to access the multiple columns if they are stored in an arrays like :</p>
<pre><code>DF1KeyArray=Array{column1,column2}
DF2KeyArray=Array{column11,column22}
</code></pre>
<p>then It is not possible to calculate the join by this method</p>
<pre><code>JoinDF = DF1.join(DF2, DF1(DF1KeyArray)=== DF2(DF2KeyArray), "outer")
</code></pre>
<p>In this case error was :</p>
<pre><code><console>:128: error: type mismatch;
found : Array[String]
required: String
</code></pre>
<p>Is there any way to access multiple columns as keys stored in an Array for calculation of join? </p> | 1 |
Instagram API pagination - Previous Page | <p>I am getting Instagram user's media with Jquery. </p>
<p>I need to get All user media, but Instagram API media limit is only 20 and API pagination returns only next link. There is no previous link.</p>
<p>I write code somethink like that, this is working with next but not working previous. And I stack here</p>
<pre><code>function instaPhotos(page) {
var $limit = 1;
var $token = $('.instagram').data('instagramtoken');
var $nextId = $('.instagram').attr('data-instagramnext');
var $pageNumber = parseInt(localStorage.getItem('page'));
switch (page){
case 'next':
localStorage.setItem('page', ($pageNumber+1));
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit + '&max_id=' + $nextId
break;
case 'prev':
localStorage.setItem('page', ($pageNumber-1));
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit + '&min_id=' + $nextId
break;
default:
localStorage.setItem('page', 1);
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit
}
console.log($pageNumber);
console.log($url);
$.ajax({
method: "GET",
url: $url,
dataType: "jsonp",
context: this,
success: function (r) {
if (r.pagination.next_max_id){
$('.instagram').attr('data-instagramnext', r.pagination.next_max_id);
}
// photo actions here.
}
});
}
</code></pre> | 1 |
Winforms: Resizing user controls in form control | <p>Context:</p>
<p>I'm trying to build a form using <a href="https://msdn.microsoft.com/en-us/library/ff648465.aspx" rel="nofollow">Microsoft Prism guidelines</a>.</p>
<p>I have two user controls that get injected into a form.
The form contains two panels that represent the containers which will hold the user controls.</p>
<p>The user controls get inject at run time via DI (I'm using the MVP pattern which is similar to MVVM but tweaked for Winforms).</p>
<p>The form has a default minimum size but the maximum size was not specified. The only way to resize the form is to make it fullscreen. It has the AutoSize property set to TRUE and the AutoSizeMode set to GrowAndShrink</p>
<p>Both user controls have the AutoSize set to TRUE.
All the containers inside the user controls have the AutoSize property set to TRUE, DOCK set to FILL and AutoSizeMode=GrowAndShrink. The maximum size for a control is not set.</p>
<p>The panels inside the the form are stacked one under another and have the Anchor property set to: TOP, LEFT,RIGHT, respectively: BOTTOM, LEFT, RIGHT.</p>
<p>Problem:</p>
<p>When resizing the form to fullscreen, I would expect that the user control to expand to fill the entire screen.</p>
<p>That is not happening.</p>
<p>The user controls do not change in size and I can't figure out a reason for it.</p>
<p>Thanks.</p>
<p><strong>UPDATE</strong></p>
<p>If I change the DOCK property of the panels inside the form to TOP, respectively
FILL, the panel will get resized, but the user controls inside the panels remain unchanged. </p> | 1 |
UWP Databinding: How to set button command to parent DataContext inside DataTemplate | <p>Short explanation of need: I need to fire the command of a button inside a DataTemplate, using a method from the DataContext of the ViewModel.</p>
<p>Short explanation of problem: The templated button command only seems to be bindable to the datacontext of the item itself. The syntax used by WPF and Windows 8.1 apps to walk up the visual tree doesn't seem to work, including ElementName and Ancestor binding. I would very much prefer not to have my button command located inside the MODEL.</p>
<p>Side Note: This is built with the MVVM design method.</p>
<p>The below code generates the list of items on the VIEW. That list is one button for each list item.</p>
<pre><code> <ItemsControl x:Name="listView" Tag="listOfStories" Grid.Row="0" Grid.Column="1"
ItemsSource="{x:Bind ViewModel.ListOfStories}"
ItemTemplate="{StaticResource storyTemplate}"
Background="Transparent"
IsRightTapEnabled="False"
IsHoldingEnabled="False"
IsDoubleTapEnabled="False"
/>
</code></pre>
<p>Inside the page resources of the same VIEW, I have created a DataTemplate, containing the problematic button in question. I went ahead and stripped out most of the formatting inside the button, such as text, to make the code easier to read on this side. Everything concerning the button works, except for the problem listed, which is the binding of the command.</p>
<pre><code><Page.Resources>
<DataTemplate x:Name="storyTemplate" x:DataType="m:Story">
<Button
Margin="0,6,0,0"
Width="{Binding ColumnDefinitions[1].ActualWidth, ElementName=storyGrid, Mode=OneWay}"
HorizontalContentAlignment="Stretch"
CommandParameter="{Binding DataContext, ElementName=Page}"
Command="{Binding Source={StaticResource Locator}}">
<StackPanel HorizontalAlignment="Stretch" >
<TextBlock Text="{x:Bind StoryTitle, Mode=OneWay}"
FontSize="30"
TextTrimming="WordEllipsis"
TextAlignment="Left"/>
</StackPanel>
</Button>
</DataTemplate>
</Page.Resources>
</code></pre>
<p>Because this is a DataTemplate, the DataContext has been set to the individual items that comprise the list (MODEL). What I need to do is select the DataContext of the list itself (VIEWMODEL), so I can then access a navigation command.</p>
<p>If you are interested in the code-behind of the VIEW page, please see below.</p>
<pre><code> public sealed partial class ChooseStoryToPlay_View : Page
{
public ChooseStoryToPlay_View()
{
this.InitializeComponent();
this.DataContextChanged += (s, e) => { ViewModel = DataContext as ChooseStoryToPlay_ViewModel; };
}
public ChooseStoryToPlay_ViewModel ViewModel { get; set; }
}
</code></pre>
<p>I've tried setting it by ElementName, among many other attempts, but all have failed. Intellisense detects "storyTemplate" as an option when ElementName is input, which is the name of the DataTemplate shown in the first code block of this question.</p>
<p>I don't believe my problem can be unique, however I'm having great difficulty finding a solution for UWP. Allow me to apologize in advance in this is a simple question, but I've spent nearly two days researching answers, with none seeming to work for UWP.</p>
<p>Thank you guys!</p> | 1 |
Get total sum values within ng-repeat with angular js | <p>I used ng-repeat to repeat json array. I calculated Night(s) by using dayDiff() function. Now I want to get total night all invoices. I am using angularjs. </p>
<p>How can I get total nights for all invoices?</p>
<pre><code><table class="table" ng-show="filteredItems > 0">
<tr>
<td>No</td>
<td>Invoice No</td>
<td>Name</td>
<td>Eamil</td>
<td>Room Name</td>
<td>Check In Date</td>
<td>Check Out Date</td>
<td>No. Room</td>
<td>Night(s)</td>
<td>Booking Date</td>
<td>Amount</td>
</tr>
<tr ng-repeat="data in filtered = (list | filter:search ) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td>{{$index+1}}</td>
<td>{{data.invoicenumber}}</td>
<td>{{data.firtname}}{{data.lastname}}</td>
<td>{{data.email}}</td>
<td>{{data.roomname}}</td>
<td ng-model='fromDate'>{{data.cidt}}</td>
<td ng-model='toDate'>{{data.codt}}</td>
<td>{{data.qty}}</td>
<td ng-model='night'>{{dayDiff(data.cidt,data.codt)}}</td>
<td>{{data.bdt}}</td>
<td>{{data.btotal}}</td>
</tr>
</table>
</code></pre> | 1 |
How to integrate ccavenue in laravel | <p>I have merchant_id, access key and working key. I have downloaded integration kit which include</p>
<blockquote>
<p>ccavRequestHandler.php, ccavResponseHandler.php, Crypto.php</p>
</blockquote>
<p>How to use those file and all those keys in laravel?</p>
<p>I have created checkout page in that user will enter their own information as well as bank information.</p>
<p>Please help me.</p> | 1 |
Multiple ajax data to Spring MVC controller | <p>I need to send data to Spring MVC controller by ajax. But controller doesn't work if I send more than one parameter.</p>
<p>Controller method:</p>
<pre><code>@Timed
@RequestMapping(value = "saveee", method = RequestMethod.POST)
@ResponseBody
public JsonResultBean saveTicketTemplate(@RequestBody TicketTemplateFieldBean fieldBean, Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
</code></pre>
<p>With this ajax code all works perfectly:</p>
<pre><code>$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
</code></pre>
<p>But if I change data parameters, then controller doesn't get request even.</p>
<pre><code>data: ({'fieldBean': JSON.stringify(fieldBean.data), 'id': id})
</code></pre>
<p>What I'm doing wrong?</p> | 1 |
-bash: script.sh: /usr/bin/ksh: bad interpreter: Permission denied | <p>I have some problems with ksh.
Logs says we don't have permission to access to ksh.
All rights are 777 and we did the symbolic link into /usr/bin/</p>
<p>In /usr/bin :</p>
<pre><code>lrwxrwxrwx 1 root root 8 Feb 2 10:29 ksh -> /bin/ksh
</code></pre>
<p>In /bin</p>
<pre><code>lrwxrwxrwx 1 root root 21 Dec 23 11:15 ksh -> /etc/alternatives/ksh
</code></pre>
<p>In /etc/alternatives</p>
<pre><code>lrwxrwxrwx 1 root root 8 Feb 2 10:01 /etc/alternatives/ksh -> /usr/bin
</code></pre>
<p>Did something go wrong during installation ?</p>
<p>It's quite critical for me, thanks for you help !</p> | 1 |
Installing Moodle - failed to load cURL php extension | <p>I know that there are lot of questions regarding this issue, but believe me , I've tried a bunch of solutions offered, but none of them worked for me.</p>
<p>Here is the list of software I've used (this is what I've been asked to use)</p>
<ol>
<li>httpd-2.2.31-win32</li>
<li>php 5.4.45-Win32-VC9-x86 thread safe</li>
<li>mysql 5.6.11.0msi</li>
<li>moodle 2.8.10</li>
</ol>
<p>After first introduction steps into moodle installation , where everything passed smoothly,I’ve encountered the problem shown on the capture.
<a href="https://i.stack.imgur.com/KCXVp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KCXVp.png" alt="enter image description here"></a></p>
<p>List of things I've tried :
- I’ve checked if <code>php_curl.dll</code> exist in ext file , it does.</p>
<ul>
<li><p>I’ve checked if line <code>;extension=php_curl.dll</code> is uncommented , it was.</p></li>
<li><p>Then I’ve took <code>icudt49.dll, icuin49.dll and icuuc49.dll</code> files and paste them inside Apache bin directory, restart apache and still nothing.</p></li>
<li><p>I read many posts, most mention copying 3 files
into C:\Windows\system32 or C:\Windows\SysWOW64 folder</p>
<pre><code> - php_curl.dll
- libeay32.dll
- ssleay32.dll , again nothing.
</code></pre></li>
<li>Then found fixed curl extensions , tried with that , again nothing.</li>
<li>Tried everything found here <a href="https://stackoverflow.com/questions/13021536/how-to-enable-curl-in-wamp-server">How to enable curl in Wamp server</a>.</li>
</ul>
<p>Is there anyone who can help ?
Thank You.</p> | 1 |
How do I loop across a correlation matrix to only give me pairs of correlations above a certain threshold? And/or make it more efficient | <p>I've got the following code:</p>
<pre><code>for i in list(corr.columns):
for j in list(corr.columns):
if corr.ix[i,j]>0.7 and corr.ix[i,j] != 1:
print i, ' ',j ,' ', corr.ix[i,j]
</code></pre>
<p>The problem is that whilst this works, it returns both corr[i,j] and corr[j,i] as if they were different correlations.
Is there anyway I could just loop through just the 'bottom triangle' of the correlation matrix?</p> | 1 |
Task Scheduler in Windows 10 throwing (0x1) on successfully completed task | <p>Running Windows 10 Pro I have the following command line as a scheduled task in Task Scheduler, running as SYSTEM, Run whether user is logged on or not, Run with highest privileges, configured for Windows 10:</p>
<pre><code>Robocopy.exe V:\Users\bbearren\Documents A:\OneDrive\Documents /MIR /XJD /R:1 /W:1 /MT:64 /V /NP /LOG:V:\Users\bbearren\Desktop\RoboCopy.log
</code></pre>
<p>If I edit the trigger to run a couple of minutes in the future and then exit Task Scheduler, the task runs, writes the log, and with Last Run Result </p>
<blockquote>
<p>"The operation completed successfully. (0x0)"</p>
</blockquote>
<p>If I reopen Task Scheduler and edit the trigger time to 3:00 AM (when I am logged off), the task runs successfully at 3:00 AM, writes the log file to the desktop, but shows <code>0x1</code> as the last run result.</p>
<p>The log results begin:</p>
<p><a href="http://i.stack.imgur.com/9k1H9.png" rel="nofollow">Robocopy Log.PNG</a></p>
<p>followed by a verbose log showing "same" files and "newer" files. The target directory shows that the "newer" files have been written.</p>
<p>I don't understand what is triggering the Last Run Result of <code>0x1</code>.</p>
<p>My purpose for this task is to trigger an automated OneDrive sync, and this is being accomplished.</p> | 1 |
XML and "flags" | <p>What's the "proper" way to encode a numeric flags variable in XML?</p>
<p>I'm converting a program that dumps data between a couple of systems.
Currently the dump is a tab-separated-values file (tabs shown as ⟿ here):</p>
<pre><code>blah de blah ⟿ blargh ⟿ 176 ⟿ ...
</code></pre>
<p>One of the fields is a number representing a "flags" word in the source DB:</p>
<pre><code>#define COURTEOUS 1 /* names changed to protect something */
#define KIND 2
#define FORGIVING 4
#define WITTY 8
#define OBSEQUIOUS 16
#define PURPLE 32
#define HAPPY 64
#define CLAIRVOYANT 128
#define WISE 256
...
</code></pre>
<p>It has been expressed that a number may not be the handiest way to transmit this information. My current thinking is running along these lines:</p>
<pre><code><things>
<thing>
<name>blah de blah</name>
<owner>blargh</owner>
<flags value='176'>
<flag>OBSEQUIOUS</flag>
<flag>PURPLE</flag>
<flag>CLAIRVOYANT</flag>
</flags>
...
</thing>
...
</things>
</code></pre>
<p>Is this a sensible approach? Is there some sort of standard approach to this?
Would this:</p>
<pre><code> <flags value='176'>
<OBSEQUIOUS/>
<PURPLE/>
<CLAIRVOYANT/>
</flags>
</code></pre>
<p>be an improvement?</p>
<p>Thanks!</p> | 1 |
SyntaxError using `with open...` | <p>There are several questions on SO that seem to deal with my problem. However, they all seem to be caused by using a pre-2.6 version of Python. Which is not the case here. I appreciate any help tracking down the cause of this.</p>
<p>I get a Syntax Error when I try to use a <code>with open() as f</code> construct.</p>
<p>Here's the code (test.py):</p>
<pre><code>#!/usr/bin/env python
import sys
print sys.version
fname = "/tmp/test.txt"
open(fname, 'a').close()
with open(fname, 'a') as fh
fh.write("test")
</code></pre>
<p>Here's the output:</p>
<pre><code>$ ./test.py
File "./test.py", line 10
with open(fname, 'a') as fh
^
SyntaxError: invalid syntax
</code></pre>
<p>Python version being used:</p>
<pre><code>$ /usr/bin/env python
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ whereis python
python: /usr/bin/python3.4 /usr/bin/python /usr/bin/python3.4m /usr/bin/python3.3 /usr/bin/python3.3m /usr/bin/python2.7 /usr/lib/python3.4 /usr/lib/python3.3 /usr/lib/python3.5 /usr/lib/python2.7 /etc/python3.4 /etc/python /etc/python3.3 /etc/python2.7 /usr/local/lib/python3.4 /usr/local/lib/python3.3 /usr/local/lib/python2.7 /usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz
</code></pre>
<p>My system info:</p>
<pre><code>$ uname -a
Linux ... 4.2.0-27-generic #32-Ubuntu SMP Fri Jan 22 04:49:08 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>Thanks!</p> | 1 |
How to add 'Add More' button to a set of dropdown list? | <p>when the 1st (destination) and 2nd (attraction or activity) dropdown lists are selected the options the 3rd drop down list shows the available activities or attractions dynamically.</p>
<p>here is the demo : <a href="http://codepen.io/foolishcoder7721/pen/jWYOxm" rel="nofollow">http://codepen.io/foolishcoder7721/pen/jWYOxm</a></p>
<p>my mark up:</p>
<pre><code><div class="multi-field-wrapper">
<button type="button" class="add-field">Add Destination</button>
<div class="multi-fields">
<div class="multi-field">
<select class="text-one" name="destination[]">
<option selected value="base">Please Select</option>
<option value="colombo">Colombo</option>
</select>
<br />
<select class="text-two" name="attraction_or_activity[]">
<option value="attraction_or_activity">Select the attractions or activities</option>
<option value="attraction">Attraction</option>
<option value="activity">Activity</option>
</select>
<select id="populated_attr_or_activity" name="attraction_or_activity_selected[]">
<!-- here I ahve to populate the ARRAYS as option -->
<option value="available_attr_act">Available attractions / activities</option>
</select>
</div>
</div>
</code></pre>
<p>And the jQuery for that:</p>
<pre><code><script>
$(document).ready(function() {
$(".text-two").change(function() { // when the attraction_OR_activity dropdown is selected
$('#populated_attr_or_activity').html(''); // emptying the selections of 3rd dropdown list if there was any selections were made before.
/* saving selected values in variables */
var selected_destination = $('.text-one :selected').val();
var selected_attraction_or_activity = $('.text-two :selected').val();
colombo_attractions = new Array("Ganga Ramaya","National Art Gallery","Galle Face Green","Arcade Indepentent Square");
colombo_activities = new Array("City Walk 2016","Traditional Dance Competition 2016","Local Spicy food");
if ( selected_destination == 'colombo' && selected_attraction_or_activity == 'attraction') {
colombo_attractions.forEach(function(t) {
$('#populated_attr_or_activity').append('<option>'+t+'</option>');
});
}
if ( selected_destination == 'colombo' && selected_attraction_or_activity == 'activity') {
colombo_activities.forEach(function(t) {
$('#populated_attr_or_activity').append('<option>'+t+'</option>');
});
}
});
</script>
</code></pre>
<p>That part works perfectly.</p>
<p>Now I want to a add more (add destination) button to create another set same dropdown lists. so guests can select more than one attractions and the activity.
For that I've added following jQuery part to the script.</p>
<pre><code><script>
/* ADD DESTINATION */
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
var x = 1;
$(".add-field", $(this)).click(function(e) {
x++;
$($wrapper).append('<div class="multi-field"><select class="text-one'+x+'" name="destination[]"><option selected value="base">Please Select</option><option value="colombo">Colombo</option><option value="kandy">Kandy</option><option value="anuradhapura">Anuradhapura</option></select><br/><select class="text-two'+x+'" name="attraction_or_activity[]"><option value="attraction_or_activity">Select the attractions or activities</option><option value="attraction">Attraction</option><option value="activity">Activity</option></select><select id="populated_attr_or_activity'+x+'" name="attraction_or_activity_selected[]"><option value="available_attr_act">Available attractions / activities</option></select><a href="#" class="remove_field">Remove</a></div>');
});
$($wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
});
</script>
</code></pre>
<p>I am able to get a set of same dropdown list when I click the <code><button type="button" class="add-field">Add Destination</button></code>
Remove also works fine.
You can check the demo : <a href="http://codepen.io/foolishcoder7721/pen/jWYOxm" rel="nofollow">http://codepen.io/foolishcoder7721/pen/jWYOxm</a></p>
<p>but the issue is I am unable load the 'availble attraction/activities' on the 2nd or 3rd set of drop down list.</p>
<p>I think it's because of same variable NAME I am using in <code>selected_destination</code> and <code>selected_attraction_or_activity</code>.</p>
<p><code>var selected_attraction_or_activity+x</code> gives me error.</p>
<p>how can make it work?</p>
<p>What I have to change to generate dynamic variables and arrays to load the available attractions / activities in 3rd dropdown in the set of 2nd and 3rd dynamically generated dropdown list according to the options selected? </p> | 1 |
Regex to replace @PathVariable values in Spring @RequestMapping URL | <p>I have Spring MVC URL's define in Interfaces (just to hold the Constants) like:</p>
<pre><code>String URL_X = "/my-url/{id:[0-9]*}";
String URL_Y = "/my-url/{id:[0-9]*}/blah-blah";
</code></pre>
<p>I have a method for my tests that replace the variables in an URL:</p>
<pre><code>private static final String REGEX_PARAMETROS_DA_URL = "(\\{[^\\}]*\\})";
protected String replaceParametersOnURL(String urlSpring, String... params) {
String urlAtual = urlSpring;
for (String parametro : params) {
urlAtual = urlAtual.replaceFirst(REGEX_PARAMETROS_DA_URL, parametro);
}
return urlAtual;
}
</code></pre>
<p>I was using this regex: <code>(\{[^\}]*\})</code> to match the variables and replace it.
But now i have some URL's that have {} on it and i can't find a properly regex to replace the variable with my value.</p>
<p>Is there any method on Spring that replaces the PathVariable value or can anyone help me with this regex?</p>
<p>Given this URL for instance:</p>
<pre><code>/pessoajuridica/{cnpj:[0-9]{14}}-{slug:[a-zA-Z0-9-]+}/sancoes/resumo
</code></pre>
<p>The matches must be: <code>{cnpj:[0-9]{14}}</code>and <code>{slug:[a-zA-Z0-9-]+}</code></p> | 1 |
How to drag and drop multiple divs in one div using javascript | <p>I'm having trouble on a project I mentioned earlier, now the problem is that I want to drag a div and drop it to another div. If I drag a div then it should be added below the previously dropped div. How can I achieve that? My current code is not appending the next div dropped, it overwrites the first one. I have tried many solutions but all end up doing more damage than good. Can anybody please help me, Thank you.</p>
<pre><code><html>
<head>
<title>CRM</title>
<link rel="stylesheet" href="style/style.css" type="text/css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".dragable").draggable({
cancel:"a.ui-icon",
revert:true,
helper:"clone",
cursor:"move",
revertDuration:0
});
$('.droppable').droppable({
accept: ".dragable",
activeClass: "ui-state-highlight",
drop: function( event, ui ) {
// clone item to retain in original "list"
var $item = ui.draggable.clone();
$(this).addClass('has-drop').html($item);
}
});
});
</script>
</head>
<body>
<div class="main-container">
<div class="wrapper">
<div class="tb-head">
<div class="target">
<span class="target-span">Target</span>
</div>
<div class="user1">
<span class="user1-span">User1</span>
</div>
<div class="user2">
<span class="user2-span">User2</span>
</div>
<div class="user3">
<span class="user3-span">User3</span>
</div>
<div class="user4">
<span class="user4-span">User4</span>
</div>
<div class="clear"></div>
</div>
<div class="tb-body">
<div class="inner-target">
<div class="dragable">
<span class="targetinn-span">Target Lead</span>
</div>
<div class="dragable">
<span class="targetinn-span">Assign1 Lead</span>
</div>
<div class="dragable">
<span class="targetinn-span">Assign2 Lead</span>
</div>
<div class="dragable">
<span class="targetinn-span">Assign3 Lead</span>
</div>
</div>
<div class="inner-user1">
<div class="droppable">
<span class="user1inn-span"></span>
</div>
</div>
<div class="inner-user2">
<div class="droppable">
<span class="user2inn-span"></span>
</div>
</div>
<div class="inner-user3">
<div class="droppable">
<span class="user3inn-span"></span>
</div>
</div>
<div class="inner-user4">
<div class="droppable">
<span class="user4inn-span"></span>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
</code></pre> | 1 |
Python 3 error: TypeError: Can't convert 'bytes' object to str implicitly in string that has more than 3 elements | <p>I wanted to make SHA256 hasher that will save both input and output in text file. I searched stackoverflow for answers but it didn't work. I wanted it to write in the text file: </p>
<pre><code>all = str("At: " + date + " you have encrypted: " + text + " into:" + hex_dig)
text_file.write(together)
</code></pre>
<p>While the date looks like that: </p>
<pre><code>date = time.strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
<p>It gave me this error in the first line of my sample: <code>TypeError: Can't convert 'bytes' object to str implicitly</code>.</p> | 1 |
How to safely terminate a tensorflow program running on multiple GPUs | <p>I have implement a network using tensorflow. The network is trained on 4 GPUs. When I hit <kbd>ctrl+c</kbd>, the program crashed the nvidia driver and created zombie process named "python". I am not able to kill the zombie process, neither can I reboot ubuntu system by <code>sudo reboot</code>. </p>
<p>I am using a FIFO queue and a thread to read data from binary files.</p>
<pre><code>coord = tf.train.Coordinator()
t = threading.Thread(target=load_and_enqueue, args=(sess,enqueue_op, coord))
t.start()
</code></pre>
<p>After I call <code>sess.close()</code>, the program won't stop and I see:</p>
<pre><code>I tensorflow/core/common_runtime/gpu/pool_allocator.cc:244] PoolAllocator: After 0 get requests, put_count=4033 evicted_count=3000 eviction_rate=0.743863 and unsatisfied allocation rate=0
I tensorflow/core/common_runtime/gpu/pool_allocator.cc:244] PoolAllocator: After 0 get requests, put_count=14033 evicted_count=13000 eviction_rate=0.926388 and unsatisfied allocation rate=0
</code></pre>
<p>It seems GPU resource is not released. If I open another terminal, <code>nvidia-smi</code> command won't work. Then I have to brutally restart system by:</p>
<pre><code>#echo 1 > /proc/sys/kernel/sysrq
#echo b > /proc/sysrq-trigger
</code></pre>
<p>I know <code>sess.close</code> may be too brutal. So I tried using dequeue operation to empty the FIFO queue, then:</p>
<pre><code>while iteration < 10000:
GPU training...
#training finished
coord.request_stop()
while sess.run(queue_size) > 0:
sess.run(dequeue_one_element_op)
print('queue_size='+str(sess.run(get_queue_size_op)))
time.sleep(1)
coord.join([t])
print('finished join t')
</code></pre>
<p>This method does not work either. Basically, the program can not terminate after max training iteration is reached.</p> | 1 |
I need to do a http request to a mail chimp subscription list via a component post | <p><strong>I need to do a http request to a mail chimp subscription list via a component post</strong></p>
<p>I've read the mail chimp documentation and couldnt find anything on this.
I also tried their mail chimp embedded form in an angular 2 html5 view but that doesnt work for some weird reason.</p>
<p>So I've resulted to doing a http request to the subscribe list instead and I'm having trouble getting that working.</p>
<p>I'm using typescript, angular2 and mail chimp</p>
<p><strong>This is my code so far:</strong></p>
<pre><code> subscribe = () => {
var url = "https://mysubscriptionlist.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
this.jsonp.request(url).subscribe(response => {
console.log(response);
});
}
</code></pre>
<p><strong>This is my current console log error in chrome:</strong></p>
<p>Uncaught SyntaxError: Unexpected token <</p> | 1 |
PyQt widget keyboard focus | <p>First off -- thanks for this group! I started delving into PyQt a month or so ago. In that time, I've bumped up against many questions, and virtually always found an answer here.</p>
<p>Until now.</p>
<p>I have a workaround for this, but I think it's a kluge and there probably is a proper way. I'd like to understand better what's going on.</p>
<p>Here's the code:</p>
<pre><code>from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class FormWidget(QWidget):
def __init__(self, parent):
super(FormWidget, self).__init__(parent)
# Create view with image in it
self.image = QGraphicsPixmapItem(QPixmap())
self.scene = QGraphicsScene()
self.scene.addItem(self.image)
self.view = QGraphicsView(self.scene)
self.hlayout = QHBoxLayout()
self.hlayout.addWidget(self.view)
self.setLayout(self.hlayout)
# self.view.keyPressEvent = self.keyPressEvent
def keyPressEvent(self, event):
key = event.key()
mod = int(event.modifiers())
print(
"<{}> Key 0x{:x}/{}/ {} {} {}".format(
self,
key,
event.text(),
" [+shift]" if event.modifiers() & Qt.SHIFT else "",
" [+ctrl]" if event.modifiers() & Qt.CTRL else "",
" [+alt]" if event.modifiers() & Qt.ALT else ""
)
)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
form = FormWidget(self)
self.setCentralWidget(form)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>As is, all keyboard input is detected by the overloaded keyPressEvent() function, except arrow keys. I've found enough posts talking about this to have a sense that it is because the child widget (self.view) is receiving them. I presume the child widget is, in fact, receiving <em>all</em> the keystrokes, but ignoring the ones that are getting through, and sucking up the arrow keys, which is why they aren't getting to the parent's keyPressEvent() function. That seems to be so, because if I uncomment the line in the middle:</p>
<pre><code> self.view.keyPressEvent = self.keyPressEvent
</code></pre>
<p>It behaves as I expect -- the parent's keyPressEvent() gets all the keystrokes, arrows included.</p>
<p>How would I tell the child widget to ignore all keystrokes? I thought maybe this:</p>
<pre><code> self.view.setFocusPolicy(Qt.NoFocus)
</code></pre>
<p>When I add that, keyPressEvent() doesn't see <em>any</em> keystrokes at all.</p>
<p>I suppose I could overload keyPressEvent() for the child as well, and just explicitly pass everything up to the parent. But that doesn't seem better than my kluge.</p>
<p>I think I must be misunderstanding something here.</p>
<p>Thanks. Just looking to learn ...</p> | 1 |
How do I reset PHPStorm? | <p>My problem is that I can't continue with my project, as long as PHPStorm won't let me use key combination anymore. Some key combination like ctrl + c are still working, but other more important combinations like uncomment many lines, or indent the code and some others don't work anymore. That's since yesterday, where my computer just shuts down without a reason.</p>
<p>Does anybody know how do I reset the settings of PHPStorm? I don't really want to uninstall and reinstall the program.</p>
<p>Using: PHPStorm 9.0.2</p> | 1 |
Intersection volume of ellipsoids | <p>I plot two ellipsoids with ellipsoid function and also use rotation handle. In order to compute the intersection volume (i.e. lens) and for the case of intersection volume between ellipsoids without rotation , i used analytical code for spheres intersection volume.
But I am stuck ,if ellipsoids are at some rotations ,how i will compute the intersection volume(i.e.lens) between them. Also i need to compute intersection dia. of lens.
ellipsoids have different rotational angles with respect to their max axis along z axis. here is a code:</p>
<pre><code> draw ellipsoid, [x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n);
(xc,yc,zc)=center; semi-axis lengths = (Fmax,Fmin,Fmin);n
X=[0,2]; two ellipsoid x coordinates i.e 0 is first ellipsoid
and 2 is second ellipsoid respectively
Y=[0,2]; two ellipsoid y coordinates
Z=[0,2]; two ellipsoid z coordinates;
ROTATIONANGLE=[90,30];
RMIN=[1,2]; two ellipsoid minor axis radius
RMAX=[3,5]; two ellipsoid major axis radius.
for a = 1:2 display ellipsoid
[x, y, z] = ellipsoid(X(a),Y(a),Z(a),RMIN(a),RMAX(a),3.25,30);
S = surfl(x, y, z);
rotate(S,[0,0,1],ROTATIONANGLE(a))
colormap copper
axis equal
xlabel('X')
ylabel('Y')`enter code here
zlabel('Z')
check the boolean condition
hold on
end
</code></pre> | 1 |
Accessing hadoop from remote machine | <p>I have hadoop set up (pseudo distributed) on a server VM and I'm trying
to use the Java API to access the HDFS. </p>
<p>The fs.default.name on my server is <code>hdfs://0.0.0.0:9000</code> (as with <code>localhost:9000</code> it wouldn't accept requests from remote sites). </p>
<p>I can connect to the server on port 9000 </p>
<pre><code>$ telnet srv-lab 9000
Trying 1*0.*.30.95...
Connected to srv-lab
Escape character is '^]'.
^C
</code></pre>
<p>which indicates to me that connection should work fine. The Java code I'm using is:</p>
<pre><code>try {
Path pt = new Path(
"hdfs://srv-lab:9000/test.txt");
Configuration conf = new Configuration();
conf.set("fs.default.name", "hdfs://srv-lab:9000");
FileSystem fs = FileSystem.get(conf);
BufferedReader br = new BufferedReader(new InputStreamReader(
fs.open(pt)));
String line;
line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>but what I get is:</p>
<pre><code>java.net.ConnectException: Call From clt-lab/1*0.*.2*2.205 to srv-lab:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
</code></pre>
<p>Thus, any hints on why the connection is refused even though connecting through telnet works fine?</p> | 1 |
Angular2 Recursive Templates in javascript | <p>I have been trying to follow <a href="http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0" rel="nofollow">this tutorial</a> to create a nested tree view. The tutorial is in typescript while I am trying to do a similar thing in javascript with Angular2. </p>
<p>In the typescript code, the tree-view component looks like so:</p>
<pre><code>import {Component, Input} from 'angular2/core';
import {Directory} from './directory';
@Component({
selector: 'tree-view',
templateUrl: './components/tree-view/tree-view.html',
directives: [TreeView]
})
export class TreeView {
@Input() directories: Array<Directory>;
}
</code></pre>
<p>In javascript that should convert to:</p>
<pre><code>TreeView = ng.core
.Component({
selector: 'tree-view',
templateUrl: './components/tree-view/tree-view.html',
directives: [TreeView],
inputs: ['directory'],
})
.Class({
constructor: function() {
},
});
</code></pre>
<p>However, javascript throws the following error:</p>
<blockquote>
<p>EXCEPTION: Unexpected directive value 'undefined' on the View of
component 'function () {'</p>
</blockquote>
<p>I believe it's because I'm calling directives: [TreeView] before TreeView has been fully defined. If I remove that directive line, the error goes away. However, I don't know why it would work in typescript and not javascript if typescript simply compiles to javascript. <a href="https://github.com/thelgevold/angular-2-samples/blob/3b93bd7649fec29d01d6f6e2d1ecbe033c1ec6bc/components/tree-view/tree-view.js" rel="nofollow">This is the compiled javascript from the typescript code.</a> I'm not sure what I'm missing. Any help would be super appreciated.</p> | 1 |
Django Template: remove underscore and capitalize each word | <p>Is there any filter in Django that can remove underscores and also capitalize each letter of the word OR remove underscores and capitalize the first letter of sentence?</p> | 1 |
Get Windows Command Line charset in java | <p>I've been having problems reading output of windows command line from Java, i'm using <code>Runtime.getRuntime().exec()</code></p>
<p>I simplified my test case: I have a file called <code>お読みください.txt</code>, and i execute the following <code>command cmd /c dir C:/PATH</code></p>
<p><strong>Note</strong>: The actual command is tasklist, but it's the same result as long as i use Runtime.getRuntime().exec()</p>
<pre class="lang-java prettyprint-override"><code>String[] cmd = new String[]{ "cmd", "/c", "dir" };
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput =
new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String s, result = "";
while ((s = stdInput.readLine()) != null) {
if (!s.isEmpty()) {
result += s + "\n";
}
}
System.out.println(result);
</code></pre>
<p>I just get ���ǂ݂�������.txt</p>
<p>I tried with no charset, default, and the other ones; after testing all charsets, i got the one i was looking for: <strong>Shift_JIS</strong></p>
<p>And that must be because i have set Language for non-Unicode applications as Japanese. systeminfo.exe says <strong>ja;Japanese</strong> for Regional Config.</p>
<p>I can simply use Shift_JIS to read, but it will only work in my computer. What about other system configurations?</p>
<p>The question is, how can i get the correct charset to read Windows Console output?</p> | 1 |
automating shell script to login vpn passing sudo -S | <p>I have to re-login to my VPN every time I leave my desk, and it is tedious. I am trying to pass the shell the info but it doesn't get it in the right order. The order is "try to openconnect, enter sudo pw if needed, then username, then password". <code>pexpect</code> would be good, since it can tell if you need your <code>sudo</code> password or not, but isn't working:</p>
<pre><code>#!/usr/bin/env python
# coding: utf-8
import os, sys, subprocess, time, re, pexpect
from my_scripting_library import *
child = pexpect.spawn('sudo openconnect vpn.com')
# send sudo pw
child.expect('.*')
child.sendline(sudopw)
# send sn
child.expect('.*')
child.sendline('cchilders')
# send work pw
child.expect('.*')
child.sendline(vpnpw)
time.sleep(150)
</code></pre>
<p>Here is what it looks like when I perform these steps manually:</p>
<pre><code>cchilders:~/scripts/work_scripts [master]$ sudo openconnect vpn.com
[sudo] password for cchilders:
POST https://vpn.com
Attempting to connect to server 555.555.55.55:555
Please enter your username and password.
Username:
Password:
</code></pre>
<p>When I try to feed my <code>sudo</code> password by shell like I have before, the VPN times out and says</p>
<blockquote>
<p>SSL negotiation with vpn.com</p>
<p>Server certificate verify failed: certificate does not match hostname</p>
</blockquote>
<p>I use</p>
<pre><code>alias vpn='echo $MYPW | sudo -S openconnect vpn.com'
</code></pre>
<p>How can I send my <code>sudo</code> password, then my username, then my VPN password all in a row from a shell/python script? Thank you</p> | 1 |
Batch: Set password with special characters to variable | <p>So in batch there are a lot of special characters that are reserved and cause issues if you use them, if I want to set up a password like so:</p>
<p>SET PASSWORD="123%6!@##$^&*_-"</p>
<p>Some of these characters will be stripped after assignment for example the percent '%' character is interpreted as a parameter, is there a way to make batch see that as a string instead of interpreting special characters? no I cannot escape those special characters, this is basically a file that we tell the user to edit teh batch file and set the password.</p> | 1 |
How do I access methods attached to a Schema in mongoose | <p>I am experiencing some confusion regarding calling a method that I have attached to a schema in a project that I am working on. I am essentially accessing a document from the database and trying to compare the hashed password I have stored to the password that was submitted by the user on login. When I go to try and compare the password though, the method that I attached to the methods object of the schema is nowhere to be found. It doesn't even throw an error for me telling me that there is no such method. This is where I am setting the method on the schema:</p>
<pre><code>var Schema = mongoose.Schema;
var vendorSchema = new Schema({
//Schema properties
});
vendorSchema.pre('save', utils.hashPassword);
vendorSchema.methods.verifyPassword = utils.verifyPassword;
module.exports = mongoose.model('Vendor', vendorSchema);
</code></pre>
<p>The function I am using as the compare method is a utility function that I created called verifyPassword, which is held in a utility file. The code for that function is here:</p>
<pre><code>verifyPassword: function (submittedPassword) {
var savedPassword = this.password;
return bcrypt.compareAsync(submittedPassword, savedPassword);
}
</code></pre>
<p>I try to verify the password like this:</p>
<pre><code> var password = req.body.password;
_findVendor(query)
.then(function (vendor) {
return vendor.verifyPassword(password);
});
</code></pre>
<p>I have promisified mongoose with bluebird promises if that makes any difference. I have tried a lot of things, but can't find any answer as to why nothing is happening when I try to invoke this method that I thought I had attached the schema. Any help would be greatly appreciated.</p> | 1 |
using System.DateTime.Now.Ticks for seed value | <p>I have started a wireless sensor network simulation code but I don't understand the meaning of the <code>seed</code> and what is the return value of <code>System.DateTime.Now.Ticks</code> in the method below.</p>
<pre><code>public void Reset(bool bNewSeed) {
// this function resets the network so that a new simulation can be run - can either be reset with a new seed, or with the previous seed (for replay.)
this.iProcessTime = 0;
this.iPacketsDelivered = 0;
foreach (WirelessSensor sensor in aSensors) {
sensor.iResidualEnergy = sensor.iInitialEnergy;
sensor.aPackets = new ArrayList();
sensor.iSensorRadius = iSensorRadius;
sensor.iSensorDelay = 0;
foreach (WirelessSensorConnection connection in sensor.aConnections) {
connection.iTransmitting = 0;
connection.packet = null;
}
}
aRadar = new ArrayList();
if (bDirectedRouting == true)
SetRoutingInformation();
iLastUpdated = iUpdateDelay;
if (bNewSeed == true)
this.iSeed = (int) System.DateTime.Now.Ticks;
r = new Random(iSeed);
}
</code></pre> | 1 |
MessageException: Current version is too old. Please upgrade to Long Term Support version firstly | <p>I downloaded SonarQube 5.3, configured the <code>sonar.properties</code> file, downloaded the JDBC driver for MSSQL (I'm using SQL Server 2012 and SQL JDBC 4.2), created a user with all grants in my SQL Server 2012 instance with database <code>sonar</code>.</p>
<p>Then I execute <code>startSonar.bat</code> and this throws the following error:</p>
<pre><code>2016.01.22 13:57:57 INFO web[o.s.s.p.ServerImpl] SonarQube Server / 5.3 / 8db783e62b266eeb0d0b10dc050a7ca50e96c5d1
2016.01.22 13:57:57 INFO web[o.sonar.db.Database] Create JDBC data source for jdbc:sqlserver://localhost;databaseName=sonar
2016.01.22 13:57:59 ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
org.sonar.api.utils.MessageException: Current version is too old. Please upgrade to Long Term Support version firstly.
2016.01.22 13:57:59 INFO web[jruby.rack] jruby 1.7.9 (ruby-1.8.7p370) 2013-12-06 87b108a on Java HotSpot(TM) 64-Bit Server VM 1.8.0_66-b18 [Windows 7-amd64]
2016.01.22 13:57:59 INFO web[jruby.rack] using a shared (threadsafe!) runtime
2016.01.22 13:58:05 ERROR web[jruby.rack] initialization failed
org.jruby.rack.RackInitializationException: java.lang.NullPointerException
at org.jruby.rack.RackInitializationException.wrap(RackInitializationException.java:31) ~[jruby-rack-1.1.13.2.jar:na]
at org.jruby.rack.RackApplicationFactoryDecorator.init(RackApplicationFactoryDecorator.java:98) ~[jruby-rack-1.1.13.2.jar:na]
at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:50) ~[jruby-rack-1.1.13.2.jar:na]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4720) [tomcat-embed-core-8.0.18.jar:8.0.18]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154) [tomcat-embed-core-8.0.18.jar:8.0.18]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.0.18.jar:8.0.18]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [tomcat-embed-core-8.0.18.jar:8.0.18]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) [tomcat-embed-core-8.0.18.jar:8.0.18]
at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_66]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_66]
--- and then creates a cascade of errors ---
</code></pre>
<hr>
<p>This is what's in the <code>sonar.properties</code> file:</p>
<pre><code># DATABASE
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar
# TCP port for incoming HTTP connections. Disabled when value is -1.
sonar.web.port=4950
</code></pre>
<hr>
<p>All I see is "Current version is too old. Please upgrade to Long Term Support version firstly." but... upgrade what? </p> | 1 |
Rails 5 - Error during WebSocket handshake: 'Connection' header value must contain 'Upgrade' | <p>I'm currently trying to deploy an application using Rails 5.0.0.beta2 but when I load the application in my javascript console I am seeing</p>
<blockquote>
<p>WebSocket connection to 'wss://example.com/cable' failed: Error during WebSocket handshake: 'Connection' header value must contain 'Upgrade'</p>
</blockquote>
<p>I'm using Apache/Passenger as the web server.</p>
<p>Has anyone else run into this issue and if so how did you solve it?</p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.