text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
ejabberd compile error
I'm a huge erlang noob, and while compiling ejabberd, I get this error:
make[1]: Entering directory `/usr/src/ejabberd-2.0.5/src/mod_muc'
/usr/local/bin/erlc -W -I .. -pz .. -o .. mod_muc_room.erl
Function: '-process_admin_items_set/4-fun-0-'/2
./mod_muc_room.erl:none: internal error in v3_codegen;
crash reason: {{case_clause,
{'EXIT',
{function_clause,
[{v3_codegen,longest,
[[{ker39},{ker38},{ker37},{ker36},{cor36}],
[]]},
{v3_codegen,longest,2},
{v3_codegen,sr_merge,2},
{v3_codegen,match_cg,5},
{v3_codegen,guard_match_cg,6},
{v3_codegen,guard_cg,5},
{v3_codegen,'-guard_cg_list/6-anonymous-0-',4},
{v3_codegen,flatmapfoldl,3}]}}},
[{compile,'-select_passes/2-anonymous-2-',2},
{compile,'-internal_comp/4-anonymous-1-',2},
{compile,fold_comp,3},
{compile,internal_comp,4},
{compile,internal,3}]}
make[1]: *** [../mod_muc_room.beam] Error 1
make[1]: Leaving directory `/usr/src/ejabberd-2.0.5/src/mod_muc'
make: *** [all-recursive] Error 1
What would cause this?
This is an internal compiler bug in R13A - it has been fixed in the R13B snapshot as of 2009-04-15_18. R13B-0 will be released on Wednesday 22nd April 2009, and mod_muc will compile fine with that.
However, ejabberd isn't quite R13B compatible yet - the ram_file_io server doesn't support the new unicode option in the IO server protocol, so you won't be able to successfully start ejabberd with R13B until that is fixed. Your best bet for now is R12B-5.
This is internal Erlang compiler bug. Please upgrade your Erlang runtime. Probably Erlang R12B-5 is the best choice.
Quick search shows this email from the Erlang/OTP team. It is states that the bug existed before R12B-0, so it is probably fixed in newer releases.
Erlang R12B-5 is available here:
Ubuntu - use Jaunty packages
Debian - use packages from Sid
Windows - use packages from http://erlang.org/download.html
other - figure out on your own :)
| common-pile/stackexchange_filtered |
What does "%:" (percent colon) mean in C?
In one of my courses I've been given this cryptic c code.
%:define BBRACE (
%:define BRACEE )
%:define CCURLY_BRACE {
%:define CURLY_BRACEE }
%:define SEMICOLON ;
%:define COMMA ,
int main BBRACE int argc COMMA char *argv<::> BRACEE CCURLY_BRACE return 1^2^3^4^5^6^7 SEMICOLON CURLY_BRACEE
Its not that complicated but I've never seen %:define ... is there any difference to #define ...? I found nothing about %:online.
Same goes with char *argv<::> but I don't know if this really deserves a second question.
I think the macros are even worse than the digraphs. Blech!
In the spirit of the thing, it should be %: define CCURLY_BRACE <%
Or better yet, ??=define CCURLY_BRACE ??<, and return 1 ??' 2 ??' 3 ??' 4 ??' 5 ??' 6 ??' 7 SEMICOLON
| common-pile/stackexchange_filtered |
Haskell (Aeson) : How to construct a record from JSON with additional values
I have a record that I want to construct with some values from a JSON string as well as some additionally provided values.
For example - given the following record:
data MyRecord = MyRecord { a :: String, b :: Int, c :: String }
I want do define a function:
createMyRecord :: String -> String -> Maybe MyRecord
createMyRecord json cValue = ???
Which I want to be able to call like so:
createMyRecord "{\"a\": \"a value\", \"b\": 100}" "c value"
Currently, I'm doing this by use Aeson to create the record with defaults (i.e. empty strings and zeros) for the values which don't come from the JSON. I then create a new version of the record with the other fields updated. Something like this:
instance FromJSON MyRecord where
parseJSON = withObject "MyRecord" $ \o -> do
valueA <- o .: "a"
valueB <- o .: "b"
return MyRecord { a = valueA, b = valueB, c = "" }
createMyRecord :: String -> String -> Maybe MyRecord
createMyRecord json cValue =
Aeson.decode json <$> (\r -> r { c = cValue })
This feels a bit cumbersome - I'd like to create the record in one go with all the values, rather than filling them in step by step. Is there a nicer way to do this with Aeson (I'm open to other libraries also) that anyone can recommend?
Thanks!
Do you want to build parseJSON? It doesn't have to be parseJSON...
abParser :: String -> Value -> Parser MyRecord
abParser valueC = withObject "MyRecord" $ \o -> do
valueA <- o .: "a"
valueB <- o .: "b"
return MyRecord { a = valueA, b = valueB, c = valueC }
createMyRecord :: ByteString -> String -> Maybe MyRecord
createMyRecord json valueC = decode json >>= parseMaybe (abParser valueC)
Excellent, thank you! I knew there was a simple solution but was struggling to work it out.
| common-pile/stackexchange_filtered |
Facebook Connect Integration with Spree Ecommerce
I am working on an existing rails application that is built on Spree version 0.11.0 and Rails 2.3.8. I am trying to integrate facebook connect but apparently because of spree application architecture I am not having a lot of success with facebooker and other plugins which are mostly used with Rails Applications..
Any idea how facebook connect is integrated with Spree E commerce ??
Thanks
You can find some extensions to do that on spree website.
But i don't know if they are compatible with Rails 2.3.8 and Spree 0.11.0 but it can give you some example of integration with Spree.
| common-pile/stackexchange_filtered |
Is my translation of unless into propositional logic correct?
I have the following sentences:
I won't go the library unless I need a book
p: I will go the library
q: I need a book
I replaced unless with if not as follows:
I won't go the library if I don't need a book
Then: $\lnot q \rightarrow p$ is my translation correct here?
And what if I paraphrased the sentence to the following:
If I won't go the library then I (don't) need a book.
$\lnot p \rightarrow \lnot q $
Would it still be correct?
If $p$ stands for "I will go the library", then "I won't go the library" must be $\lnot p$.
"$A$ unless $B$" is usually read in English as
$A$, if not $B$.
Thus, for I won't go the library unless I need a book, will be:
I won't go the library, if I do not need a book.
With:
$p$: I will go the library
$q$: I need a book
will be:
$\lnot q \to \lnot p$
that is the same as:
$p \to q$.
$\lnot q \to \lnot p$
is not equivalent to:
$\lnot p \to \lnot q$,
and this is consistent with the fact that:
If I won't go the library, then I don't need a book
is not the same as the previous:
I won't go the library, if I do not need a book.
Trough the truth-functional equivalence between "if $B$, then $A$" and "not $B$ or $A$", we have that :
"$A$ unless $B$" is equivalent to "$B$ or $A$".
Let's say I replace unless with whenever in this sentence: "I go the the library whenever I need a book.", so basically the logical translation is: $p \rightarrow q$. Another solution would be: $\lnot p \rightarrow \lnot q$, however, not the same as the original sentence, but still correct. Correct me if I'm wrong? I can see different combinations here, but I can't tell the right one:
*whenever I don't need a book, I don't go to the library = $\lnot p \rightarrow \lnot q$
whenever I go the library then I need a book = $p \rightarrow q$
@direprobs - YES: "B when A" is "if A, then B". Thus, "I go the the library whenever I need a book", must be "If I need a book, then I go the the library", i.e. (with $p$ and $q$ as you defined them) again: $p \to q$. Thus, $\lnot p \to \lnot q$ is not correct.
I'm really having hard time trying to translate sentences into logic, consider this:
A =“Angelo comes to the party”;
B =“Bruno comes to the party”;
C =“Carlo comes to the party”.
“Carlo comes to the party only if Angelo and Bruno do not come”
So, if I write it this way: $(\lnot A \land \lnot B) \rightarrow C$, is it correct?
@direprobs - Yes, it is. "A only if B" is again: "if A, then B".
Therefore $(\lnot A \land \lnot B) \rightarrow C$ is the same as $C\rightarrow (\lnot A \land \lnot B)$.
@direprobs - NO; $p \to q$ and $q \to p$ are not equivalent; check with truth table.
I get you, $C\rightarrow (\lnot A \land \lnot B)$ is the equivalent of this sentence: "If Carlo comes to the party then Angelo and Bruno do not come” which is the converse.
Let's think about your sentence carefully:
I won't go the library unless I need a book.
This sounds like you hate the library, and that as a general rule of thumb, you should not be expected to be caught dead there, except for one extenuating circumstance (you need a book). Let's evaluate your proposed translations.
Translation 1 ($\neg q \to p$): If I don't need a book, then I'll go to the library.
This definitely doesn't make sense. After all, you hate libraries. And you don't even need a book!
Translation 2 ($\neg p \to \neg q$): If I won't go to the library, then I don't need a book.
This isn't quite as bad of a translation, but it doesn't necessarily follow from the original sentence. Perhaps the library is merely your last resort for getting a book, and so it's possible that there are other alternatives (like borrowing your friend's old copy, for example). Thus, you are able to successfully avoid a trip to the dreaded library and yet simultaneously satisfy your need for a book.
Correct Translation ($p \to q$): If I go to the library, then I need a book.
This works. There are only three possible combinations and one impossible combination:
Possible #1: You are not at the library and you don't need a book. (happens all the time)
Possible #2: You are not at the library and you need a book. (hopefully there are alternatives)
Possible #3: You are at the library and you need a book. (rarely happens, but you had no other choice)
Impossible: You are at the library and you don't need a book. (...then why are you there?)
Is it okay if I change the order of the sentence? "I play football when I am bored". p: I play football; q: I am bored. So basically: $p \rightarrow q$. What about: $\lnot p \rightarrow \lnot q$ or $q \rightarrow p$ ? I suspect the first one $\lnot p \rightarrow \lnot q$ is wrong, because I might not be bored but still play football!
| common-pile/stackexchange_filtered |
magento 2.4.2 shows /index of instead of site
magento fresh install shows index of instead of site.
Os : ubuntu 20.04
php:7.4
after your url add pub path like :- localhost/urlname/pub/
From Magento 2.4.2 need to setup virtual host.
is virtual host neccessary
already tried using pub path
I finally found an answer in apche configuration file need to give allowoveride all for the document directory
| common-pile/stackexchange_filtered |
Must the variadic arguments be the second parameter in a variadic function?
Debugging this code, I find the parameter "size" in the first position of my array structure.
Must the variadic arguments of a variadic function always be passed as the second parameter? In the code below, I commented my fix, which consists in skipping the first va_list value (and it worked):
void my_array_assign(struct my_array * array, int size, ...)
{
va_list arguments_pointer;
int i;
my_array_create(array, size);
va_start(arguments_pointer, size);
va_arg(arguments_pointer, int); // MyFix: do I really have to skip first parameter "size" here ?
for (i = 0; i < size; ++i)
{
array->data[i] = va_arg(arguments_pointer, int);
}
va_end(arguments_pointer);
}
I could not find the answer anywhere, because all the examples I found use just two parameters: the size, and the variadic arguments.
This is where I call the function:
int main(int argc, char *argv[])
{
my_array test;
my_array_init(&test);
my_array_assign(&test, 3, 0, 1, 2); // the call
/* ETC... */
Thanks in advance.
Many library examples exist with more than 1 fixed parameters like int sprintf(char * restrict s, const char * restrict format, ...);.
No, variadic functions in C can have an arbitrary but defined amount of fixed argument in first positions (but at least one fixed argument is required). See e.g. syslog(3) as an example. And read carefully stdarg(3).
I have a code in main.c of my MELT monitor, the function mom_debugprintf_at line 104 (of commit a37e36c...), it has 4 fixed arguments.
Thanks. Any idea why my fix works? Could it be a compiler issue? (Unfortunately, I'm using VS2010)
Use a debugger to find out. BTW, consider installing Linux, using gcc -Wall -g to compile and gdb to debug.
If only I could. Project specs. -_- I'm updating the question including the function call.
Note: As I recall, early C even allowed variadic functions with no fixed arguments. Not having that ability today is not much of a loss.
@chux: You can still declare a function as int foo() to leave the args unspecified, then call foo("abc", 0); and foo(1, 2, 3, 0); from the same compilation unit. That doesn't help you define it in C, I don't think, but it lets you call a fully-variadic function written in asm, like in this code-golf answer: How many arguments were passed?
@PeterCordes Interesting. I see, with your idea, how modern code could still effectively have a int foo(...). Of course some back channel is needed to determine the argument list.
@chux: yeah, as I said in my code-golf answer I linked, it could make sense if passing pointers to "boxed" objects, if that's the right term. A NULL terminator for the arg list like in execl(3) to mark the end of args then becomes a valid sentinel / terminator, if the other args have to be valid pointers. I think that's a plausible justification for that calling convention :P
@PeterCordes Aside: A NULL terminator for int foo(const char *path, const char *arg, ...) is trouble for highly portable code. It can be UB with foo(".", "hello", NULL); versus the more reliable foo(".", "hello", (void*)NULL);. Since NULL, the null pointer constant, may be an integer type or void*, foo(".", "hello", NULL); lacks a conversion to pointer should NULL be some integer. See last part of this
@chux: Oh right, 0 is a valid definition of NULL. I was talking about an asm calling convention (ABI), but good point that you might have to write different C source to make sure the caller compiles to asm that passes the binary representation of a NULL pointer. Potentially problematic on platforms where int is smaller than void* and high garbage is allowed in arg-passing slots. x86-64 SysV is like that, but IDK if any compilers define NULL as 0 instead of ((void*)0) or something.
| common-pile/stackexchange_filtered |
Defined function raises TypeError when tried to be accessed after module.exports
So I followed a udemy course on JS and during the making of an app he writes the code that is written bellow. When I come to run the code an error is raised saying "TypeError: this.validate is not a function". I tried different ways of exporting User and sometimes it told me that it cannot read User as a constructor which is what I want it to be. I have been on this for the past 4 hours and I am still unable to figure out how it works. The whole file is required by other files. When on these other files I create an instance of the object like below. It works although the .push method of an array cannot be accessed(error message pops up)when I call the pushError function
const User = require('../models/User.js')
let user = new User(req.body);
//I can then run the .validate function
user.validate();
//But in that function another error raises that says that the
//"push cannot be accessed in undefined"
//And it leads me to think that during the construction the
//empty list becomes undefined????
let User = function(data) {{
this.username = data.username;
this.mail = data.email;
this.password = data.password;
this.errors = [];
}
}
User.prototype.validate = function(){
if(this.username.replace(" ","") == ""){pushError("Username")}
if(this.password == ""){pushError("Password")}
if(this.mail.replace(" ","") == ""){pushError("Email")}
}
User.prototype.register = ()=>{
//Step #1: Validate user Data
this.validate();
//Step #2:If validated store data to DB
}
function pushError(str){
this.errors.push(`You must provide a valid ${str}.`);
};
module.exports = User;
If you read through all this thank you!
The problem is that your pushError function is in no way related to the User instance you are creating.
Inside pushError, this is not the new User object you're attempting to create, hence this.errors is undefined, and you cannot call push on undefined.
Also, writing register as an arrow function instead of a regular function makes it lose the value of this (this becomes that of the enclosing context, window in a browser or global in Node.js).
There three steps involved to solve this.
First you should rewrite pushError as part of User's prototype chain, like so:
User.prototype.pushError = function(str) {
this.errors.push(`You must provide a valid ${str}.`);
};
Second, you should use this.pushError instead of pushError in validate:
User.prototype.validate = function() {
if (this.username.replace(" ", "") == "") {
this.pushError("Username");
}
if (this.password == "") {
this.pushError("Password");
}
if (this.mail.replace(" ","") == "") {
this.pushError("Email");
}
}
Third, write register as a regular function:
User.prototype.register = function() {
//Step #1: Validate user Data
this.validate();
//Step #2:If validated store data to DB
}
That should do it. Now, a few additional comments and resources. It might help you to:
Dig into JavaScript Objects on MDN, especially the Object prototypes section.
Write your code as an ES6 class, which is a more "modern" way to do the same thing: this article gives examples of how to write things the "prototype way" or with classes.
Learn more about the differences between regular and "fat arrow" functions in this article.
I see thank you. But how do I fix the error I get when I try to call the "this.validate()" function in the User.prototype.register (which says that this.validate isn't a function)? Again thank you for the help you have provided already I appreciate that!
I edited my answer, the third point should solve your problem. Cheers!
Glad my answer helped! Please consider accepting it :).
| common-pile/stackexchange_filtered |
How to find the shortest path between two nodes within array of objects?
I have 10,000+ data (Users) coming from an API in JSON format and given two nodes (i.e. 2 Users), I would like to find the shortest path between two Users.
When I realized that to find the shortest path, I could use Dijkstra's algorithm, but then to do that, I have to create a graph which is not sufficient with 10,000+ data.
For example, I make an API request
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
)
Where each user is an object
{
"name": "Leanne Graham",
"address": {...}
},
"website": "hildegard.org",
"company": [
"Romaguera-Crona",
"Google",
"Facebook"
]
}
And the problem is to see how two users are related to one another based on the company that they work for
I simply can't start on this because the data is so huge. I would just like to know, how can we go about this? Do we create a graph and apply Dijkstra's algorithm?
All I've done is to really loop through each User and check companies array.
Users.filter(user => user.companies.include([...]))
I think this question is also related to database not only javascript.
I think you should construct a graph with a vertex for each user and each company, then go through the list of users and add an edge between the user vertex and the vertices of all companies belonging to the user data. Then run the shortest path algorithm on this graph. I cannot help with the implementation, I don't know if there is a library for graph theory in javascript.
When you get the data from the API, are you using that data only once for 2 users or will you be accessing it multiple times? I am no expert in this field, but if you are accessing it multiple times then one idea that comes to mind is to convert the array into an indexed map where the index is the persons name. Once you have that you can get a person's information by their name without having to loop through an array. It's just an idea, I don't know how that holds up against other options.
@SamHerrmann I'm only using it once.
As far as I can tell, this is the original problem that you reduced to the question in How to create edges between nodes that have similarities. Your reduction is useful, but without knowing the nature of the data, namely, that it represents companies a person worked for, the problem becomes more general. Because this is real-life data, we can assume some things about it, like users on average don't have more than 10 job entries, and not all users have worked at the same company. This means the graph will be rather sparse.
To construct the users graph, you can go with my second suggestion from the other post:
Build a map from a company name to the set of all users that have worked for this company
Iterate over company names, iterate over all pairs of users that have worked for each company, and connect them with an edge if they aren't connected yet
This can still be a rather large graph: for 10k users you might end up with a million edges if users have worked with 100 other users on average. However, it's nothing a modern computer can't store in RAM. I'm not sure how memory-efficient Javascript is though - if you are open to switching to a more performant language, you could consider that option.
Now you have a graph and want to find a shortest path between two nodes (repeatedly, I assume). Note that since your graph does not have weights, Djikstra's algorithm is not necessary. You can run a BFS which works in O(N+M) time, where N is the number of users and M is the number of edges. For a million edges, it could comfortably run within a second in Java, but might take several in Javascript.
| common-pile/stackexchange_filtered |
VS Code C++ issue
I tried to compile a cpp file using VScode, but I have got an issue. The tdm-gcc have already added to environment variable. I tried to reboot my computer but it didn't work. Here is the error.
error:
/usr/bin/bash: D:TDM-GCC-64bing++.exe: command not found
The terminal process terminated with exit code: 127
You must ensure your Windows System PATH has the full path to your MinGW install directory, for example c:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin
I have added D:\TDM-GCC-64\bin to the system path, isn't it correct?
Q: Do you have TDM-GCC-64bing++.exe in your D:\TDM-GCC-64\bin folder? Q: Why does the error say D:TDM-GCC-64bing++.exe if your %PATH% has D:\TDM-GCC-64\bin? Where is "D:" coming from?
I just have g++.exe in the bin folder
I have encountered the exact same problem as yours and I think I found a fix.
You probably have Git Bash as your default integrated shell in VSCode in Windows. As the shell parses the path it removes the slashes /. To fix it, you should surround any path with \" that is found in your tasks.json. This forces the shell to interpret the path correctly. Attached is the args of my tasks.json. Hope this helped.
"args": [
"-g",
"-Wl,--stack,256000000",
"-Wl,--heap,256000000",
"\"${file}\"",
"-o",
"\"${fileDirname}\\${fileBasenameNoExtension}.exe\"",
"-std=c++11",
"-O2",
],
| common-pile/stackexchange_filtered |
CDI + JSF does not work
I created a simple Maven project in Eclipse.
My container is Glassfish 4.
First I added the following dependencies:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maven_cinema</groupId>
<artifactId>maven_webapp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>maven_webapp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>maven_webapp</finalName>
</build>
</project>
Then I created an empty beans.xml in the WEB-INF folder.
Then in the project properties I changed the Java version to 1.8.
Then Dynamic Web Module to 3.1.
Then enabled JavaServerFaces 2.2. (I downloaded the Mojarra library.)
This is my model:
package model;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class LoginModel implements Serializable {
private static final long serialVersionUID = 1L;
private String name = "Maven";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
When I try to bind the property in a JSF page:
<body>
<h:outputText value="#{loginModel.name}" />
</body>
The body is empty.
But when I do something like:
<h:outputText value="abc" />
It works.
So it must be the CDI.
What do I have to configure?
I don't see any obvious error, try with mvn package and then deploy the war manually to check if the problem is not eclipse.
anything in the faces-config? It may be a mixup of annotations: http://stackoverflow.com/questions/4347374/backing-beans-managedbean-or-cdi-beans-named - or some missing bean resolver in faces-config?
Do you see any errors in console when opening a page?
Is that beans.xml truly empty or does it contain ? And did you check what is actually deployed to the server? Your project may be 100% correct but if the deployment configuration is then wrong it still won't work.
A beans.xml is not needed for this to work. You should add your web.xml to the question.
The beans.xml is the trigger file to get the CDI implementation to scan for beans in that module. If you don't add the beans.xml in the proper place (WEB-INF for web modules, META-INF for jar modules), no beans will be registered.
I tried Java 8 with GF 4 resulting in some strange behavior (especially on list sorting), maybe it's related. Try to switch back to 7: compile your war and run GF with java 7 binaries, using java 8 with lower compiler level could not work.
You should use glassfish 4.1 with java-8. Not sure if it solves your problem..
| common-pile/stackexchange_filtered |
I am attempting to move from mediainfo CLI to pymediainfo but I am having a difficult time getting the correct information
I use the MediaInfo CLI to write up some basic information from groups of video files. I currently use a batch file that runs a MediaInfo CLI template. Here is a template (I call it "template.txt'):
General;%FileSize/String%" & "%Duration/String%\r\n
Video;%BitRate/String%\r\n
Audio;%BitRate/String%
I call on it with a batch file (template.bat):
For %%F IN (*.mp4) do ("C:\Program Files\MediaInfo CLI\MediaInfo.exe" --Inform=file://"F:\template.txt"
"%%F" >"%%~dpnF.txt")
Here is the python command I am attempting to replace the CLI with:
from pymediainfo import MediaInfo
media_info = MediaInfo.parse("events.mp4")
general_track = media_info.general_tracks[0]
video_track = media_info.video_tracks[0]
audio_track = media_info.audio_tracks[0]
print(
f"{general_track.other_file_size} & {general_track.other_duration}\n"
f"{video_track.other_bit_rate}\n"
f"{audio_track.other_bit_rate}"
)
There is plenty of data I can extract from the template that works fine with pymediainfo but I cannot get any of the 'String' data to work. For example, the pymediainfo equivalent of '%FileSize%' is 'file_size' and those both list the size in bits instead of MiB or GiB. For 1 of the videos I am attempting to write up a .txt file for the %FileSize/String% option in the CLI brings up the listing I am looking for (in this case 812 MiB). When I try using pymediainfo the only options I can find are 'file_size' which is 851764225 or 'other_file_size' which gives you ['812 MiB', '812 MiB', '812 MiB', '812.3 MiB']. Is there any way to select 1 of the 'other_file_size' options instead of all 4? Something like 'other_file_size_1'? I know that does not work, but some way to tell pymediainfo to only use the 1st 812 MiB in this case vs listing all 4. All of the CLI 'String' options seem to have this same issue when using pymediainfo.
I have spent hours searching the internet for a solution but I have not been able to find 1. I am assuming there is a very simple option to choose which data pymediainfo will select, but I cannot find anything about it on the internet. I have run a python command to display all the available pymediainfo data to determine the proper language but again, I can only find the "other_...." which I am hoping there is a way to tell it which 'other' I want to select. Thank you for any assistance
The solution was simple, not sure how I missed it. Just add [#] after the request to inform pymediainfo which data you are looking for. To get the '812 MB' from the previous case, I just tell python I am looking for the 1st data entry that results from the command: {general_track.other_file_size}. To direct python to use the 1st entry, I add [0] to the end of the command: {general_track.other_file_size[0]}.
I don't know for pymediainfo, but FYI with Python binding of MediaInfo you can use the exact same field names than with the CLI, example.
| common-pile/stackexchange_filtered |
Same DbContext shared for multiple HTTP requests
I'm receiving the following exception when two concurrent requests are sent to my ASP.NET MVC web application. I simulated this by logging in from desktop and mobile at the same time.
There is already an open DataReader associated with this Command which
must be closed first.
I am using Autofac to register DbContext, Repositories and Services
builder.RegisterType<DbContext>().As<IDbContext>().Named<IDbContext>("appdb").InstancePerRequest();
builder.RegisterType<LogDbContext>().As<IDbContext>().Named<IDbContext>("applogdb").InstancePerRequest();
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerRequest();
Services are also being registered to be created for every unique HTTP request.
builder.RegisterType<ProductService>().As<IProductService>().InstancePerRequest();
builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerRequest();
builder.RegisterType<ProductLineService>().As<IProductLineService>().InstancePerRequest();
builder.RegisterType<PatientService>().As<IPatientService>().InstancePerRequest();
builder.RegisterType<CommonService>().As<ICommonService>().InstancePerRequest();
My understanding is that I'm receiving the error because the same DbContext instance is being shared between the requests (root scope).
This does not make sense because I have registered my DbContext instance to create a unique instance for every HTTP request.
The only singleton object I have registered is the cache manager class.
Could this be because I have named my DbContext as 'appdb' and each request received the same instance? Edit= Doesn't have any impact
Can you please provide your connection string?
@StephenReindl <add name="sqlserver" providerName="System.Data.SqlClient" connectionString="Data Source=<IP_ADDRESS>;Initial Catalog=appdb;Integrated Security=False;Persist Security Info=False;User ID=abc;Password=123;Enlist=False;Pooling=True;Min Pool Size=1;Max Pool Size=100;Connect Timeout=30;User Instance=False" />
I have researched about MultipleActiveDataSets and setting that to true will solve it. However, I still don't understand why I am receiving the error when DbContext is registered as InstancePerRequest.
The common cause is that EF is materializing a list of entities and lazy loading is triggered during that process. Also happens in single-threaded environments.
After spending 10 hours on thinking it was EF related, I decided to look at how I was resolving IDbContext.
The problem was I was not resolving IDbContext from the HTTP request container which is named 'AutofacWebRequest`. It was not creating an instance for every HTTP request, hence causing the error. This was a dependency injection related issue.
As mentioned in your comment, please use MultipleActiveDataSets = true even if you set InstancePerRequest.
You are creating an instance per request for the DbContext, but the SQL server interface shares the same connection over several threads to reduce resource usage.
In addition, EF is sharing resources for lazy loading (see also @gert-arnold's comment)
| common-pile/stackexchange_filtered |
Can I have a Interface in method?
I know that that on can have a class declaration in a method of class.
Eg. We can have anonymous class declaration for event handling in a method body.
But I want to know that same way can I have Interface declaration in a method in a class.
What is use of that?
After reading fastcodejava's post, I think I misunderstood the OP. Do you mean inner/anonymous-interface within a method?
Please give an example of what you mean.
I' assuming you are refering to returning an interface for a method?
Short answer: Yes.
Why?
Here's a good post.
Why we return type Mostly Interface rather than Class?
Excerpt:
The benefit is that returning an
interface makes it possible to change
the implementation later on. E.g., you
might decide after a while that you'd
much rather use a LinkedList instead
of an ArrayList.....
I don't think you can declare an Interface inside a method. Why would you want to?
You can only define an anonymous inner class.
nested interfaces are implicitly static and cannot be defined in a method body.
No. why don't you just write one, compile, and see for yourself?
Suppose an interface can be declared inside a method, it wouldn't be accessible outside. It's hard to imagine the usefulness of such an interface confined in a block. A local class on the other hand can be useful since it contains concrete implementation.
You can do that, a well known example is the Comparator<T> interface.
For example:
List<Person> persons = personDAO.list();
Collections.sort(persons, new Comparator<Person>() {
// Anonymous inner class which implements Comparator interface.
public int compare(Person one, Person other) {
return one.getName().compareTo(other.getName());
}
});
Some may argue against this and tell that it rather belongs in the Person class, so that you don't need to implement it again and again whenever needed. E.g.
public class Person {
// ...
public static final Comparator<Person> ORDER_BY_NAME = new Comparator<Person>() {
public int compare(Person one, Person other) {
return one.getName().compareTo(other.getName());
}
};
}
which can be used as follows:
Collections.sort(persons, Person.ORDER_BY_NAME);
I think what you have in your example is an anonymous class which is an instance of the interface Comparator. But I think the OP's question was whether an interface declaration can exist inside a method, which is not possible in Java. Or is it I miss something here ?
Hmm this doesn't make any sense. But I think you're right that it was actually his question. I'd be curious where he wanted to use it for. To get better answers he at least need to edit his question with a concrete example of what he's trying to achieve.
| common-pile/stackexchange_filtered |
Get the value of the variable url to iframe
I would like to help see the example:
http://www.siteexemple.com/pagina.php?url=http://www.variablevalue.com
In my php: pagina.php I have the iframe:
<Iframe src = "" width = "100%" height = "100%" scrolling = "no" frameborder = "0" allowFullScreen = "true"> </ iframe>
Now how do I get the value of the variable `` urlto the iframe src = ""
the result I would like to get is:
<Iframe src = "http://www.variablevalue.com" width = "100%" height = "100%" scrolling = "no" frameborder = "0" allowFullScreen = "true"> </ iframe>
Already tried:
<Iframe src = "<? Php echo $ url;?>" Width = "100%" height = "100%" scrolling = "no" frameborder = "0" allowFullScreen = "true"> </ iframe>
But it did not work, I thank you in advance for attention thank you!
use javascript to get src
where did you define $url in the php?
Use $_GET["url"] instead of $url.
<Iframe src = "<?php echo $_GET["url"]; ?>" Width = "100%" height = "100%" scrolling = "no" frameborder = "0" allowFullScreen = "true"> </ iframe>
Just a note that if you contain un-encoded URL as variables might cause some escape exceptions. I'll suggest to use urlencode() and urldecode() to process these variants in advance.
| common-pile/stackexchange_filtered |
Where do I put custom capistrano recipes?
I'm trying to manage database.yml using capistrano, following this post:
http://www.simonecarletti.com/blog/2009/06/capistrano-and-database-yml/
I'm running into trouble including the code used in the post above. I've named this file cap_database.rb but I don't where to save it, or how to load it in deploy.rb.
I've tried placing it in lib/capistrano and added it to deploy.rb with this line:
require 'capistrano/cap_database'
and then I get this:
$ cap deploy:db
/home/daniel/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- capistrano/cap_database (LoadError)
Why can't it find the file?
where have you placed cap_database.rb ?
@AnkitG I've tried placing it in a bunch of places:
lib/capistrano
lib/capistrano/recipes
config/recipes
config/deploy
etc.
Upon further inspection, it seems like capistrano uses its own require/load methods, and use a minimal value for load_paths (from the looks of it, it just includes the gemdir for capistrano, which is not where I want to place my own code :))
For now I've resorted to your previous suggestion, I've just included the entire script as part of deploy.rb, but this isn't a solution I'm happy with. I should be able to load files like I do in any other script.
it's just a shot but try
bundle exec cap deploy:db
For recipes at the gem level, put your custom recipes into GEMDIR/CAPGEMDIR/lib/capistrano/recipes
If you want to include additional files into your app's deploy.rb, then you can do it using this method:
require in capistrano deploy.rb cannot find file
I know this is a bit late but here goes anyway.
If you store cap_database.rb in config/recipes, it can be included in deploy.rb using load config/recipes/cap_database.
| common-pile/stackexchange_filtered |
SQL find bad combination
I have the following table
item_id dep_id value_id
67 20 3
67 20 2
68 20 8
68 20 8
68 20 8
97 16 3
I need to make sure that the table has the same value_id for each item in each department_id. In other words I must not have an item_id with different value_id for a given department_id.
In the above example the first two rows are invalid because the item 67, in department_id 20 appears with different value_ids (3,2)
Is there a query to perform in order to catch the "anomalies"? I am using SQL Server 2005
Thanks in advance!
How do you decide which one is the correct value_id ??
@M.Ali - yes, actually he want to only get anomaly. probably someone else deal with the resolution of duplicates.
This will list you the (item_id, dep_id) pairs where there are different valud_is's.
select
item_id,
dep_id
from
table
group by
item_id,
dep_id
having
count(distinct value_id)>1
DISTINCT is usually more expensive, this might use less resources (and additionally shows two different values):
select
item_id,
dep_id,
min(value_id),
max(value_id)
from
table
group by
item_id,
dep_id
having
min(value_id) <> max(value_id)
| common-pile/stackexchange_filtered |
Can you splice a single object property in an array of objects?
I'm wondering if it's possible to mutate a specific object property in an array of objects using the splice method.
For example
const array = [
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Pluto'}
]
array.splice(1, 1, /* Can I mutate [1].body without replacing the whole object? */)
Expected output would be:
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Jupiter'}
What is your expected output?
Using splice method, no.
You could take a property accessor with the array, index and property without splicing the array.
const array = [{ name: 'Object 1', body: 'Hello world'}, { name: 'Object 2', body: 'Bye Pluto'}];
array[1].body = 'Bye Mars!';
console.log(array);
If you use splice to do this.
const array = [
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Pluto'}
];
array.splice(1, 1, {...array[1], body: 'Bye Jupiter'})
console.log(array)
Of course you can do it easy.
const array = [
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Pluto'}
]
array[1].body = 'Bye Jupiter';
console.log(array)
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. So you can never use splice to update objects in the array without removing it.
What you want to achieve can easily be done with
const array = [
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Pluto'}
]
array[1].body = 'Bye Jupiter 1'
console.log(array)
array[1]['body'] = 'Bye Jupiter 2'
console.log(array)
const array = [
{ name: 'Object 1', body: 'Hello world'},
{ name: 'Object 2', body: 'Bye Pluto'}
]
array[1].body = "New Content"
console.log(array)
| common-pile/stackexchange_filtered |
Nested div is centered horizontally and vertically in React but not in HTML
Ideally the parent-div should be visible like following (I confirmed it by running index.html file attached at the end)
But when I am running my react application, I am seeing the parent-div as:
I am not sure why is this happening. I could not find much information on this. May be I need to learn more about certain concepts but not sure what! Can someone please help me with this.
.centered-div {
position: absolute;
top: 50%;
left: 50%;
margin-top: calc((0.5*30vh)*-1); /* Half of the height */
margin-left: calc((0.5*30vw)*-1); /* Half of the width */
border: 1pt solid rgb(192, 184, 184);
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
height: 30%;
width: 30%;
}
.parent-div {
position: absolute;
box-sizing: border-box;
height: 70%;
width: 70%;
border: 1pt solid rgb(192, 184, 184);
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
}
<body>
<div class="centered-div">
<!-- Parent div without padding -->
<div class="parent-div">
<!-- Child div without top and left properties -->
</div>
</div>
</body>
There must be other styles in your React app. Did you use your browser's document inspector to look at it? It should be fairly apparent what adds the extra space or alignment.
Thanks for the direction. I have same div name (centered-div) in my Home.tsx but it has different css file(which has additional flex properties defined). When I am clicking a button in Home.tsx, I am redirecting to the page I shared in the question using window.location.href. So, it looks like because of the flex properties in Home.css, my current page's centered-div is inheriting those flex and causing spaces. I thought that the css classes in separate files are scoped, are they not?
Not in React. CSS scoping is a common request.
| common-pile/stackexchange_filtered |
JPA HIbernate - ManyToOne mapping - insert if not exists
I have the below 2 classes(entities).
Person Class
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE,
generator="person_id_seq")
@SequenceGenerator(name="person_id_seq", sequenceName="person_id_seq",
allocationSize=1)
private Integer person_id;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinColumn(name = "location_id")
private Location location;
}
Location Class
@Entity
@Table(name = "location")
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "location_seq_gen")
@SequenceGenerator(name = "location_seq_gen", sequenceName = "location_id_seq", allocationSize = 1)
@Column(name = "location_id")
private Long id;
@Column(name = "address_1")
private String address1;
@Column(name = "address_2")
private String address2;
@Column(name = "city")
private String city;
@Column(name = "state")
private String state;
@Column(name = "zip")
private String zipCode;
@Column(name = "location_source_value")
private String locationSourceValue;
public Location() {
}
public Location(String address1, String address2, String city, String state, String zipCode) {
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
public Long getId() {
return id;
}
public Long getId(String address1, String address2, String city, String state, String zipCode){
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getLocationSourceValue() {
return locationSourceValue;
}
public void setLocationSourceValue(String locationSourceValue) {
this.locationSourceValue = locationSourceValue;
}
}
What I want to be able to do is the following.
When I insert a new Person record, I will provide the addressLine1, addressLine2, city, state, zipcode and it should check in the Location table if the record exists. If it exists, then get the location_id from the Location table and insert the new Person record with the existing location_id. If it does NOT exist, create a new record in the Location table, get the location_id and use that as the location_id for the new Person record.
I believe this can be achieved with the appropriate JPA Hibernate annotations.
Currently, whenever I am inserting a new Person record, it is creating a new record in the Location table even if the Location exists.
Please help. Thanks in advance!
Have you overrided equals and hashCode methods? By this method you will add identifying each row in the table. You have specified annotations properly, but Hibernate can't determine if this row exists or not. Internally Hibernate uses Map, so equals and hashCode should solve your problem.
Thank you for replying. Please can you elaborate this with an example.
Please look into this link
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/persistent-classes.html#persistent-classes-equalshashcode
Here you can find why do you need override these methods and samples.
@Sergiy Rezvan I am facing the same issue, but I dont clearly understand what is specified either. Please elaborate on what changes should be made in the entity tables.
@SergiyRezvan Thank you for pointing to the documentation but it is not clear enough. Also, I tried the above example with a simple code https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-one-using-annotations-1.html. In this, if I give it to a constructor it works but it does not work when I set it using a setter method.
@SergiyRezvan any help please
| common-pile/stackexchange_filtered |
Comma usage and maintain succinctness
I have started my book with the words "The day I was born, Granny died." On reading all the comma rules this doesn't seem quite right. Should the comma be replaced by a semicolon? I wanted the first lines to be impactful, but perhaps I should just replace the line with something like "The day I was born is the day Granny died."? It's not as succinct as I would like, but grammatically correct.
Your original sentence is correct. Definitely do not replace the comma with a semicolon, as a semicolon connects two independent clauses and "[t]he day I was born" is not an independent clause.
Also, you can check the validity of "[t]he day I was born, Granny died" by inverting the clauses: "Granny died the day I was born." This makes sense, so your original does too.
Thank you - that clarifies - I was studying the Sussex Univ rules: http://www.sussex.ac.uk/informatics/punctuation/comma My sentence didn't seem to fall into any of the comma rules, and hence the confusion.
Look here. If you do a CTRL-F for comma, you will find that commas are used "to separate subordinate clauses from their main clauses, e.g. Although Wittgenstein came to disapprove of Russell's approach to philosophy, in his early phase he was strongly influenced by Russell's work" (bold emphasis mine). Review this Wikipedia entry for more information.
@JakeRegier The day I was born is not, however, a clause.
@phoog Please explain.
@JakeRegier it's an adverbial noun phrase. It has no predicate, as a clause must. The clause I was born modifies the day, but the fact that the phrase contains a clause doesn't make it a clause.
so - what is the consensus? Is the sentence still correct?
Would it be right to use a dash instead? So, "The day I was born -- Granny died"?
Your punctuation of the sentence works well. In the University of Sussex Guide to Punctuation, for example, the type of comma you used is called the bracketing comma. That type of comma setting off an introductory adverbial phrase is usual. In your example, however, the comma could be omitted without changing the meaning of the sentence, and so the use is a stylistic choice.
Your punctuation (with a comma after born) is faultless. Your wording "The day I was born" is prefatory to the main subject and verb of the sentence ("Granny died"). The comma marks the end of the introductory phrase, and it is entirely appropriate. Neither a semicolon nor an em-dash would work well here—the semicolon because it would negate the subordinate relationship of the introductory phrase to the main part of the sentence, and the em-dash because it would break the continuity between the intro phrase and the main phrase.
| common-pile/stackexchange_filtered |
$\exp$ of a stopping time is integrable
Let $B_t$ be a real Brownian motion started from zero. For $a> 0$, define $$\sigma_a:= \inf_{t\geq 0}~\{t: B_t-t\leq -a\}.$$
Then do we have $$E \left[\exp\left(\frac{\sigma_a}{2}\right)\right]<\infty~?$$
The motivation is the second part of this exercise. I have already done part 1 and the first part of part 2 (where $\lambda \geq 0$). The part I don't understand is extending $\lambda$ down to $-1/2$:
"The fact that this formula remains valid for $\lambda \in [−1/2,0[
$ can be obtained via an argument of analytic continuation."
If I don't know that expectation is finite I can't use analytic continuation.
Exercise 3.28 $\quad$ Let $(B_t)_{t \geq 0}$ be an ($\mathfrak{F}_t)$-Brownian motion started from $0$. Let $a > 0$ and $$\sigma_a = \inf \{t \geq 0 : B_t \leq t-a\}.$$
1. $\,$ Show that $\sigma_a$ is a stopping time and that $\sigma_a < \infty$ a.s.
2. $\,$ Using an appropriate exponential martingale, show that, for every $\lambda \geq 0$, $$E \left[\exp(-\lambda \sigma_a)\right] = \exp(-a(\sqrt{1+2\lambda}-1)).$$
The fact that this formula remains valid for $\lambda \in [-\frac{1}{2}, 0[$ can be obtained via an argument of analytic continuation.
3. $\,$ Let $\mu \in \mathbb{R}$ and $M_t = \exp \left(\mu B_t - \frac{\mu^2}{2}t\right)$. Show that the stopped martingale $M_{\sigma_a \wedge t}$ is closed if and only if $\mu \leq 1$. (Hint: This martingale is closed if and only if $E[M_{\sigma_a}] = 1$.)
Curious, which text is this from?
@SeanRoberson Le Gall Brownian Motion, Martingales, and Stochastic Calculus
Formula
By using the martingale $M_{t}=exp(\mu B_{t\wedge \sigma_{a}}-\frac{\mu^{2}}{2}t\wedge \sigma_{a})$, we get
$$1=E[M_t]=E[e^{\mu(\sigma_{a}-a)-\frac{\mu^2}{2}\sigma_{a} }1_{\sigma_{a}\leq t}]+E[e^{\mu B_{t}-\frac{\mu^2}{2}t }1_{\sigma_{a}\geq t}].$$
The first term converges to $E[e^{\mu(\sigma_{a}-a)-\frac{\mu^2}{2}\sigma_{a} }]$ by monotone convergence theorem. The second term, we claim goes to zero for some $\mu$. Since $\sigma_{a}\geq t$, we have $B_{t}-t\geq -a$ and so for $\mu\leq 0$
$$e^{\mu B_{t}-\frac{\mu^2}{2}t }1_{\sigma_{a}\geq t}\leq e^{-\mu a} e^{\frac{\mu}{2}(2 -\mu)t }1_{\sigma_{a}\geq t}. $$
This is bounded as long as $\frac{\mu}{2}(2 -\mu)\leq 0$ which follows from $0\geq \mu$. So also using that negative-drifted BM goes to negative infinity, the second term goes to zero by dominated convergence theorem.
Therefore, we are left with
$$E[e^{\frac{\mu}{2}(2 -\mu)\sigma_{a} }]=e^{\mu a}.$$
So by letting $-\lambda=\frac{\mu}{2}(2 -\mu)$, we get $\mu=1+\sqrt{1+2\lambda}$ or $\mu=1-\sqrt{1+2\lambda}$.
Analytic continuation: bounded
Here we consider the function
$$E(z):=E[e^{-z \sigma_{a}}]$$
for $Re(z)>-\frac{1}{2}$. First we need to show that this function is well-defined for all such $z$. As done in Le-Gall pg16 for the Gaussian case, we bound
$$|E[e^{-z \sigma_{a}}]|=|\int_{0}^{\infty}e^{-zs}\frac{a}{\sqrt{2\pi s^{3}}}e^{-(a-s)^{2}/2s}ds|\leq \int_{0}^{\infty}e^{-Re(z)s}\frac{a}{\sqrt{2\pi s^{3}}}e^{-(a-s)^{2}/2s}ds\leq c_{a}e^{b_{a}\sqrt{\frac{1}{2}+Re(z)}},$$
for some constants $c_a>0,b_a<0$ by using that
$$\int_{0}^{\infty}\frac{1}{s^{3/2}}e^{-a^{2}s-\frac{b^2}{s}}ds=\frac{\sqrt{\pi}}{b}e^{-2ab}.$$
Analytic continuation: extending the formula
This means that $E(z)$ is well defined. It is also holomorphic in the region $D=\{Re(z)>-\frac{1}{2}\}$ since we can apply Morera's principle over closed loops $C$
$$\int_{C}E(z)dz=E[\int_{C}e^{-z \sigma_{a}}dz ]=E[0]=0.$$
On the other hand, the RHS expression $e^{-a(\sqrt{1+2z}-1)}$ is similarly holomorphic in that region. But since $E(z)=e^{-a(\sqrt{1+2z}-1)}$ along the line $\lambda\geq 0$, the identity theorem implies equality throughout domain $D$.
So that means we have it for $\lambda\in (-\frac{1}{2},+\infty)$.
Extension to $\frac{1}{2}$
Here we simply apply the monotone convergence theorem
$$E[e^{\frac{1}{2} \sigma_{a}}]=\lim_{r\to \frac{-1}{2}}E[e^{-r \sigma_{a}}]=\lim_{r\to \frac{-1}{2}}e^{-a(\sqrt{1+2r}-1)}=e^{a}.$$
Thank you, I will try to understand this tomorrow.
Two questions:
Doesn't $e^{\mu B_{t}-\frac{\mu^2}{2}t }1_{\sigma_{a}\geq t}\leq e^{-\mu a} e^{\frac{\mu}{2}(2 -\mu)t }1_{\sigma_{a}\geq t} $ assume $\mu \leq 0$?
I don’t understand the last line. You say “the above constraints force $\lambda\in (0,\frac{1}{2}]$.” But when $\mu \leq 0 or \mu \geq 2$, we have $\lambda \leq 0$, right?
@famousmortimer I agree we just need $\mu\leq 0$.
Your approach is basically the way you do the first part of part 2. the challenge is extending lambda up to 1/2
but when $\mu \leq 0$, $\lambda$ is also $\leq 0$
sorry your lambda is the negative of the lambda in the exercise, so it may cause confusion. i hope it's clear what i'm saying
Where did you find this density for $\sigma_a$: $\frac{a}{\sqrt{2\pi s^{3}}}e^{-(a-s)^{2}/2s}$? Page 16 in my copy of Le Gall is some unrelated exercises, and I coudn't find it in the first two chapters.
this is the density for hitting time for Brownian motion with drift pg. 141 in Le Gall. (By symmetry of BM it works for negative $a$ too)
Ah! so 2 chapters after the exercise! I will add this to my short list of le gall errata. thank you for your help!
@famousmortimer I am not sure if it is a mistake. There might be some different approach that doesn't use the density.
| common-pile/stackexchange_filtered |
Define a relation $ \sim$ on $\mathbb{R}^2 \setminus (0,0)$ by $(a,b)\sim (c,d)$ if there is some real number x with $a=xc$ and $b=xd$.
Define a relation $ \sim$ on $\mathbb{R}^2 \setminus (0,0)$ by $(a,b)\sim (c,d)$ if there is some real number $x$ with $a=xc$ and $b=xd$.
I need to prove the relation is an equivalence relation and determine the equivalence classes.
Here's what I have started.
Reflexive: Let $(a,b) \epsilon \sim$, then $a=1\cdot a$ and $b=1\cdot b$. Thus $(a,b)\sim(a,b)$ and $\sim$ is reflexive.
Can I have a nudge to finish the rest?
Even more important though...can I some deeper intuition to their relation? Help with understanding that will help me determine the equivalence classes on my own.
Viewing $(a,b)$ as a vector from $(0,0)$ to $(a,b)$ then the relation says $V\sim U\iff V = xU$ is a scaling of $U$ by some real $x$ (necessarily $x\neq 0$ since $V\neq (0,0)$ by hypothesis). That this is an equivalence relation is equivalent to the fact that the scalars $\Bbb R\backslash0$ contain $1$ (reflexive) and are closed under inverses (symmetric) and multiplication (transitive) i.e. the scalars $\Bbb R\backslash0$ form a group.
Symmetry comes from the fact that you can divide by $x$ since neither $a$ or $b$ are $0$, and transitivity comes from considering the product of $x_1$ and $x_2$.
For what the equivalence classes are, think of $\mathbb{R}^2$ as the Euclidean plane, and imagine lines through the origin.
If $x = 0$ then we have $a = b = 0$, but we've forbidden that from the choice of set we're working on.
Then for symmetry I can say: If $(a,b),(c,d))\epsilon\sim$, then $ a=xc, b=xd$ and so $c=x^{-1}a, d=x^{-1}b$. Thus $\sim$ is symmetric.
Exactly. You will probably also want to include a line about why $x^{-1}$ exists.
Transitivity: If $(a,b), (c,d), (e,f) \epsilon \sim$, then
$a=xc, b=xd$
$c=xe, d=xf$
Thus, $a=x^{2}e, b=x^{2}f$.
Therefore, $\sim$ is transitive.
Yes, thanks. Since $x \epsilon \mathbb{R}, x^{-1} \epsilon \mathbb{R}$
@Denise Not quite, on both counts. Why would the $x$ for the first pair equal the $x$ for the second pair? And what if $x = 0$? Then $x^{-1} \notin \mathbb{R}$. Argue as to why $x \neq 0$ (see my first comment for why).
Got it! So in ~ two points are related if they are lying on the same straight line passing through the origin? Then the equivalence classes are composed of vectors (nonzero) which are scalar multiples of each other?
That's exactly right.
| common-pile/stackexchange_filtered |
Usage of input:hidden selector
Let's say we have two div with display:none style attribute like this :
<div id="dv_1" style="display:none;">
DIV - 1
<br />
<input type="radio" name="dv_1_radio_gender" value="male" checked="checked" /> Male
<input type="radio" name="dv_1_radio_gender" value="female" /> Female
<input type="hidden" name="dv_1_radio_gender" value="male" />
</div>
<div id="dv_2" style="display:none;">
DIV - 2
<br />
<input type="radio" name="dv_2_radio_gender" value="male" checked="checked" /> Male
<input type="radio" name="dv_2_radio_gender" value="female" /> Female
<input type="hidden" name="dv_2_radio_gender" value="male" />
</div>
As you can see, each div contains two radio buttons and one hidden input field.
If we try to set new value to hidden field like this :
$('input:hidden[name="dv_1_radio_gender"]').val('female');
The selector seems get all elements that has the same name inside a hidden (display: none) div and set value to 'female'.
if we change div with this first :
$(div).show();
Еhen everything works perfectly.
JSFiddle example.
So, here is my question: why does selector get all matched elements in a hidden div? Doesn't the syntax $('input:hidden[name="xxx"]') means to find input which is a hidden type?
I don't know what might be the problem but I've checked your code and it works like how you wanted it to be..
From docs for :hidden selector:
Selects all elements that are hidden.
Elements can be considered hidden for several reasons:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
Number 4 is what is all about: all <input>s are inside hidden <div>s. To select only <input> with type hidden, you can use input[type="hidden"].
Fiddle example.
This will select all inputs with name "dv_1_radio_gender" that are not visible, no matter what kind of inputs they are:
$('input:hidden[name="dv_1_radio_gender"]');
This second one will select all inputs of type hidden with name "dv_1_radio_gender", no matter if they are inside a hidden parent element or not:
$('input[type="hidden][name="dv_1_radio_gender"]');
| common-pile/stackexchange_filtered |
Docker Desktop 3.1.0 installation issue - access is denied
I am trying to install Docker Desktop to my Windows 10 Professional Build 19042 and receive an installation error even when trying to install as 'Administrator'.
Error: Component CommunityInstaller.ServiceAction failed: Failed to start service: Access is denied ...it is not clear to me what specifically Docker cannot access.
Curious to see if anyone has a solution to this issue.
You may need to add your account to the "docker-users" group. See
https://github.com/docker/for-win/issues/785, especially nfunky response on Aug 10, 2020. I used the following command and it resolved that problem for me where "username" is your Windows username:
net localgroup "docker-users" "username" /add
According to the documentation, first you should control the requirements based on your operating system. Next, uninstall the older versions. For example if you are using windows OS, look at this picture
and make sure these items are active in advance.
plus, make sure Hyper-V is installed and working (check the link above).
Finally, if you have this error message while opening the docker desktop:
You are not allowed to use Docker. You must be in the “docker-users” group
you should add your user to docker-users named group created under Computer Management/user and groups/groups. look at this link
| common-pile/stackexchange_filtered |
Getting a SyntaxError when running babel from babel-runtime/helpers/typeof-react-element.js (_symbol."for")?
Project Structure (src contains react component classes using jsx syntax):
root
- src/
- package.json
- webpack.config.js
Command I'm running: babel src --out-dir lib
And here is the error
SyntaxError: src/node_modules/babel-runtime/helpers/typeof-react-element.js: Unexpected token (5:62)
3 | var _Symbol = require("babel-runtime/core-js/symbol")["default"];
4 |
> 5 | exports["default"] = typeof _Symbol === "function" && _Symbol."for" && _Symbol."for"("react.element") || 60103;
| ^
6 | exports.__esModule = true;
npm ERR! Darwin 15.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build:lib"
npm ERR! node v5.7.1
npm ERR! npm v3.6.0
npm ERR! code ELIFECYCLE
npm ERR<EMAIL_ADDRESS>build:lib: `babel src --out-dir lib`
npm ERR! Exit status 1
here are my top babel devDependencies (not including plugins)
"babel-cli": "^6.7.7",
"babel-core": "^6.7.7",
"babel-loader": "^6.2.4",
Could this be a legitimate bug in babel? Or perhaps I need a different node version, dependency version? Any thoughts or advice would be greatly appreciated.
I would try removing them from you package.js file and try install with no version. npm install --save babel-cli babel-core babel-loader
Realized that a copy of node_modules somehow made it into my src folder. So babel was running against all of node_modules. Also simplified my babel.rc file to just this...
{
"presets": ["es2015", "react", "stage-1"]
}
After that it works fine. So the issue was either from babel running aginst something weird in node_modules or one of the many plugins I had manually specified before.
The error message is still really confusing but at least I don't think it was any fault of babel.
| common-pile/stackexchange_filtered |
Building a Word document containing two different tables
I am trying to generate a Word document with two different tables inside it. For this purpose I have two similar methods where I am passing word document reference and data object and table to the similar methods.
I am looking to make single generic method. So in different places I can use single method and passing parameters to it.
Method 1:
private static List<OpenXmlElement> RenderExhaustEquipmentTableDataAndNotes(MainDocumentPart mainDocumentPart, List<ProjectObject<ExhaustEquipment>> exhaustEquipment,Table table)
{
HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart);
var equipmentExhaustTypes = new Dictionary<string, List<ProjectObject<ExhaustEquipment>>>();
foreach (var item in exhaustEquipment)
{
string exhaustEquipmentName = item.TargetObject.Name;
if (!equipmentExhaustTypes.ContainsKey(exhaustEquipmentName))
{
equipmentExhaustTypes.Add(exhaustEquipmentName, new List<ProjectObject<ExhaustEquipment>>());
}
equipmentExhaustTypes[exhaustEquipmentName].Add(item);
}
List<OpenXmlElement> notes = new List<OpenXmlElement>();
int noteIndex = 1;
foreach (var exhaustEquipmentItem in equipmentExhaustTypes)
{
List<string> noteIndices = new List<string>();
for (int exhaustEquipmentConditionIndex = 0; exhaustEquipmentConditionIndex < exhaustEquipmentItem.Value.Count; exhaustEquipmentConditionIndex++)
{
var condition = exhaustEquipmentItem.Value[exhaustEquipmentConditionIndex];
var row = new TableRow();
Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript }));
if (exhaustEquipmentConditionIndex == 0)
{
row.Append(RenderOpenXmlElementContentCell(new Paragraph(
new List<Run> {
new Run(new RunProperties(), new Text(exhaustEquipmentItem.Key) { Space = SpaceProcessingModeValues.Preserve }),
superscriptRun
}), 1,
new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin {
LeftMargin = new LeftMargin { Width = "120" },
TopMargin = new TopMargin { Width = "80" } }
}));
}
else
{
row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } }));
}
row.Append(RenderTextContentCell(condition.TargetObject.IsConstantVolume ? "Yes" : "No"));
row.Append(RenderTextContentCell($"{condition.TargetObject.MinAirflow:R2}"));
row.Append(RenderTextContentCell($"{condition.TargetObject.MaxAirflow:R2}"));
if (condition.TargetObject.NotesHTML?.Count > 0)
{
foreach (var note in condition.TargetObject.NotesHTML)
{
var compositeElements = noteConverter.Parse(note);
var htmlRuns = compositeElements.First().ChildElements.Where(c => c is Run).Cast<Run>().Select(n => n.CloneNode(true));
notes.Add(new Run(htmlRuns));
noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture));
}
}
if (exhaustEquipmentConditionIndex == exhaustEquipmentItem.Value.Count - 1 && condition.TargetObject.NotesHTML?.Count > 0)
{
superscriptRun.Append(new Text($"({String.Join(',', noteIndices)})") { Space = SpaceProcessingModeValues.Preserve });
}
table.Append(row);
}
}
List<OpenXmlElement> notesSection = new List<OpenXmlElement>();
List<OpenXmlElement> result = RenderNotesArray(table, notes, notesSection);
return result;
}
This is how I am using the above method:
var table = new Table(RenderTableProperties());
table.Append(new TableRow(
RenderTableHeaderCell("Name"),
RenderTableHeaderCell("Constant Volume"),
RenderTableHeaderCell("Minimum Airflow", units: "(cfm)"),
RenderTableHeaderCell("Wet Bulb Temperature", units: "(cfm)")
));
body.Append(RenderExhaustEquipmentTableDataAndNotes(mainDocumentPart, designHubProject.ExhaustEquipment, table));
Method 2:
private static List<OpenXmlElement> RenderInfiltrationTableData(MainDocumentPart mainDocumentPart, List<ProjectObject<Infiltration>> infiltration,Table table)
{
HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart);
var nameByInflitrationObject = new Dictionary<string, List<ProjectObject<Infiltration>>>();
foreach (var infiltrationData in infiltration)
{
string infiltrationName = infiltrationData.TargetObject.Name;
if (!nameByInflitrationObject.ContainsKey(infiltrationName))
{
nameByInflitrationObject.Add(infiltrationName, new List<ProjectObject<Infiltration>>());
}
nameByInflitrationObject[infiltrationName].Add(infiltrationData);
}
List<OpenXmlElement> notes = new List<OpenXmlElement>();
int noteIndex = 1;
foreach (var inflitrationDataItem in nameByInflitrationObject)
{
List<string> noteIndices = new List<string>();
for (int inflitrationNameIndex = 0; inflitrationNameIndex < inflitrationDataItem.Value.Count; inflitrationNameIndex++)
{
var dataItem = inflitrationDataItem.Value[inflitrationNameIndex];
var row = new TableRow();
Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript }));
if (inflitrationNameIndex == 0)
{
row.Append(RenderOpenXmlElementContentCell(new Paragraph(
new List<Run> {
new Run(new RunProperties(), new Text(inflitrationDataItem.Key) { Space = SpaceProcessingModeValues.Preserve }),superscriptRun
}), 1,
new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin {
LeftMargin = new LeftMargin { Width = "120" },
TopMargin = new TopMargin { Width = "80" }}
}));
}
else
{
row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } }));
}
row.Append(RenderTextContentCell($"{dataItem.TargetObject.AirflowScalar.ToString("R2", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}"));
if (dataItem.TargetObject.NotesHTML?.Count > 0)
{
foreach (var note in dataItem.TargetObject.NotesHTML)
{
var compositeElements = noteConverter.Parse(note);
var htmlRuns = compositeElements.First().ChildElements.Where(c => c is Run).Cast<Run>().Select(n => n.CloneNode(true));
notes.Add(new Run(htmlRuns));
noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture));
}
}
if (inflitrationNameIndex == inflitrationDataItem.Value.Count - 1 && dataItem.TargetObject.NotesHTML?.Count > 0)
{
superscriptRun.Append(new Text($"({String.Join(',', noteIndices)})") { Space = SpaceProcessingModeValues.Preserve });
}
table.Append(row);
}
}
List<OpenXmlElement> notesSection = new List<OpenXmlElement>();
List<OpenXmlElement> result = RenderNotesArray(table, notes, notesSection);
return result;
}
This is how I am using the above method:
var table = new Table(RenderTableProperties());
table.Append(new TableRow(
RenderTableHeaderCell("Type"),
RenderTableHeaderCell("Air Flow")
));
body.Append(RenderInfiltrationTableData(mainDocumentPart, designHubProject.Infiltration, table));
I know this is a lot of code, but are there any ways to convert these to a single method. I am using .net core.
Any ideas or suggestions on how I can refactor these two methods into single method would be very grateful.
I find a lot of your question's content to be fairly redundant, after the first time you have explicitly stated that you are looking for a way to merge these two methods any more of the same request are no longer needed. Reading the same thing 4 times, 3 in the body of your question and 1 in the title, is just a poor use of peoples time.
Sorry for confusion, I am looking a way to extract common methods or possible make generic method out of it
Wow, those methods are pretty similar.
Initially, these objects:
List<ProjectObject<ExhaustEquipment>> exhaustEquipment
List<ProjectObject<Infiltration>> infiltration
are only different in which template parameter refers (ExhaustEquipment,Infiltration), so you could do a generic method:
//this all, could be written as a Generic method, the Generic Parameter would be
//Infiltration or ExhaustEquipment
private static List<OpenXmlElement> GenericRenderElement<Element>(MainDocumentPart mainDocumentPart, List<ProjectObject<Element>> element, Table table)
HtmlConverter noteConverter = new HtmlConverter(mainDocumentPart);
var nameByBusinessElement = new Dictionary<string, List<ProjectObject<Element>>>();
string elementName;
foreach (var element in businessDictionary)
{
elementName = element.TargetObject.Name;
if (!nameByBusinessElement.ContainsKey(elementName))
nameByBusinessElement.Add(elementName, new List<ProjectObject<Element>>());
nameByBusinessElement[elementName].Add(element);
}
List<OpenXmlElement> notes = new List<OpenXmlElement>();
int noteIndex = 1;
foreach (var element in nameByBusinessElement)
{
List<string> noteIndices = new List<string>();
for (int elementNameIdx = 0; elementNameIdx < element.Value.Count; elementNameIdx++)
{
var dataItem = element.Value[elementNameIdx];
var row = new TableRow();
Run superscriptRun = new Run(new RunProperties(new VerticalTextAlignment { Val = VerticalPositionValues.Superscript }));
if (elementNameIdx == 0)
{
row.Append(RenderOpenXmlElementContentCell(new Paragraph(
new List<Run> {
new Run(new RunProperties(), new Text(element.Key) { Space = SpaceProcessingModeValues.Preserve }),superscriptRun
}), 1,
new OpenXmlElement[] {new VerticalMerge { Val = MergedCellValues.Restart },new TableCellMargin {
LeftMargin = new LeftMargin { Width = "120" },
TopMargin = new TopMargin { Width = "80" }}
}));
}
else
{
row.Append(RenderTextContentCell(null, 1, null, null, new OpenXmlElement[] { new VerticalMerge { Val = MergedCellValues.Continue } }));
}
row.Append(RenderTextContentCell($"{dataItem.TargetObject.AirflowScalar.ToString("R2", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}"));
if (dataItem.TargetObject.NotesHTML?.Count > 0)
{
foreach (var note in dataItem.TargetObject.NotesHTML)
{
var compositeElements = noteConverter.Parse(note);
var htmlRuns = compositeElements.First().ChildElements.Where(c => c is Run).Cast<Run>().Select(n => n.CloneNode(true));
notes.Add(new Run(htmlRuns));
noteIndices.Add(noteIndex++.ToString(CultureInfo.InvariantCulture));
}
}
if (elementNameIdx == element.Value.Count - 1 && dataItem.TargetObject.NotesHTML?.Count > 0)
{
superscriptRun.Append(new Text($"({String.Join(',', noteIndices)})") { Space = SpaceProcessingModeValues.Preserve });
}
table.Append(row);
}
}
return RenderNotesArray(table, notes, new List<OpenXmlElement>());
}
and invoke it in the other two concrete methods:
private static List<OpenXmlElement> RenderExhaustEquipmentTableDataAndNotes(MainDocumentPart mainDocumentPart, List<ProjectObject<ExhaustEquipment>> exhaustEquipment,Table table) {
return GenericRenderElement<ExhaustEquipment>(mainDocumentPart, exhaustEquipment, table);
}
private static List<OpenXmlElement> RenderInfiltrationTableData(MainDocumentPart mainDocumentPart, List<ProjectObject<Infiltration>> infiltration,Table table) {
return GenericRenderElement<Infiltration>(mainDocumentPart, infiltration, table);
}
Well, I hope it has been helpful.
thanks for the input and other difference is appending data to the table rows at here row.Append(RenderTextContentCell($"{dataItem.TargetObject.AirflowScalar.ToString("R2", CultureInfo.CurrentCulture)} cfm {EnumUtils.StringValueOfEnum(dataItem.TargetObject.InfiltrationCalculationType).ToLower(CultureInfo.CurrentCulture)}"));
is there any way we can pass these ones from the parent method
You could add a lambda as parameter, said lambda would be of generic type <Element> and has two parameters, TableRow row, Element element, when invoking the GenericRenderElement method you sould send the lambda as parameter, in the case of RenderExhaustEquipmentTableDataAndNotes as the embed procedure you need (using castings if needed), and in the case of RenderInfiltrationTableData as the embed procedure for EnumUtils.StringValueOfEnum(//...
Thanks for the suggestion If possible could you please paste any pseudo code
@EnigmaState For your own growth you should learn how to do that yourself - teach a man to fish rather than give one. Miguel's answer and comment are good, and have told you, as far as I can tell, all you need. The code is very basic, and you've known how to use lambdas for roughly 10 years now, I'm sure you can do it.
@Peilonrayz my bad since then I haven’t worked on lambda much so I lost grip on it
@MiguelAvila could you please provide any pseudo code that would be very grateful to me, thanks
@MiguelAvila the row need to be appended in foreach loop that is where i got confused even if we pass the lambda into it
I'm only adding some notes here on addition of Miguel answer, his answer gives you what you asked, but what you really want is to divide this method into several methods, each method would handle one thing and only one thing. here is a list of the methods you need :
Converting List<ProjectObject<T>> to Dictionary.
Creating a Note from ProjectObject<T>.
Creating a Note Indices from ProjectObject<T>.
Creating TableRow from ProjectObject<T>.
Creating Run for ProjectObject<T>.
Then, you can create methods to use these single object return methods to return IEnumerable<T> in which would create multiple objects of each method
like creating multiple notes, rows, runs ..etc.
if you do this, it'll be very easy to reuse and maintain. and then, you can overload them to add some other requirements, for instance, for the TableRow, you can add RenderTextContentCell overload.
Another thing is to make use of interface. If you implemented an interface that would be implemented on Infiltration and ExhaustEquipment, you would be able to pass that interface to the method instead of the concrete object name like this
private static List<OpenXmlElement> RenderInfiltrationTableData(
MainDocumentPart mainDocumentPart,
List<ProjectObject<IExhaustInfiltration>> exhaustOrInfiltration,
Table table)
{ ... }
with this, you would be able to pass one of those two objects, which would easier to make some conditions in the method to switch some cases based on the type like:
var isInfiltration = exhaustOrInfiltration.GetType() == typeof(Infiltration);
if(isInfiltration)
{
// do something
}
else
{
// it's ExhaustEquipment
}
here is a pseudo-code example on how your method would be if you done these suggestions :
private static List<OpenXmlElement> RenderTableData(MainDocumentPart mainDocumentPart, List<ProjectObject<IExhaustInfiltration>> exhaustOrInfiltration,Table table)
{
var exhaustOrInfiltrationTypes = ToDictionary(exhaustOrInfiltration);
// to be used on notes
var isInfiltration = exhaustOrInfiltration.GetType() == typeof(Infiltration);
foreach(var item in exhaustOrInfiltrationTypes)
{
// CreateTableRow would contains the add single row, note, and run methods.
var tableRows = CreateTableRow(item.Value, isInfiltration);
table.Append(tableRow); // assuming there is a method accepts (IEnumerable<TableRow>) to add multiple rows at once.
}
return RenderNotesArray(table, notes, notesSection);
}
Thanks for suggestion, Those two are different objects and there is no interface related with those two and I would like to make single method common among those two
@EnigmaState use generics,like what Miguel answer.
even i am favorable with Miguel answer but stuck at passing lambda expressions as parameters to it
@EnigmaState the easiest way to understand lambda expressions is to use delegate Func<T> if you create a delegate function that would only pass a string, and return bool Func<string, bool>, then just add the RenderTextContentCell inside it, then just pass this function as parameter.
thanks for suggestion I am just looking for some pseudo code
if you can please provide kind of pseudo code that would be very grateful to me , thanks
@EnigmaState if the lambda expressions is for the part of appending rows RenderTextContentCell, then you can combine both texts, separate them with an if condition to switch between them based on the object type (like in my isInfiltration example).. That would do the job. for lambda refer to https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
| common-pile/stackexchange_filtered |
Question closed due to incorrect assumptions
I asked this question:
Extension causes 404 Error from the Admin Panel
Several people decided that my problems were caused by the patch SUPEE-6285, and they marked my question as a duplicate.
However my problems weren't caused by this patch (they seem to have been caused by an earlier patch).
What can I do to have this question re-opened? Or should I just ask the question again?
Any advice on this situation would be welcome.
You can add a comment explaining that your problem is different.
Or better, you can edit the question and explain you issue.
After a few minutes the question will appear in the reopen votes queue and it might get opened.
Once you reach 500 rep points you will have the option to vote to reopen you question and if it receives enough votes it will be reopened.
If nothing works you can delete your question and ask it again, just be sure to state that the problem is not caused by the latest patch.
I reopened the question this time. It looks like a valid one to me.
I added a comment and edited my question, but there was no change, which is why I came here. Many thanks for re-opening my question!
| common-pile/stackexchange_filtered |
how to save a subimage in Rust?
I got a subimage from an image in Rust. Though the document seems to list no way to save a subimage conveniently. Do I have to read each pixel to write to a buffer?
Here follows my code in Playground.
fn main() {
f();
}
fn f(){
let (w,h)=(100,100);
for (x,y) in &[(100 as u32,200 as u32)]{
let mut img = image::open("mySvg.png").unwrap();
let subimg = imageops::crop(&mut img, *x , *y , w , h );
let mut output = std::fs::File::create(format!("mySvg.{}.{}.png",x,y).as_str()).unwrap();
subimg.write_to(&mut output, ImageFormat::Png).unwrap(); //Error!!
}}
no method named `write_to` found for struct `SubImage<&mut DynamicImage>` in the current scope
--> src/main.rs:12:17
|
12 | subimg.write_to(&mut output, ImageFormat::Png).unwrap(); //Error!!
| ^^^^^^^^ method not found in `SubImage<&mut DynamicImage>`
The method write_to is not implemented for SubImage.
However, the method SubImage::to_image is available, which returns an ImageBuffer.
One can then use ImageBuffer::save_with_format to write out the file.
I've used an image of Ferris and the following directory structure:
. stackoverflow_save_subimage
├─ Cargo.lock
├─ Cargo.toml
├─ ferris.png
├─ src/
│ └─ main.rs
└─ target/
use image::*;
fn main() {
let (w, h) = (100, 100);
for &(x, y) in &[(100, 200)] {
let mut img = image::open("ferris.png").unwrap();
let sub_img = imageops::crop(&mut img, x, y, w, h);
let path = format!("ferris_crop.{}.{}.png", x, y);
sub_img
.to_image()
.save_with_format(&path, ImageFormat::Png)
.unwrap();
}
}
Running the above generates the following cropped ferris_crop.100.200.png:
| common-pile/stackexchange_filtered |
Django no reverse match for view details
im stuck on show details for object, no matter i do (following all guides on internet )
still getting reverse not match error
views.py
def val_details(request, id):
val = Validator.objects.get(id=id)
print(f'vali: {val}')
context = dict(val=val)
return render(request, 'users/val_details.html', context)
print(f'vali: {val}') printing vali: Validator object (14)
html
<button class="btn btn-warning " href="{% url 'val-details' val.id %}">detals</button>
urls.py
path('dashboard/validator/<int:id>/', user_views.val_details, name='val-details'),
models.py
class Validator(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=200, blank=True, null=True)
address = models.CharField(max_length=200, blank=True, null=True)
owner = models.CharField(max_length=250, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __int__(self):
return self.id
error
django.urls.exceptions.NoReverseMatch: Reverse for 'val-details' with arguments '('',)' not found. 1 pattern(s) tried: ['users/validator/(?P<id>[0-9]+)/$']
profile view
def profile(request):
valid = Validator.objects.filter(user=request.user)
valid_count = valid.count()
context = {
'valid': valid,
'valid_count': valid_count,
}
return render(request, 'users/profile.html', context)
and urls.py
from django.urls import path
from users import views as user_views
urlpatterns = [
path('dashboard/', user_views.profile, name='dashboard'),
path('dashboard/validator/<int:id>/', user_views.val_details, name='val-details'),
]
Don't use id. It is a python built-in function. Where is val_details.html ?
@Ram, is that what you mean ?
`def val_details(request, id):
val = Validator.objects.get(id=id)`
if yes, then still the same :(
Not the view. I mean the Template - val_details.html . Your val_details view is rendering this template. Also add relevant views and urls to the question.
val_details.html is in the same app if you asked for this
You get this NoReverseMatch error when Django is unable to find matching url pattern. Please provide your complete url patterns
@Ram , i have added relevant views and urls
this is the typical error message if in your
<button class="btn btn-warning " href="{% url 'val-details' val.id %}">detals</button>
val.id is either NULL or empty.
Please check where you assign it.
can you point me where to look to check this ?
for example go backwards ...first step: {{ val.id }} before the <button ....
ok, so looks like href="{% url 'val-details' val.id %}" is pointing to urls path('dashboard/validator/<int:id>/', user_views.val_details, name='val-details'), and then to view, if im correct
yes, but please check "backwards" why val.id is empty -> error message when processing path(...)
thx for pushing me to use more of my brain :) , that was so small issue and the answer was on front of me .
detals was the answer in my case. {% for v in valid %} in my profile template. thank you
| common-pile/stackexchange_filtered |
WCF - Error: The message version of the outgoing message (Soap12 (http://www.w3.org/2003/05/soap-envelope)
1) I have WCF service deployed on local IIS 5.1:
Interface:
[OperationContract(Action = Service.RequestAction, ReplyAction = Service.ReplyAction)]
Message SetData(Message requestXml);
Implementation:
public const string ReplyAction = "http://localhost/AsurReceiveData/Message_ReplyAction";
public const string RequestAction = "http://localhost/AsurReceiveData/Message_RequestAction";
public Message SetData(Message requestXml)
{
using (StreamWriter writer = File.CreateText(@"E:\Projekti\WCF\Parus\AsurReplicData\Parus\Body.xml"))
{
writer.WriteLine(requestXml.ToString());
}
Message response = Message.CreateMessage(MessageVersion.Default, ReplyAction, requestXml.ToString());
return response;
}
Web.config:
<system.serviceModel>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://localhost:80/"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
<behaviors>
<serviceBehaviors>
<behavior name="Parus.ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost/AsurReceiveData/Service.svc"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<MyInspector />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="Parus.ServiceBehavior" name="Parus.Service">
<endpoint address="http://localhost/AsurReceiveData/Service.svc" binding="basicHttpBinding" contract="Parus.IService">
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<extensions>
<behaviorExtensions>
<add name="MyInspector" type="Parus.MessageInspectorExtension, Parus, Version=<IP_ADDRESS>, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
2) The client side looks as following:
ServiceClient client = new ServiceClient();
string RequestAction = "http://localhost/AsurReceiveData/Message_RequestAction";
Message request = Message.CreateMessage(MessageVersion.Default, RequestAction, "Test message");
Message reply = client.SetData(request);
Web.config:
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<endpoint address="http://localhost/AsurReceiveData/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="ServiceReference.IService" name="BasicHttpBinding_IService" />
When I run the client, the following error message comes up:
The message version of the outgoing message (Soap12 (http://www.w3.org/2003/05/soap-envelope) Addressing10 (http://www.w3.org/2005/08/addressing)) does not match that of the encoder (Soap11 (http://schemas.xmlsoap.org/soap/envelope/) AddressingNone (http://schemas.microsoft.com/ws/2005/05/addressing/none)). Make sure the binding is configured with the same version as the message.
How can I make it work?
You have version mismatch between in your client and server. Make sure you are using:
Same MessageVersion
Same AddressinVersion
Same Encoding
I know that but where exactly should I set them, in web.config files or in code and what should I set?
The error message is coming on client side and I've already tried to set different options in message creation method but nothing helps.
| common-pile/stackexchange_filtered |
jQuery + CSS | Horizontal Scroll
I'm trying to make my div scroll horizontally. My div is 100%, and I want the entire div size (100%) to scroll over to reveal more of the div. Like so:
I already have buttons that tells JS to scroll +150%, but I doesn't work properly.
Now, heres the situation, my div is 100%, but, within that div, is an image thats 800x500, which I want to vert/hori centre within the 100& div.
So when I press the arrow, I want it to move div1 to div2, and then div2, to div3... ect.
Thanks
Here is my code
HTML:
<div class= "edge_container" data-stellar-ratio="3">
<div class = "edge_wrapper">
<div class="OLLIEJ_Welcome"> <!--id="stage0" data-slide="0">-->
Hello & Test
</div>
<div class="EDGE_idea"> <!--id="stage1" data-slide="1">-->
IDEAS & CONCEPTS
</div>
<div class="OLLIEJ_002"> <!--id="stage2" data-slide="2">-->
RESEARCH & DEVELOPMENT
</div>
<div class="OLLIEJ_003"> <!--id="stage3" data-slide="3">-->
BUILD & PRODUCTION
</div>
</div>
</div>
CSS:
.edge_container{
position:absolute;
height: 550px;
overflow: hidden;
width:100%;
white-space: nowrap;
display:block;
top: 50%;
margin-top: -250px;
background-color:#00FFFF;
}
.edge_wrapper{
/*position:absolute;*/
width: 300%;
white-space: nowrap;
vertical-align: top;
background-color:#3366FF;
}
.OLLIEJ_Welcome{
height: 500px;
width: 800px;
display: inline-block;
white-space: normal;
margin-left: 50%;
left: -400px;
padding-left: 2px;
}
.EDGE_idea{
height: 500px;
width: 800px;
display: inline-block;
white-space: normal;
margin-left: 50%;
left: -400px;
padding-left: 2px;
}
.OLLIEJ_002{
height: 500px;
width: 800px;
display: inline-block;
white-space: normal;
margin-left: 50%;
left: -400px;
padding-left: 2px;
}
.OLLIEJ_003{
height: 500px;
width: 800px;
display: inline-block;
white-space: normal;
margin-left: 50%;
left: -400px;
padding-left: 2px;
}
JS:
button_right_0.click(function (e) {
//dataslide = $(this).attr('data-slide');
if(horSlide_0 < 3){
console.debug("Button Pressed");
$('.edge_wrapper').animate({marginLeft: '-=100%'},1000, 'easeInOutQuint');
//horSlide_0 ++;
}
//hideButtons(dataslide);
});
Could you please show us the broken code so we can help you fix it?
You need to have two div elements. The first one acts as mask, showing only the content you wish (i.e. each slide). You then have another div inside of that which holds all of the elements. Something like this should work for your needs:
<div id="slider_mask">
<div id="slider_content">
<img src="src/to/img1.jpg" />
<img src="src/to/img2.jpg" />
</div>
</div>
Your CSS should look something like this (you can use jQuery to calculate the overall width of #slider_content, based on the outerWidth() of its child nodes:
#slider_mask {
width: 100%;
height: 500px;
overflow: hidden;
position: relative;
}
#slider_content {
width: 2400px; /* 800 * 3 */
height: 500px;
position: absolute;
top: 0;
left: 0;
}
#slider_content img {
width: 800px;
height: 500px;
float: left;
}
Now with your markup, you can handle the keypress event via jQuery, to animate left property of #slider_content:
var curr_left = 0,
content = $('#slider_content');
$(window).keyup(function(e) {
// Right arrow key:
if(e.which == 39)
{
// Animate to the left if it's not already set:
if(curr_left <= 0 && curr_left > -1600)
{
content.animate({ 'left': (curr_left - 800) }, 'fast', function() {
curr_left -= 800
});
}
}
// Left arrow key:
else if(e.which == 37)
{
if(curr_left < 0)
{
content.animate({ 'left': (curr_left + 800) }, 'fast', function() {
curr_left += 800
});
}
}
});
I have put together a quick jsFiddle to show you a working example:
http://jsfiddle.net/Y2Ese/
If you want to replace the keydown logic, obviously replace it with your click() event for the buttons.
Getting there, but now my images aren't central (top left), and its not fitting 100%, I can see the next image on the screen (Also, they're not images, they are EDGE builds, but they're still 800x500).
I've literally copied your example into my site - and it displays two, side by side, half the size.
Even in your example it doesn't fit 100% ... only 800px, then it shows the next image, which is not what im looking for.
You need to use JavaScript to get the dimensions, exactly as I indicated in the answer I posted. This isn't a 100% working solution, but it should give you enough basis to edit and get yours working...
| common-pile/stackexchange_filtered |
Drawing lines on PDF with Python
Is there a way to draw lines on a PDF file, by giving it coordinates of the start and end points? I have tried PyFPDF but cannot find much documentation about implementing it.
try reportlab with canvas.line(378,723,580,723) https://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/
The following code will draw a line in pdf:
pdf.set_draw_color(0, 0, 0) #black line
pdf.line(5, 16,205 ,16) #coordinate sequence: (x_start, y_start, x_end, y_end)
| common-pile/stackexchange_filtered |
I want my button, when pressed, it will be able to switch to another layout
How can I launch another layout when button is pressed?
I followed some of the web's solution, but it doesn't seem to help me out.
This was answered here: http://stackoverflow.com/questions/4186021/how-to-start-a-new-activity-when-click-on-button
Well, if you simply want to change the view for the entire Activity, you can do setContentView(R.layout.newLayout) but that is a really bad way to do it.
What you should do instead is startActivity(new Intent(context, NewActivity.class));
You would do that like this:
Button button = (Button)context.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Put the necessary methods here.
}
}
Though in the future, you really should try to do more research before asking a question like this. I had the same question when I was new to Android, but Google and StackOverflow were able to resolve it by searching for the answer. The Developer's Guide also helps if you peruse it enough.
thankyou so much for this info, was searching for it but unable to get the right tags.
right now, using the way you gave, i am facing one error.
The method findViewById(int) is undefined for the type Context
replace context with this or just call findViewById() without it as it should already be in scope
| common-pile/stackexchange_filtered |
How to duplicate strings and attach the numeric suffix using formulas on Google Spreadsheet?
I have strings with each line in one cell. The number after # means the number of items.
Is it possible on Google Spreadsheet to write a formula that allows you to process like B cell if you input strings in A cell like the attached image?
I tried to combine formulas such as JOIN, SPLIT, ARRAYFORMULA, and SUBSTITUTE, but failed. Should I learn the query?
sure:
=INDEX(TEXTJOIN(CHAR(10), 1, IF(""=SPLIT(REPT(
INDEX(SPLIT(FLATTEN(SPLIT(A1, CHAR(10))), "#"),,1)&"-×",
INDEX(SPLIT(FLATTEN(SPLIT(A1, CHAR(10))), "#"),,2)), "×"),,SPLIT(REPT(
INDEX(SPLIT(FLATTEN(SPLIT(A1, CHAR(10))), "#"),,1)&"-×",
INDEX(SPLIT(FLATTEN(SPLIT(A1, CHAR(10))), "#"),,2)), "×")&
TEXT(SEQUENCE(1, 1000), "00"))))
or arrayformula:
=INDEX(SUBSTITUTE(SUBSTITUTE(TRIM(IFNA(VLOOKUP(ROW(A1:A5), SPLIT(TRIM(FLATTEN(
QUERY(SUBSTITUTE(QUERY(IFERROR(SPLIT(FLATTEN(IF(""=IFERROR(SPLIT(REPT(
INDEX(SPLIT(FLATTEN(SPLIT(A1:A5, CHAR(10))), "#"),,1)&"-×",
INDEX(SPLIT(FLATTEN(SPLIT(A1:A5, CHAR(10))), "#"),,2)), "×")),,SPLIT(REPT(
INDEX(SPLIT(FLATTEN(ROW(A1:A5)&"♠♦"&SPLIT(A1:A5, CHAR(10))), "#"),,1)&"-×",
INDEX(SPLIT(FLATTEN(SPLIT(A1:A5, CHAR(10))), "#"),,2)), "×")&
TEXT(SEQUENCE(1, 100), "00"))), "♦")),
"select max(Col2) where Col1 is not null group by Col2 pivot Col1"),
" ", CHAR(13)),,9^9))), "♠"), 2, 0))), " ", CHAR(10)), CHAR(13), " "))
It works perfectly on my case. I stayed up all night, but I couldn't achieve it.
And do you have any tips for writing long formulas? Do you write all the formulas at once? Or do you divide steps across cells for debugging and finally combine them into one formula?
@J.SungHoon depends on the formula, but mostly (like in this case) I start right in the middle and add it up like onion layers and every step is checked if it holds coz at the end when formula is assembled I am pretty much lost if something somewhere needs to be fixed. this formula can be considered as small one :) compared for example to https://webapps.stackexchange.com/a/125018/186471
I went to the link page, looked at step 5, and my chin fell to the floor. It's so interesting. Thank you for helping me.
@J.SungHoon if you are interested in an example of formula assembly: https://docs.google.com/spreadsheets/d/1Wtw-PMjUtIN4KMm-6088tAXtmozxwQFDAsup8KbDHRM/edit#gid=2098948025
Suppose that you want to do this for multiple cells of data in the range A2:A. Clear B2:B and place the following formula in B2:
=ArrayFormula(IF(A2:A="",,IFERROR(TRIM(SUBSTITUTE(SUBSTITUTE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(REPT(REGEXEXTRACT(SPLIT(A2:A,CHAR(10)),"[^#))]+")&"~",REGEXEXTRACT(SPLIT(A2:A,CHAR(10)),"#(\d+)")*1)),,COLUMNS(SPLIT(A2:A,CHAR(10)))))),"~ ","~"),"~",CHAR(10))))))
This formula should produce all results for all rows where A2:A contains data.
If you only want to process the one cell (say, A2), you can use this version in, say, B2:
=ArrayFormula(IFERROR(TRIM(SUBSTITUTE(SUBSTITUTE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(REPT(REGEXEXTRACT(SPLIT(A2,CHAR(10)),"[^#))]+")&"~",REGEXEXTRACT(SPLIT(A2,CHAR(10)),"#(\d+)")*1)),,COLUMNS(SPLIT(A2:A,CHAR(10)))))),"~ ","~"),"~",CHAR(10)))))
ADDENDUM (after comments):
The OP realized that I'd left off the sequencing of numbers. This definitely made things quite a bit trickier. However, I was able to write an array formula that should work.
Again, supposing that the raw data runs A2:A, clear B2:B and then place the following into cell B2:
=ArrayFormula(REGEXREPLACE(REGEXREPLACE(TRANSPOSE(QUERY(TRANSPOSE(REGEXREPLACE(IFERROR(VLOOKUP(SEQUENCE(ROWS(A2:A))&"^"&SEQUENCE(1,COLUMNS(SPLIT(A2:A,CHAR(10))))&"*",TRANSPOSE(QUERY(TRANSPOSE(REGEXREPLACE(SPLIT(QUERY(FLATTEN(FILTER(IFERROR(SEQUENCE(ROWS(A2:A))&"^"&SEQUENCE(1,COLUMNS(SPLIT(A2:A,CHAR(10))))&"^"&REPT(REGEXEXTRACT(SPLIT(A2:A,CHAR(10)),"[^#))]+")&"~",REGEXEXTRACT(SPLIT(A2:A,CHAR(10)),"#(\d+)")*1)),A2:A<>"")),"Select * WHERE Col1 Is Not Null"),"~")&TEXT(SEQUENCE(1,MAX(IFERROR(SPLIT(REGEXREPLACE(A2:A,"[^#\d]",""),"#",1)))),"00")&"~","^\d+~$","")),,MAX(IFERROR(SPLIT(REGEXREPLACE(A2:A,"[^#\d]",""),"#",1))))),1,FALSE)),"^\d+\^\d+\^","")),,COLUMNS(SPLIT(A2:A,CHAR(10))))),"~\s*$",""),"~\s*",CHAR(10)))
Is it long? Sure. Does it work? Yes, it should. And being an array formula, it actually saves processing and eliminates the need to drag the formula down as new rows of data are added in A2:A.
It is good to split, repeat, and re-join the strings. However, there seems to be no formulas about the numeric suffix.
Yes, I seem to have missed that part of the request. If I have time, I will look into this again. In the meantime, it seems player0 has provided a working formula for you.
See "ADDENDUM" to my post for an array solution.
Your formula works well, too!
One regrettable thing is that even if 00 in the formula is changed to -00 to decorate the form of suffix, if data#2 in A2 cell and data#5 is entered in A3 cell, data-00, data-01, and data-02 are printed in B2, and unnecessary -03, -04, and -05 are added.
But the current formula is also cool. I wanna study steadily so that I can add the requirements I need on my own. Thanks your help.
I don't understand your extended goal. (Or, I should say, I do not have the time to analyze the extended goal for understanding.) As it is, the solutions offered have required quite a bit more time than I can generally donate to answering all posts in a given week. But I'm glad that it at least gives you food for thought. Perhaps upon analyzing the solutions offered here, you can manage extending the application of them yourself. Good luck.
| common-pile/stackexchange_filtered |
What does vim ` char mean?
I am looking around to try and understand a line of code via latest snipMate plugin source.
The statement appears at the autoload section of the plugin
for expr in s:snippet_filenames(scope,escape(a:trigger, "*[]?{}`'$|#%"))
for path in g:snipMate.snippet_dirs
for file in s:Glob(path, expr)
source `=file` <-----
endfor
endfor
endfor
The above code iterates over all files found in the snippet folder and executes the source statement - but what exactly does it do? what does =file means?
soruce? Are you sure that's correct?
@Carpetsmoker: you're correct, just a typo...
See :help `=. Basically, it will evaluate file as a VimL expression, then insert the result into the command line. E.g. echo `="file" . "name"` will expand to echo filename, and will print the value of the variable filename.
In your case, for example, if file is ticks.txt, source `=file` will execute source ticks.txt.
| common-pile/stackexchange_filtered |
trying to run a loop in java with below code who gives output a - b c- d but getting error package Sytem does not found?
getting two error when trying to compile programm using commandline
error-Shuffle1.java:24 error:package System does not exist
System.out.print("b c")
Shuffle1.java:31 error:package System does not exist
System.out.print("b c")
letter in word Sytem is also capital then too getting error
public class Shuffle1
{
public static void main(String[] args)
{
int x=3;
while(x > 0){
if(x > 2){
System.out.print("a");
}
x=x-1;
System.out.print("-");
if(x==2){
Sytem.out.print("b,c");
}
if(x==1){
Sytem.out.print("d");
x=x-1;
}
}
}
}
It is
System.out.print
NOT
Sytem.out.print
Your welcome, can happen to anybody ;)
Cause you wrote Sytem instead System
| common-pile/stackexchange_filtered |
Problems with model.destroy()
Whenever I do a model.destroy() with Backbone, it tries to do a DELETE request on the following URL:
http://localhost:8000/api/v1/item/?format=json
Since I am doing a destroy on a model, I would expect that the ID of the model should be passed, so the URL to do a DELETE request on would be this:
http://localhost:8000/api/v1/item/8/?format=json
where the ID is specified. Because of the lack of ID, and my use of tastypie, all items get deleted. How do I make it so that the URL contains the ID of the item that I wish to delete?
Are you overriding the url method on the model?
I'm guessing that your model looks something like this:
var M = Backbone.Model.extend({
url: '/api/v1/item/?format=json',
// ...
});
The url for a model is supposed to be a function but, since it ends up going through the internal getValue function, a string will also "work"; if you check the source I linked to, you'll see why a string for url would give you the results you're seeing.
The solution is to use a function for url as you're supposed to:
url model.url()
Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.
You'd probably want something like this:
url: function() {
if(this.isNew())
return '/api/v1/item/?format=json';
return '/api/v1/item/' + encodeURIComponent(this.id) + '/?format=json';
}
or this:
url: function() {
if(this.isNew())
return '/api/v1/item/?format=json';
return '/api/v1/item/' + encodeURIComponent(this.get('id')) + '/?format=json';
}
encodeURLComponent returns a URL that looks like http://localhost:8000/api/v1/item//api/v1/item/29//?format=json. How would I get just the ID?
@egidra: That doesn't make sense, what do your ids look like? Are they numbers or strings like '/api/v1/item/29/'?
Sorry, they look like what you just typed: '/api/v1/item/29/'. When the URL returns it looks like 'localhost:8000/api/v1/item//api/v1/item/29//?format=json'. My ids look like '/api/v1/item/29/'.
@egidra: That's a funny looking ID you have there, you might want to fix it be just the number. In the mean time, return this.id + '?format=json' should work, you'd want to keep the "is new" branch as-is though.
Do you know what might be the cause for the id to look that? Does it have something to do with my API? I am using Tastypie. When I fetch a list of objects, each object has a JSON with an attribute of resource_uri. This matches 'this.id'
I don't know anything about Tastypie (except the kind I bake of course), you could use parse to clean them up if necessary. Does Tastypie include just a plain id in the JSON?
For a simple fix, I am using return '/api/v1/item/' + this.get("id") + '/?format=json';
I should have thought of that.
| common-pile/stackexchange_filtered |
Importing a PostGIS geometry type into Python as a geometry type from Shapely?
So I have a situation where I have a ton of Linestrings of a broken up route, where I need to Union them together using Shapely's LineMerge or Union OR PostGIS ST_Union.
My idea right now is to use Shapely to import the Linestrings as Geometry types. Union them or merge them using Shapely, and then export back to a results table in the database.
However, the geometry type in the PostGIS database is just a bunch of gibberish. Like...
01020000020e61000....
How can I translate this from the database to a Python geometry type using Shapely, do some manipulations, and then export it back to a database?
Currently this is my code, its just importing that geom object string from the database right now and throwing errors because it isn't a Geometry type.
def create_shortest_route_geom(shortest_routes):
conn = connect_to_database()
cur = conn.cursor()
shortest_route_geoms = []
for route in shortest_routes:
source = str(int(route[1]))
target = str(int(route[2]))
query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';'
cur.execute(query)
total_geom = cur.fetchone()
for index, node in enumerate(route):
try:
source = str(int(node))
target = str(int(route[index + 1]))
query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';'
cur.execute(query)
geom = cur.fetchone()
query = "SELECT ST_Union("+str(geom[0])+","+str(total_geom[0])+")"
cur.execute(query)
total_geom = cur.fetchone()
except IndexError:
print "Last element"
shortest_route_geoms.insert(total_geom)
return shortest_route_geoms
EDIT: I may have found my answer here, looking more into it and will update my question with an answer if I figure this out.
Instead of string concatenating values to SQL queries please use placeholders. Makes for more readable code, removes the need to manually "handle" quoting, and mitigates risk of injections, in general.
Shapely already has libraries for this specific problem.
PostGIS stores the geometries as HEX values. Use Shapely's loads function to load this with the parameter of hex=True.
Specifically...
geom = shapely.wkb.loads(hex_geom[0], hex=True)
Don't use PostGIS ST_Union, cause you have to dump and load over and over for this to work. Shapely has that configured as well with linemerge
| common-pile/stackexchange_filtered |
Executing external command using exclamation mark in MATLAB
In order to execute an asynchronous external command I currently use following snippet:
command = strcat('start python "', obj.path, 'scriptname.py"');
system(command);
Unfortunately, the above command is not portable, since 'start' is a windows only command. Is there a way to start an external command asynchronously with user defined input?
Using
! python "obj.path" "scriptname" &
is not a viable option, since I can't use user defined input as the path. Is there a way to use the behavior of '!' without using an operating system dependent command?
Just a point: you can use ! with user input. Use eval: eval(['!python "' user_path_string '" "scriptname" $']).
So, why not use
system(['python "' obj.path filesep 'scriptname.py" &'])
?
thanks, wasn't aware that windows also supported the ampersand
@anopheles: Yup, although I think it's indeed not documented...so, it might disappear in future releases without warning. But oh well :)
@anopheles: It's documented for the ! -- see help punct.
| common-pile/stackexchange_filtered |
favicon.ico results in 404 error in flask app
I found a lot of entries in my logfile, which indicate that somebody tried to load /favicon.ico and similar files
GET - /favicon.ico
GET - /apple-touch-icon.png
GET - /apple-touch-icon-precomposed.png
I read a lot about this issue online, but I can't get rid of it. Here is what I trued. First I added the following to my head tag
<link rel="shortcut icon" href="/static/favicon/favicon.ico" type="image/x-icon">
However, even though I provide this information in my header, there seem to be browsers out there which don't care about it and still call /favicon.ico?
So I thought just putting the ico file at root and be done with it, but it does not seem to work? If I call
http://localhost:5000/static/favicon/favicon.ico
I get to the icon, but
http://localhost:5000/favicon.ico
Does not work (gives 404)? I cleared my cache and tried it with Chrome and Safari, but I get 404 in both cases? I am really at a loss here. If I move the image in the static folder and call
http://localhost:5000/static/favicon.ico
it works, but the root folder doesn't? What am I missing here?
By default, the flask will only serve files on the /static endpoint. You can add a custom view to handle the default /favicon request.
The flask documentation has some more information on this subject:
https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/
import os
from flask import send_from_directory
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
great that solved the issue. Do you know whether I need to create the same for the apple icos, or are those not search for if favicon.ico exists?
I think favicon.ico is the only one that fires by default. All others are optional. You can also just keep other icons in /static and use the url_for() in the template to point to the correct place, as explained in the first part of the documentation.
thnx so much , excellent fix!
I ran into a very similar problem. I do not have the necessary points to add a comment to the answer yet. So I'll do it using "Your answer". For those who need a much more specific answer on how to use url_for () here is one way to do it.
<!-- Adding a favicon icon to Flask app -->
<!-- SEE: https://favicon.io/favicon-converter/-->
<link rel="shortcut icon"
href="{{ url_for('static', filename='favicon.ico') }}">
<link rel="apple-touch-icon"
sizes="180x180"
href="{{ url_for('static', filename='apple-touch-icon.png') }}">
<link rel="icon"
type="image/png"
sizes="180x180"
href="{{ url_for('static', filename='favicon-32x32.png') }}">
<link rel="icon"
type="image/png"
sizes="16x16"
href="{{ url_for('static', filename='favicon-16x16.png') }}">
<link rel="manifest"
href="site.webmanifest">
To generate the necessary files use the following link: https://favicon.io/favicon-converter/ All files were copied into the /static directory.
| common-pile/stackexchange_filtered |
12.10 Lost power, boots to grub rescue>
boot-repair http://paste.ubuntu.com/1458019/
To my novice eyes it appears that the /sda SSD is the problem. File system "unknown". /sdb is my home drive and appears intact.
Is there anything I can do to attempt recovery on the SSD?
=> Grub2 (v2.00) is installed in the MBR of /dev/sda and looks at sector 1 of
the same hard drive for core.img. core.img is at this location and looks
in partition 1 for (,msdos1)/boot/grub.
=> No boot loader is installed in the MBR of /dev/sdb.
=> Syslinux MBR (4.04 and higher) is installed in the MBR of /dev/sdh.
sda1: __________________________________________________________________________
File system:
Boot sector type: -
Boot sector info:
Mounting failed: mount: unknown filesystem type ''
It does appear that the power failure has corrupted your main partition /dev/sda1. It's fortunate you have a separate /home partition, as your data should be okay.
You can start by running fsck on /dev/sda1. Boot from your live CD/USB and run:
sudo fsck /dev/sda1
Additional information
You can supply options to fsck to force checking even if the filesystem appears clean, respond Y to repair requests automatically, and specify verbose output, or all of these, for example:
sudo fsck -fyv /dev/sda1
Wow, that's all it took. Well, that and responding a couple of hundred times. Stalled for a little bit on the reboot while checking the drive again, and then right to my Desktop. Snooped around for about an hour and I can't find anything missing. Thanks so much for your help.
I should have mentioned that you can supply a -y option to avoid having to respond to every repair request. My bad :(
| common-pile/stackexchange_filtered |
Display image as response from Express with Node.js API to Angularjs
I tried to save the image on server directory and saved it's path in mongodb. When client (Angularjs) request details , Express has to send an array of objects in which one object property will send the image and rest of the object properties are data. First i got the image path from mongodb, and read the image from server directory and appended it to the rest of the data and send the response. But the image is sent as buffer array and my html page is not able to display the image buffer array.
Here's code
Express code
var fs = require('fs');
//To view the cars
app.route('/cars/view')
.get(function(req,res){
rentalcars.find().toArray(function(err,docs){
if(err){
res.send([{found:false}]);
}else{
var data = [];
data.push({found:true});
for(var i=0;i<docs.length;i++){
docs[i].imagePath = fs.readFileSync('./assets/images/'+docs[i].imagePath);
data.push(docs[i]);
}
res.send(data);
}
});
});
Client Code
<table>
<tbody ng-repeat="car in home.cars">
<tr>
<img ng-src="data:image/JPEG;base64,{{car.imagePath.data}}">
<td>{{car.carName}}<br/>Segment : {{car.segment}}<br/>Rent : ${{car.rentCost}} /day</td>
</tr>
</tbody>
</table>
Response i get through Express API call is as below
[
{
"found": true
},
{
"_id": "58564aacbd224fdd2b7ad527",
"carName": "sai",
"segment": "suv",
"rentCost": "1000",
"imagePath": {
"type": "Buffer",
"data": [
255,
216,
255,........]
}
}
]
Where data is array of huge data, i didn't paste it completely. How to send the images from Express with Node.js API to Client.
Below is the code that saves the images to the server directory and saves it's path in mongodb.
var filepath ='';
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './assets/images/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
filepath = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1];
cb(null, filepath);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
//To add new cars
app.route('/cars/add')
.post(function(req,res){
//upload images to server/assets/images/
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
}
var doc = {
carName : req.body.carname,
segment : req.body.segment,
rentCost : req.body.rentcost,
imagePath : filepath
}
rentalcars.insert(doc,function(err,result){
if(err){
res.json({error_code:1,err_desc:err});
}else{
res.json({error_code:0,err_desc:null});
}
});
});
});
2 things: 1. do you save the whole image in the database? 2. If you're using mongoose, can you show me the model?
No, i'm saving only the image path in the database and images are saved on the server side directory with help of 'multer'. 2. I'm not using mongoose, i'm using mongodb native driver.
And also i have edited my question where i have pasted the code which shows how i'm saving my images on server and it's path in mongodb
Since you're using express and you're saving the file location in the database, I recommend to make the route static and use ng-src in Angularjs and fix it like that (fastest to implement and serve, with the least server load)
Or 2: load the image in memory and base64 encode it (I do NOT recommend this option)
I followed your first way of implementation. It's working. Thank you
Since you're saving the images on disc, you're using express and angular, I recommend using express.static to serve the images and use ng-src to load them the right way.
It's the fastest way to implement and serve with the least server load.
| common-pile/stackexchange_filtered |
Add same DefaultMutableTreeNode to 2 different DefaultMutableTreeNode
I have a DefaultMutableTreeNode("birds") which has n number of children. Now I want to add this node to 2 different parents DefaultMutableTreeNode("animals") & DefaultMutableTreeNodes("animals2").
But as the add or insert method of DefaultMutableTreeNode removes the child from it's parent first. The DefaultMutableTreeNode("birds") is getting added in only one of the parent node. Whichever is the called later.
Is there any way around this?
DefaultMutableTreeNode birds = new DefaultMutableTreeNode("birds");
DefaultMutableTreeNode animals = new DefaultMutableTreeNode("animals");
DefaultMutableTreeNode animals2 = new DefaultMutableTreeNode("animals2");
animals.add(birds);
animals2.add(birds);
No, it's not possible, because DefaultMutableTreeNode is used to represent trees, but in your case it's a graph. So you can only add a new node with the same text.
What's the solution then? Can I duplicate the node and then add it?How can I duplicate?
Something like this: animals2.add(new DefaultMutableTreeNode("birds"));
But that won't add the children of already existing birds node. I don't want to create new node with no children. I just want to add the node to another parent node. This seems so simple yet there is no explanation of it anywhere.
I finally ended up with below solution
JTree.DynamicUtilTreeNode.createChildren(DefaultMutableTreeNode parent, Object children)
JTree myTree = new JTree(parent)
This takes a root node as input and children object can be either an array, vector or hashtable. I used hashtable initially to store all the tree's children(birds) and then added them to 2 different root nodes(animals & animals2).
If I correct understand your problem the best way is to create a method which provides "birds-hierarchy":
private DefaultMutableTreeNode createBirdsNode() {
DefaultMutableTreeNode birds = new DefaultMutableTreeNode("birds");
// add another nodes to birds node.
return birds;
}
And later you can use this method to add the complete hierarchy.
animals.add(createBirdsNode());
animals2.add(createBirdsNode());
| common-pile/stackexchange_filtered |
Newsletter sign up on footer showing white text on Macs
I'm getting reports of when someone types in their info into the newsletter sign up in the footer on this site: https://www.hawaiianmanagement.com/ that the text is invisible or white. I'm wondering if anyone knows how I can make it black or if it's just a MAC issue? Thanks!
Here you go; enjoy.
#mc_embed_signup .mc-field-group input {
display: block;
width: 100%;
padding: 8px 0;
text-indent: 2%;
color: #000000; // add this
}
| common-pile/stackexchange_filtered |
"I you already know": is this proper English?
I found this sentence in Terry Pratchett's "Interesting Times": (*)
“Great wizard,” said Butterfly, bowing. “I you already know, but these two are Lotus Blossom and Three Yoked Oxen, other members of our cadre. [...]”
It's certainly not the usual word order, but there's clearly emphasis on “I” and that often can reason about alterations like that. A word-for-word translation into my native language (Czech) works perfectly. Moreover I believe if it was like
“I already know you, but these two [...]”
the “other two” could in principle at first be perceived like a substitution for the object rather than the subject, turning the thing into a garden path sentence.
Note: At least I assume that “I” is the subject and “you” the object, as in “I already know you, but these two don't”.
What makes me unsure is that this is in a part of the story where the speaking character intentionally switches between a flawless language and some sort of pidgin English for the purpose of disguise. It's not clear to me which is the case right here.
(*) An e-book edition so sorry for a missing page reference.
Is the first phrase supposed to mean "I already know you" or "You already know me"? There isn't enough context in your quote to determine that. If the latter, it would be "Me you already know"; if the former, it's decidedly odd.
My apologies. The speaker knows the addressee and is introducing two other people. This is mutual, so the clause is presumably towards the latter two, explaining why the speaker wouldn't introduce themselves, too.
From the added context, I think Butterfly is introducing the trio to the wizard, so it's "You already know me, but these two (whom you don't) are..." I have no idea why Pratchett got the case wrong.
Pratchett did not get the case wrong, he merely dug into the existing language, much as he dug into history and philosophy. What we allow ourselves to become is largely a reflection of what we absorb, rather than the total possible. Language, which is both older and more experienced than we are, always contains more than we realise.
Yes, well, I have no idea what Sir Terry absorbed over his lifetime. It seems not to have done his English a great deal of good.
@AndrewLeach I think that the intended meaning is "You already know me" as you have stated. Notice that the novel is set in a Chinese-like country, Pratchett has altered the order and changed "me" by "I" because Butterfly is not an English native speaker. Maybe that structure is taken from Chinese. Anyway this resource is used to emphasize that characteristic of Butterfly.
Pratchett is a writer. He knows what he's doing. He intentionally wrote the character to be ultra-formal. Non-traditional word-order for emphasis is not unheard of. It would sound vulgar to start a sentence with 'me'.
How if he had said "I am already known to you, but these two are..."?
To me, never having read the book, it's fairly obvious that Butterfly is not a native English speaker, and that the meaning of the sentence is "Me you already know...", i.e. "You already know me...". I'm surprised to see so many comments and answers that disagree with this reading. I agree that it's not a typical foreigner's mistake, but then neither is mangling the word order in this fashion.
@AndrewLeach - Yeah, it took me a second. If you add a comma, it is a little easier to parse: "I, you already know, but these two are..."
"That car, you already know". This seems valid, and the subject is the car. Changing the subject to yourself, "I" seems proper.
It would sound ok if Yoda said it, so it's fine, especially considering the oriental-ish context. Oops, didn't realize Yoda was already referenced in an answer.
@kbelder: "That car" is the object, not the subject. The subject is "you". These are precise grammatical terms!
This quote is DIALOG.It's weird that I have to point this out. Butterfly is a female character introducing Rincewind to two of her cohorts. When speaking in front of them she speaks in a formal but demure fashion, but when speaking privately to Rincewind, she talks much more directly and less formally. How she is speaking is part of the story. Complaining about the grammar used in spoken dialog is just... well... never mind.
It's not correct according to traditional grammar
It might depend on what you mean by "proper English". Based on the context, I'm assuming the clause is meant to express the same idea as "You already know me."
The traditional prescriptivist answer would be that the quoted sentence is not "proper English". This kind of word order (Object-Subject-Verb, or OSV) can be used for emphasis, but changing word order like this isn't supposed to change the form of the pronoun, which still functions as the object of the clause. So "Me you already know" would be correct in "proper English", which makes "I you already know" incorrect—from a certain (not uncommon) viewpoint.
You could stop here. The rest of my answer will be about why I'm hesitant to say that it is incorrect/improper regardless of viewpoint: I'm not sure based on the context that Pratchett intended for it to sound incorrect, and there is some attested variation in the usage of I and me that certain linguists view as falling inside the boundaries of standard English. The quoted sentence certainly shows a very marginal usage of I, but I feel like it could be related in some way to the less marginal areas of variation that I discuss below. And even if we just categorize the usage as improper, I'm interested in the question of why I might have been used here.
Actual usage of I and me is somewhat variable in some contexts
In traditional grammar, I and me are described as the "nominative case" and "accusative case" forms of the first-person singular pronoun. "Nominative" and "accusative" is terminology derived from the grammatical description of Greek and Latin, in which many nouns and adjective have distinct forms for these two "cases". Modern English is descended from a language with cases that worked similarly to those of Latin, but in present-day English, the original distinction between "nominative case" and "accusative case" is only visible on some of the pronouns. (Actually, the modern English "accusative case" represents a merger of the Old English accusative case and dative case, but that's an additional complication that's not relevant to your question.) Because of the way English has developed, linguists have questioned the applicability of the traditional terminology and concepts to modern English grammar.
The use of the remaining distinct pronoun forms has also changed over time. In some contexts, we see a certain amount of variability between the two forms, despite the prescriptive tendency to identify one form as "correct" and the other as "incorrect".
One area where such variation is well-known is coordination. According to prescriptive rules, it is incorrect to use ...and I in place of ...and me, but it still sounds OK to many English speakers to use I here. This use of I is common enough that some linguists argue that it is an established variant usage within the range of Standard English. See F.E.'s answer to Between you and (“me” or “I”)?, which cites the Cambridge Grammar of the English Language (CGEL) by Huddleston and Pullum and also mentions less common constructions that CGEL calls "hypercorrections".
Another context where we see some variability is before a relative clause that has who as the subject: it is possible to see ...I(,) who being used in place of me(,) who.
I haven't read about variability in sentences like the one that you quote, but to my ear, the use of I in this context seems similar to its use in the other contexts that I discussed above. The unusual word order makes the use of I not sound particularly jarring to me, but other people might have different reactions.
I know of a possibly related example of unexpected "nominative case" on a fronted pronominal object (but with "incorrect" usage of he in place of him) in Jane Austen's Pride and Prejudice (unlike the Pratchett sentence that you quote, the Austen sentence also contains one of the environments I mentioned above, as who follows the pronoun):
He, who had always inspired in herself a respect which almost overcame her affection, she now saw the object of open pleasantry.
(Chapter 61)
I first saw the Austen sentence brought up in a related question and its comments: Why the use of objective form?
It doesn't strike me as a very plausible "pidgin English" form
I wouldn't think that an author would be likely to use "I" instead of "me" as a way of characterizing a pidgin form of English. The usual stereotype would be that such a speaker would instead use "me" instead of "I" (e.g. "me no see them" for "I didn't see them").
Comparing it to other errors in the speaker's English
I Googled the book passage glanced at the area near the sentence that you quoted. So far, I didn't see any errors in Butterfly's sentences: maybe you could add a quote showing that?
Lotus Blossom is depicted as making the following kinds of grammatical errors in English ("Morporkian") sentences:
incorrect verb agreement: "Then it are true", "Rincewind, he say . . . Goodbyeeeeeeeee—",
incorrect use of singular forms: "Indeed, I am all ear"
Unfortunately, what I've seen so far doesn't seem much use in answering your question.
Update: sentence production errors and commas
I talked above about the possibility that this usage could be related to other, better-attested variation in the use of I and me. There is fairly good evidence that in some contexts such as ...and I, the prescriptively incorrect use of I is used frequently enough by some speakers to constitute a pattern of usage rather than a one-off slip of the tongue or pen.
But it's harder to find examples of I being used in contexts like "I you already know...." In previous drafts of this answer, I neglected to talk about the possibility that the use of "I" in this sentence is some form of production error, where Pratchett inadvertently used a form that actually wasn't grammatical at all for him. A typo is unlikely, but it could be an error in putting the sentence together based on mental interference from other sentences with similar meaning. It's not incredibly rare for speakers to produce sentences that are syntactically malformed for that reason, although this is less expected in written text.
I think some comments have indicated possible sources of interference that could have caused Pratchett to inadvertently produce an ungrammatical sentence:
The second clause in the sentence has a copular structure: "these two are Lotus Blossom and Three Yoked Oxen". In anticipation of this, "I" might have been used in the first clause, as if it had a parallel structure along the lines of "I am..." (Joshua Taylor's comment is I think making this point).
Kate Bunting pointed out that the clearly grammatical "I am already known to you" would have the same meaning. Possibly, "I you already know" comes from blending the two grammatical sentences "I am already known to you" and "Me you already know".
Some other comments have suggested that a comma might improve the acceptability of the sentence, although I can't think of any reason why that would be the case (zwol, and also BruceWayne, if I'm reading the latter comment correctly).
It strikes me that this is an attempt by butterfly to sound more formal, in deference to the great wizard.
Just like people often confuse "I" with "me" when attempting to sound better educated, and achieve the opposite.
I would not put it past Terry Pratchett to lightly satirise such deference to perceived superiors.
I agree. It's absolutely the norm in business English in North America to hear "You should send it to John or I" or "...to John and myself", both patently non-correct, both apparently because people feel "me" is just a lower register of speech. The prohibition against starting a sentence with "Me" is especially strong because mis-using "me" as subject is characteristic of children's speech ("me want a cookie") and kids are taught early that sentences don't start with "me". So it's a kind of hyper-correction, and well worth satirizing.
Yes, as @CCTO notes, the concept of hypercorrection seems relevant here, and is unfortunately missing from the currently leading answer, and only hinted at in this one.
@CCTO, you've got it. Why not write an answer?
Thanks! But I think the original question (at it’s core a simple yes/no one) has been answered, and very well. I feel my comments are more ancillary in nature.
Well that was not five minutes... Thanks SE...
What's actually happening in this passage is that Butterfly is trying to impress her companions. If you read the full passage, you'll notice that when speaking to or referring to Rincewind in front of her group, she uses a reverent, deferential but slightly stilted manner of speech. But this is feigned. When alone with Rincewind, she abandons the pretense and speaks in a very fluent and down-to-earth fashion.
Although I think this is not what is intended in the context, it could be archaic-correct to have "I" be the subject, "you" the direct object, "already" an adverb, and "know" the verb. In other Germanic languages this would be ok even in current usage. But, yes, probably it's better accounted-for in other ways.
This would not be grammatical in any other current Germanic language, no (well, I don’t know for sure about Afrikaans or local languages like Elfdalian or Gutnish). In some Germanic languages (German, Dutch, probably Afrikaans), it would be grammatical in a subordinate clause, but not in a main clause. In German “I already know you” would be ich kenne dich schon, and “…that I already know you” would be …dass ich dich schon kenne, but as a main clause, *ich dich schon kenne is ungrammatical.
@JanusBahsJacquet, ah, thanks for the information! In Old English I think it would have been ok... Also, with some other verbs, wouldn't such word order be ok, nowadays, in standard German?
Putting the direct or indirect object at the beginning of the sentence is an uncommon but perfectly valid sentence construction, generally done to direct emphasis. Imagine someone looking at multiple sketches from an artist they have hired.
"This is too bold and busy."
"This is washed out and doesn't draw the eye to the focus."
"This, I like."
The emphasis would be different if they said "I like this" -- that focuses on the person talking, not the object of the statement.
The general term for this kind of altered sentence order is Inversion, but generally that talks about inverting subject and verb.
Sample usage from the web: Now this I like. No more annoying ads.
In your example, better grammar would be to have the character say
Me, you already know, but you have not met my friends X and Y before.
but messing up "I" and "me" is a common small grammatical error, especially when instinct is to use "I" at the beginning of a sentence.
This question was previously answered, in a different form, on the English Language Learners stack.
| common-pile/stackexchange_filtered |
Redshift: Incremental products ordered across marketplaces
I have a table, 'Customer_Orders' that basically lists the products purchased by customers across marketplaces (UK, DE, US etc). Here's a short overview of the table:
Cust_id
marketplace
product
1
UK
A
1
UK
B
1
DE
A
1
US
A
1
US
C
From the above table, i want to extract, the incremental number of products ordered 1. in total; 2. by marketplace. For eg: If we use UK as the base, Total: 3; DE: 0 and US: 1.
Are you trying to get the differences like this?
select cust_id, marketplace,
(count(*) - max(case when marketplace = 'UK' then count(*) end) over (partition by cust_id)) as diff_from_uk
from Customer_Orders co
group by cust_id, marketplace;
| common-pile/stackexchange_filtered |
Floating DIV in bottom of the page (it shouldn't scroll after footer DIV)
div{
position:fixed;
bottom:0px;
height:20px;
}
in above code explains that will always keep the DIV in bottom. but i need to avoid the scroll after the footer. i meant need to set boundary for the floating div.
Can you help me?
[Edited] Please refer this and help me!
http://jsfiddle.net/umarfaruk/y9cWf/ i added my sample in that. how
can i stop floating div when we touch footer div. (i meant the
floating should stop scrolling before the footer)
UPDATED:
Thank you guys. i found the solution at http://jsfiddle.net/PnUmM/1 Really thanks to @Gatekeeper :)
can you give an example in http://jsfiddle.net/ for understand better
you can insert an empty div after footer which height is 20px
how is any of this related to jquery ?
http://jsfiddle.net/umarfaruk/y9cWf/ i added my sample in that. how can i stop #floating div when we touch #footer div. (i meant the #floating should stop scrolling before the #footer)
I had same question here - http://stackoverflow.com/questions/5141425/fixed-div-on-bottom-of-page-that-stops-in-given-place little modification and it works like a charm ;-)
dude you could really accept one of the answers from below...
The easiest thing to do is to give the body a bottom padding the same height as the fixed element. That way you will always be able to scroll to any content.
#body {
padding-bottom: 50px;
}
#fixed {
height: 50px;
position: fixed;
width: 100%;
}
here's a fiddle
Like Giberno wrote in his comment, use an empty div to fill up the space occupied by the footer (and thus preventing the last line(s) of text falling being hidden by the footer. Nice and easy: No scripts required!
div#footer{
position:fixed;
bottom:0px;
height:20px;
}
div#empty-space{
height:20px; /* Same height as footer */
}
And the HTML:
Put your page here
...
<div id="empty-space"/>
<div id="footer">footer</div>
See this jsFiddle for a working example.
Thank you guys. i found the solution at http://jsfiddle.net/PnUmM/1/ Really thanks to @Gatekeeper :)
write in your page or stylesheet to avoid scrollbar after f
* {
margin: 0 auto;
}
| common-pile/stackexchange_filtered |
Constant VPN issues on El Capitan
I installed an el capitan update about two weeks ago, and since then I've had constant issues connecting my macbook pro to my work VPN.
I can connect ok, but after only a few minutes (usually-- it can be as long as 45 min and as short as about 2 minutes) the VPN dies off.
Tailing the VPN logs, it all looks ok for a while, then starts repeating the following:
Thu Apr 14 13:01:03 2016 : No DHCP server replied
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0x5 88 ce 83 e3 a6 12 ea 7b 43 ac 98 7f de 47 5c 2c 6f 86 f7 7c 8a 5e 0a c6 1d b1 23 c7 95 92 a1 f0 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0x88ce
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0x6 62 7b 8e 7c b2 95 42 8f 7e 38 88 37 32 bb bb 79 7a 10 e5 e8 35 76 99 20 7b bd 83 1c bc b7 b0 4c ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0x627b
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0x7 00 4d fb fc 33 73 bc 0c 25 9b f0 eb 3a 6c 93 21 d6 9f ec e1 f5 19 71 6d ff 7d 8b 3a 02 f2 e6 e4 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0x4d
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0x8 d8 ac 17 1e 35 e3 59 3b 7d 0c 34 0b 4f 87 d3 86 6a 5c 03 dc 09 7b e0 a7 17 79 5f 5e 73 b6 ac 26 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0xd8ac
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0x9 00 3b d8 5e 73 a1 e5 fd ff 33 3c 27 0d 5c aa 46 8c 1c 85 33 e0 ac 5d e0 f5 fc 50 bc 30 af 23 23 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0x3b
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0xa 00 ef a9 de 91 fe 98 7b a3 db f4 32 08 c0 af 6b ff 86 31 09 e4 23 dd ef 53 df b4 18 b2 33 81 c0 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0xef
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0xb 00 27 41 a2 f0 b1 53 69 71 fa ae 58 fb 33 c2 5a 1e dc 10 ce 4d f8 ca bc 28 d6 ef 8a 95 7a 60 03 ...]
Thu Apr 14 13:03:08 2016 : Protocol-Reject for unsupported protocol 0x27
Thu Apr 14 13:03:08 2016 : rcvd [LCP ProtRej id=0xc 00 c5 76 9b 78 e4 44 b6 df 7c ea 61 41 a2 17 12 e3 ab 42 2c 11 a6 37 72 15 30 93 10 81 7b 69 7d ...]
Has anyone seen this before? Any idea of workaround or things to try?
I'd recommend using TunnelBlick. Whenever I run into issues with the default VPN client TunnelBlick works much better. It even has options (like forcing full tunneling) that the built-in one doesn't.
| common-pile/stackexchange_filtered |
WPF Binding: Expression evaluation
I have a listbox in markup and a detail control. The listbox template defines a details button for each element. If this button is pressed a dependency property in the element's datasource is set to Visiblility == Visible. As long as I do have a selected item everything is OK. But if there is no selected item, the detail control is displayed always. Markup:
<Listbox x:Name="myListbox" />
<local:detailcontrol Visibility="{Binding ElementName=myListbox, Path=SelectedItem.DetailVisibility}" />
What I want is something like this:
<Listbox x:Name="myListbox" />
<local:detailcontrol Visibility="myListbox.SelectedItem != null ? {Binding ElementName=myListbox, Path=SelectedItem.DetailVisibility} : Visiblity.Hidden" />
Snippets both do not compile, but are provided to make my point clear.
Starting using the article at http://www.11011.net/wpf-binding-expressions I implemented something similar which solved my problem
| common-pile/stackexchange_filtered |
Why at the school not at school
In the following sentence why is it at the school not at school?
They don't have to do their homework today because it's a holiday at the school.
Because the school, as an institution, has declared it a holiday. So no one is there. Which means the holiday isn't occurring on school grounds. It's abstract, not physical.
The real question is why they didn't just say "because it's a school holiday".
In the US, we'd simply say 'it's a school holiday'. "At school" would be used to describe a 'school function':
"The football team had their first practice at school, today."
"At school, we sometimes start fires in science class."
But - (not school functions)
"The Ladies' Auxiliary Committee will meet at the school."
"There was a fire at the school, that practically destroyed the gymnasium."
| common-pile/stackexchange_filtered |
Broaden off-topic migration flags
When was the last time the migration selection was updated ?
It's lacking programmers, code review, software rec and user experience SE.
And I'm not a huge reviewer, but I never had to migrate to tex or stats...
SO has a terrible history of migrations to Programmers. Way, way too many SO users seem to think it's just a place to dump all bad questions. Very few seem to actually understand what's on topic there. Also note that there have only been 22 migrations to Programmers in the past 90 days (putting it in 9th place).
Code Review and Software Recommendations are in beta, and are thus ineligible as migration targets. CR actually has a lot of migrations, so it'll likely be considered as a migration target when it leaves beta; but it may or may not make it based on a number of factors that will need to be considered at that time. As for SR, it has a whopping 1 migration in the past 90 days; it's clearly nowhere near meriting a slot.
As for UX, it literally has zero migrations from SO in the past 90 days. Obviously it's not a frequent migration target.
As for the items on the list not being frequent migration targets, stats is the site with the single most migrations in the past 90 days, with 137 migrations. Tex is 7th at the moment, with one of the items above it being an inelligible migration target, and the other being GIS with 32 migrations (to Tex's 30). We'd need to see GIS surpassing Tex regularly over an extended period of time to merit it bumping it off of the list.
Ok ! I understand the beta status and programmers.se problem. Thanks!
The examples in this Q & A may be not very good, but the concept is still very true -- I see a LOT of topics on SO that should be moved to gamedev (as well as various other SE forums) but the fact that SE has what 50+ forums and only 5 migration links, it's not great. The fact that some migrations are not used correctly or that are a dumping ground is second to the fact that SO is the biggest and most popular SE site and so is a first port of call for an awful lot of people whose questions can be better answered / researched on more specific SE sites
@Martin No, it's not second to that. We don't want the most of those questions migrated, because the most of them aren't good questions to migrate. Having an easier migration path would mean that those sites would simply get flooded with bad and/or inappropriate questions migrated over from SO by people that don't understand the site, it's scope, it's quality standards, etc. and often moving more quesitons than these smaller sites have the users to properly moderate.
Make it difficult to transfer valid and useful questions because some questions may not be up to standard and will apparently not be weeded out by other options on the close portal? While I can see your point of view in general, I disagree with your assertion. If SO doesn't move out things that are not SO related and instead valid gamedev questions get answered and upvoted by SO users then this means that gamedev SE gets less traffic and less users, and SO gets more, as more and more [beginner] game developers will google questions and find answers in SO rather than on gamedev.SE
There's two factors here; 1) the validity/quality of the question itself and 2) the validity / quality of the reviewer wanting to move this question. Bad questions don't belong on any SE site, be it SO or gamedev or any other. I think you're getting so worried about point 1, that you're forgetting that if SO doesn't distribute it's content to other related sites, it will never [does not] remain focused on its primary purpose while at the same time collecting traffic / users / advise providers from other SE sites
@Martin Making it difficult to transfer questions because the vast majority of questions migrated are bad questions (which we know, because it's been demonstrated time and again that SO users are bad at determining what should be migrated to other sites), and where the target site simply won't have the means to properly handle those quesitons, all so that the very few good questions that should be migrated take only the tiniest bit less effort? When this hasn't been done, and easy migration paths have existed, it's completely tanked other sites, causing serious problems for years.
@Servy if there's a track record of SO bad decision making then yeah, fair enough, from the way you angle your words it sounds endemic that SO users are poor decision makers :-/
@Martin I mean it's not particularly reasonable to expect most SO users to know what types of questions are appropriate for sites they aren't active on, but yes, there is lots of evidence that they're really bad at migrations, even more so than you'd expect given that they are out of their area of expertise.
I think many would say that this is as much as can be expected
| common-pile/stackexchange_filtered |
How to Draw a shape or bitmap into another Bitmap , Java/android
I want to draw a shape(many circles particularly) into a Specific Bitmap.
I have never used canvas / 2D graphs etc.
Anyone that can point me to the right direction to do what i want.?
#
As i see it i create a Drawable put the bitmap in it then "canvas-it" to the shapes i want etc
but i really need some guideline
OK i sorted it out
Bitmap b=BitmapFactory.decodeResource(CON.getResources(),R.drawable.deltio);
Bitmap bmOverlay = Bitmap.createBitmap(b.getWidth(), b.getHeight(), b.getConfig());
canvas = new Canvas(bmOverlay);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawBitmap(b, new Matrix(), null);
canvas.drawCircle(750, 14, 11, paint);
What are you doing with the resulting canvas to show the image in your UI?
Bitmap b;
b.setImageBitmap(bmOverlay);
| common-pile/stackexchange_filtered |
Declaring a script from a PartialView only once
I have a Razor PartialView that works with Metro-UI-style tiles. It's a very simple PartialView that allows me to display tiles bound to a ViewModel, really nothing spectacular.
Since it's not used in all pages, I don't want to include the jQuery block on every page load. Instead I prefer that the script is declared inline with the PartialView, but registered once in the pagecode.
The view is the following (I have reenginered Metrofy template)
@model IEnumerable<MetroStyleTile>
<div class="container tiles_hub">
<div class="sixteen columns alpha">
@foreach (MetroStyleTile tile in Model)
{
<div class="tile_item four columns alpha">
<a href="@Url.Action(tile.Action, tile.Controller, routeValues: tile.MvcArea != null ? new { area = tile.MvcArea } : null)" class="tile">
@Html.Label(tile.Description)
@if (tile.ImageUrl != null)
{
@Html.Image(tile.ImageUrl.ToString(), tile.Title, htmlAttributes: new { @class = "tile_img" })
}
</a>
</div>
}
</div>
@section Scripts{
<script type="text/javascript">
$(document).ready(function ($) {
//Tiles hover animation
$('.tile').each(function () {
var $span = $(this).children('span');
$span.css('bottom', "-" + $span.outerHeight() + 'px');
});
var bottom = 0;
$('.tile').hover(function () {
var $span = $(this).children('span');
if (!$span.data('bottom')) $span.data('bottom', $span.css('bottom'));
$span.stop().animate({ 'bottom': 0 }, 250);
}, function () {
var $span = $(this).children('span');
$span.stop().animate({ 'bottom': $span.data('bottom') }, 250);
});
});
</script>
}
</div>
The above code is fine when I use the PartialView only once in the page, but if I use the @Html.Partial twice I get the script twice.
Now let me clarify: I often ask question on StackOverflow to learn more from the platform, and I don't usually like workaround solutions.
I could use a Javascript global variable to see if the function must be declared again or not.
I could register the script in the Layout to make it appear in all pages and not worry.
I'm asking how to print the script to Response only once. Learning how to do this allows me to lighten page payload when multiple PartialViews are developed like this (so the client gets the script only when needed, and only once if needed).
How can I do that?
Maybe you can use a wrapper view where you could put all your scripts and required jquery statements, which will load only once. and then render the above partial views either using @html.Partial or ajax as per the requirement.
This is a very good question. In my experience, it's better practice to render your JS in a JS file referenced in your parent view. It's tempting to encapsulate partials with their JS dependencies; But then you will more easily lose track of what JS is relevant to your View.
I had a similar problem. Maybe this will help you too?
http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates
| common-pile/stackexchange_filtered |
Prediction on mixed effect models: what to do with random effects?
Let's consider this hypothetical dataset:
set.seed(12345)
num.subjects <- 10
dose <- rep(c(1,10,50,100), num.subjects)
subject <- rep(1:num.subjects, each=4)
group <- rep(1:2, each=num.subjects/2*4)
response <- dose*dose/10 * group + rnorm(length(dose), 50, 30)
df <- data.frame(dose=dose, response=response,
subject=subject, group=group)
we can use lme to model the response with a random effect model:
require(nlme)
model <- lme(response ~ dose + group + dose*group,
random = ~1|subject, df)
I would like to use predict on the result of this model to get, for instance, the response of a generic subject of group 1 to a dose of 10:
pred <- predict(model, newdata=list(dose=10, group=1))
However, with this code I get the following error:
Error in predict.lme(model, newdata = list(dose = 10, group = 1)) :
cannot evaluate groups for desired levels on 'newdata'
To get rid of it I need to do, for instance
pred <- predict(model, newdata=list(dose=10, group=1, subject=5))
This, however, does not really make much sense to me... the subject is a nuisance factor in my model, so what sense does it have to include it in predict? If I put a subject number not present in the dataset, predict returns NA.
Is this the wanted behaviour for predict in this situation? Am I missing something really obvious?
I think you are looking for a population response rather than a mean prediction. The unconditional model does assume that your mean is given by $X\beta + Z\gamma$ (in particular $y \sim N(X\beta+Z\gamma, \sigma^2 I)$ so it will expect some values for the nuisance parameter also. There are situations that it might not even make sense to assume your evaluation point is hierarchy-free (so no $Z$). That's why fitted() gives you results "with nuisance" in the first place. (And actually I don't think it nuisance but rather a extra info but OK...)
@user11852: just to clarify, I am thinking about this as a model to be used, for instance, in case of repeated measures for the same subject.
Given you are are looking estimates for the same subject, why exclude it then? If you want population level estimates (no $Z$ information) then it is a difference question. As Greg says in his response you can get estimates for the population if you want but that won't be subject specific.
@user11852: I am not looking for estimate on the same subject. I do repeated measures on various subjects in order to get population estimates. I do not care for the subjects that I already tested as I already have the experimental answer... I want to be able to predict how a new subject of a specific group will respond to the stimulus. Greg answer solves the problem indeed.
If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at. The default is the highest or innermost which means that if you don't specify the level then it is trying to predict at the subject level. If you specify level=0 as part of your first predict call (without subject) then it will give the prediction at the population level and not need a subject number.
| common-pile/stackexchange_filtered |
SQL joins to display data without a foreign key to identify the data to retrieve
I am trying to retrieve data of a trainer's clients from the client table that only applies to the user from the personal_trainer table. However, in the client table there is no foreign key to identify the trainer.
I have created two other tables nutrition and training which have both ClientID and personalTrainerID as foreign keys from their respective tables. I am wondering what is the sql statement to retrieve the data?
The logic i'm trying to create is: if a coach (personaltrainerID) has created a trianing/nutrition plan and assigned it to a client (clientID), the output is all the clients which have been assigned a training/nutrition plan.
The first $query is for a search function that works, the problem resides in the statement
$query = "SELECT * from client AS t1 LEFT JOIN nutrition_plan AS t2 ON personalTrainerID = clientID";
Full code:
<?php
//code to search for a item from the database
// user can enter any character to search for a value from the db
if (isset($_POST['search'])) {
$valueToSearch = $_POST['ValueToSearch'];
$query = "SELECT * FROM client WHERE concat(`clientID`, `name`, `age`, `sex`, `weight`, `height`, `yearsExperience`, `goal`, `injuries`, 'email')LIKE'%".$valueToSearch."%'";
$search_result = filterTable($query);
} else {
$query = "SELECT * from client AS t1 LEFT JOIN nutrition_plan AS t2 ON personalTrainerID = clientID";
$search_result = filterTable($query);
}
//code to filter the db
function filterTable($query)
{
$connect = mysqli_connect('localhost:3308', 'root', '', 'fypdatabase');
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<?php
while ($row = mysqli_fetch_array($search_result)) {
//display the details from the db in the table with option to delete or update entry
?>
<tr>
<td><?php echo $row['clientID']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['age']; ?></td>
<td><?php echo $row['sex']; ?></td>
<td><?php echo $row['weight']; ?></td>
<td><?php echo $row['height']; ?></td>
<td><?php echo $row['yearsExperience']; ?></td>
<td><?php echo $row['goal']; ?></td>
<td><?php echo $row['injuries']; ?></td>
<td><?php echo $row['email']; ?></td>
<td>
<a href="?Delete=<?php echo $row['clientID']; ?>" onclick="return confirm('Are you sure?');">Delete</a>
</td>
<td>
<a href="updateClient.php?Edit=<?php echo $row['clientID']; ?>" onclick="return confirm('Are you sure?');">Update</a>
</td>
</tr>
<?php
}
Tables:
CREATE TABLE IF NOT EXISTS `training_plan` (
`trainingPlanID` int(11) NOT NULL AUTO_INCREMENT,
`personalTrainerID` int(11) NOT NULL,
`clientID` int(11) NOT NULL,
`trainingType` varchar(30) NOT NULL,
`exercise1` varchar(30) NOT NULL,
CREATE TABLE IF NOT EXISTS `nutrition_plan` (
`nutritionplanID` int(11) NOT NULL AUTO_INCREMENT,
`personaltrainerID` int(11) NOT NULL,
`clientID` int(11) NOT NULL,
`nutritionPlan` varchar(30) NOT NULL,
`mealType` varchar(30) NOT NULL,
CREATE TABLE IF NOT EXISTS `personal_trainer` (
`personalTrainerID` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`location` varchar(30) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(30) NOT NULL,
`yearsExperience` int(11) NOT NULL,
CREATE TABLE IF NOT EXISTS `client` (
`clientID` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(30) NOT NULL,
`weight` int(11) NOT NULL,
Sample data and expected output would help here
May I ask what this is for? If this is just a pet project you can probably use nutrition or training as ugly bridge tables, as long as you won't have orphaned records. If this is going to be anything more than a pet project though you really need to rethink your data model.
This is a university project, its the last part of what i need to display from my db, so I just need to find a way to output it!
@GMB ive updated the question with the table structures, thank you!
Try using a left join. Then you get data from both tables.
$query = "SELECT * from client WHERE email = (SELECT clientID FROM nutrition_plan WHERE personalTrainerID=clientID)";
change SQL to:
$query = "SELECT * from client AS t1 LEFT JOIN nutrition_plan AS t2 ON personalTrainerID = clientID";
Further more your query:
$query = "select * from client WHERE concat(`clientID`, `name`, `age`, `sex`, `weight`, `height`, `yearsExperience`, `goal`, `injuries`, 'email')like'%".$valueToSearch."%'";
Will lead to slow execution on large tables. Do an OR 'name' like'%".$valueToSearch."%'" etc. for every field and make sure the fields a properly indexed.
Hi Henry, thanks for your feedback! I have changed the SQL to the new code but it still is displaying me an error. The logic im trying to express is if a coach has created a training/nutrition plan and assigned it to a client, those clients will appear under the client list.
Use the coach_id in the client table if its a one tot one relation. Else use a third table to link the two tables.
| common-pile/stackexchange_filtered |
Standard way to map handler-thrown exceptions to IActionResults in ASP.NET Core 8 Web API?
The API controllers in my new ASP.NET Core 8 Web API use MediatR to dispatch requests to handlers. Handlers may throw exceptions; when that happens, the controllers appear to be returning generic status 500 regardless of the exception.
Is there something built into .NET Core that will handle the basic mappings from Exception to IActionResult, like mapping a BadHttpRequestException to a BadRequestResult and a NotFoundException to a NotFoundResult?
I do see there's an app.UseExceptionHandler for creating something custom but I'm not sure that's applicable and I don't want to create something custom if there's already a built-in.
There is no built-in method for mapping exceptions to specific IActionResult types. UseExceptionHandler is applicable and effective for handling such mapping and other more custom needs. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-8.0
Another way would be Exception filters but it is not as flexible as UseExceptionHandler so it is more recommended to apply UseExceptionHandler.
| common-pile/stackexchange_filtered |
Posting data with angularjs v 1.3
I have a web api 2.0 application and I have to post data of a form.. Here my js code:
(function (angular) {
var public_area = angular.module("public-area", ['ngResource']);
public_area.factory("MyService", function ($resource) {
return {
my_controller: $resource("/api/MyHttpControllerTest/")
};
});
public_area.controller("MyController", function ($scope, MyService) {
$scope.getPlans = function ()
{
var pianiTariffari =
new MyService
.my_controller
.query({
customerType: $scope.customerType
}, isArray = true);
}
$scope.sendInvitation = function ( )
{
var invitation =
new MyService
.my_controller(
{
request: {
CustomerType: "test"
}
});
invitation.$save();
}
});
})(angular);
How you can see, I have a controller.. and two function, 1 in GET and 1 in POST...
I see you also the server side controller
public FillFormPresentaUnAmicoResponse GetPromozioni(string customerType)
{
...
}
[HttpPost]
public PresentaUnAmicoResponse InvitaAmico(PresentaUnAmicoRequest request)
{
...
}
Where the class PresentaUnAmicoRequest is
public class PresentaUnAmicoRequest
{
public string CustomerType { get; set; }
}
The GET function works correctly! But the POST not...
In the post I receive a valid instance of the "request", bu the property inside it is NULL...
The really strange thing to me is that if I call the Post method in this way:
var invitation = new MyService.my_controller(undefined);
invitation.$save();
server side, the "request" is instanced.. I expected "request = null" instead..
Can anyone help me?
Thank you
UPDATE:
If I understood, I need always the same object to stick REST principles. So, according to spike's example I believe I have to create an object similar to this:
public class Promos
{
public string CustomerType{ get; set; }
public List<string> PromoPerCustomerType{ get; set; }
}
public class PresentaAmico
{
public Promos Promozioni { get; set; }
public string Name{ get; set; }
public string Surname { get; set; }
...
}
And my Rest service should be like this
[HttpGet]
public PresentaAmico Get(string customerType)
{
...
}
[HttpPost]
public void Save(PresentaAmico myForm)
{
...
}
Is it correct?
IMHO This is not the way the $resouce is works at its best and that's because you're not really sticking to REST principles. The idea of $resource, is to get an object, modify it and then $save it again, which maps to a GET and POST calls in which the object that comes back and is being sent, are the same.
You are GETting an FillFormPresentaUnAmicoResponse and POSTing another type of object, namely a PresentaUnAmicoResponse.
Which of course could start the whole discussion whether you are using REST as it would work with WebAPI: namely a resource, which you modify by mapping the HTTP verbs on it ( GET/POST etc. ) Your controller doesn't really stick to those rules since you send different types of objects over the wire.
So I would actually recommend 2 controllers, one for each of your types: FillFormPresentaUnAmicoResponseController and a PresentaUnAmicoResponseController. I would also reconsider the naming in this case - there's no need in the 'response' suffix.
var presenta = $resource('/presentaunamicoresponse/:id', { id:'@id'});
// The id doesn't make any sense here - which should raise the question on
// whether these stuff is really suitable for REST or whether you are really
// doing a remote procedure call, but OK.
presenta.CustomerType = 'Whatever';
presenta.$save();
I think this is how it would work. You would have to stick it in your factory though for consistency. But as you can see in the docs ( https://docs.angularjs.org/api/ngResource/service/$resource ) - you get the resouce, and manipulate properties on the resource itself. Then you call the $save() method on it.
Yes... I had some doubts when I was reading a guide about angularjs and resources... Now my doubts are clear... surely I miss important notions about REST.. I have done a test.. 1 controller, 1 object as you had told me, and infact it works now! But that was a test, and that is not my solution.. I still have a doubt about your solution too... But i need to explain the context. I have a dropdown and when I select a value another drop must be filled. I think have 2 controllers would work but perhpas is not the solution this time. What do you suggest? Using get/post instead of resources?
Could you give me a bit more information on the domain? You are getting promozioni - which are special offers I suppose - and you want to invite a friend or something? Sorry my italian ( if it is italian ) is very bad.
Yes, I have this really simple application. Just 1 form: "Invite a friend".. In this form I have some textbox (not important), 1 dropdownlist where i can select customer type (Biz or not), and 1 dropdownlist that is filled with special offers for business or private, based on previous selection.
So user selects customer type and the application do a call to the controller to obtain special offer for that customer type.
Then user continue to fill the form and in the end click on a link (that is not a submit) and I do a call (in POST) to the controller to save on db the invitation.
I created a fiddle: http://jsfiddle.net/jctzqdcv/1/ - does that work for you? In case of cascading dropdowns - returning a tree structure worked really well for me. You just need one GET call for that to make that work. I'm sorry I didn't use $resource, I can do that too if you like. Let me know.
Ohh thank you.. really... You are too kind :) No, that's ok.. I can try by myself to transform you example using $resource...
Just 2 questions:
I've updated my question, can you confirm I have understood everything good, please?
I understood your example works really good with cascading dropdowns. But what if I had radio button, and when I had selected it, the dropdown was filled? The update I did in the post is still valid?
Thank you
1 - Yes I think you did, although you could add the wrapping controller for clarity. The original REST document is here, it may be interesting for you. http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm. Furthermore, WebAPI works a lot by convention. So if you just call your methods Get and Post, you don't need the attributes. And as an added bonus I created a radio button example for you: http://jsfiddle.net/jctzqdcv/2/ - note the $parent in the ng-model of the ng-repeat. Here's why: http://odetocode.com/blogs/scott/archive/2013/06/25/radio-buttons-with-angularjs.aspx
Thak you, you are really fantastic... Both the solution and the explanations an the link
please can you let me see just the post with resource? If I do $http.post('/api/PresentaUnAmico/',$scope.pianiTariffari[0]).success(function () {}); works fine... If I do var invitation = new PresentaUnAmicoService.piani_tariffari({ request: $scope.pianiTariffari[0] }).$save();, I have always the same problem... the property inside my object are null
@Ciccio: I hadn't worked with $resource before so I decided to give it a try: https://github.com/jochenvanwylick/SODemoAngularResourceWebAPI . Check out application.js to see how I think $resource could be used against WebAPI
Thank you... but in the end this link helped me really much with resource... perhaps it can be useful to you too.. http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/
| common-pile/stackexchange_filtered |
Laravel 5.5 Geocoder
I wanted to use this package for geocoding in Laravel. I have added it to providers and published the config, but I am getting trouble setting it up to work.
try {
$location = Geocoder::geocode('<IP_ADDRESS>')->get();
return $location;
} catch (\Exception $e) {
return $e;
}
This returns empty object.
I have left the config file as is.
return [
'cache-duration' => 9999999,
'providers' => [
Chain::class => [
GoogleMaps::class => [
'en-US',
env('GOOGLE_MAPS_API_KEY'),
],
GeoPlugin::class => [],
],
],
'adapter' => Client::class,
];
And added valid API key to env. Is there something I'm missing?
Geocoder is imported as use Geocoder\Laravel\Facades\Geocoder;
EDIT
In case someone gets to the same problem...this is how you'd get the country from it:
app('geocoder')->geocode('<IP_ADDRESS>')->get()->first()->getCountry()->getName();
Really complicated unnecessarily in my opinion, I requested a documentation change on official repo.
Have your tried one of the other IP aware Geocoding services? Like FreeGeoIp::class?
Well not really, but I wasn't searching for alternatives, I'm simply not sure how to make this work
Many thanks to you.
You save my day
did you try using dd() in tinker?? I have been try it...and it work for me..
try this :
dd(app('geocoder')->geocode('<IP_ADDRESS>')->get());
response :
Illuminate\Support\Collection {#764
items: array:1 [
0 => Geocoder\Model\Address {#753
-coordinates: Geocoder\Model\Coordinates {#755
-latitude: 51.0823
-longitude: -113.9578
}
-bounds: null
-streetNumber: null
-streetName: null
-subLocality: null
-locality: "Calgary"
-postalCode: null
-adminLevels: Geocoder\Model\AdminLevelCollection {#767
-adminLevels: array:1 [
1 => Geocoder\Model\AdminLevel {#768
-level: 1
-name: "Alberta"
-code: "AB"
}
]
}
-country: Geocoder\Model\Country {#769
-name: "Canada"
-code: "CA"
}
-timezone: null
-providedBy: "geo_plugin"
}
]
}
| common-pile/stackexchange_filtered |
Calling ASM x64 function from C (double), GAS
I've got this really simple functions in ASM and C. I want to call ASM function from C code for double. I think return value from ASM should be stored in XMM0, but what actually happen is that my return value is taken from rax or if rax isn't set, I get 1.
C code:
#include <stdio.h>
int main() {
double a = 3.14;
double b = add(a);
printf("%lf\n", b);
return 0;
}
ASM function:
.type add, @function
.globl add
add:
#movq $1, %rax
addsd %XMM0, %XMM0
ret
What's wrong with it? Appreciate all hints.
You haven't told the compiler what the function takes in or returns. Implicit declaration will make it assume return value of int.
The compiler should warn you about this. If it doesn't, turn the warnings up.
You should add
extern double add(double val);
so the compiler knows what's up.
| common-pile/stackexchange_filtered |
Find date difference based on condition in R
I want to find the date Difference based condition.
Dataframe is like
Order_Id ReceivedDate DueDate (Y-m-d)
---------------------------------------
E1625 N/A 2021-05-10
E8655 2021-01-03 2021-01-03
E1360 2021-03-23 2021-03-15
E2347 2021-03-20 2021-04-01
E7807 2021-03-15 2021-04-20
.
.
.
To calculate date difference:
df$received_delay <- ifelse(is.null(df$ReceivedDate) , 0,
ifelse((difftime(df$ReceivedDate, df$DueDate, units = "days"))< 0, 0,
difftime(df$ReceivedDate, df$DueDate, units = "days")))
but getting the expected result.
Expected result:
Order_Id ReceivedDate DueDate received_delay(days)
----------------------------------------------------------
E1625 N/A 2021-05-10 0
E8655 2021-01-03 2021-01-03 0
E1360 2021-03-23 2021-03-15 8
E2347 2021-03-20 2021-04-01 0
E7807 2021-03-15 2021-04-20 5
.
df$received_delay <- ifelse(is.na(df$ReceivedDate) , 0,
ifelse((difftime(df$ReceivedDate, df$DueDate, units = "days"))< 0, 0,
difftime(df$ReceivedDate, df$DueDate, units = "days")))
should work
Or
df$received_delay <- ifelse(difftime(df$ReceivedDate, df$DueDate, units = "days")< 0 | is.na(difftime(df$ReceivedDate, df$DueDate, units = "days")), 0,
difftime(df$ReceivedDate, df$DueDate, units = "days"))
| common-pile/stackexchange_filtered |
Convert from auto_ptr to normal pointer
I have some third party libraries that generate and return an auto_ptr. However, I really want to use some STL containers.
So I'm guessing one way would be to convert
auto_ptr <int> ptr = some_library_call ();
into a regular c++ pointer. Will the following work?
int* myptr = ptr;
If not, what is the best way to use STL with auto_ptr (yes I know it won't work directly... I'm aware that stl and auto_ptr don't mix together)?
What does the 3rd party function do, and how are you using the return value with STL?
Basically reads some stuff from a file and deserialize it. So it's actually some_library_call (string filename) if that helps...
Note that std::unique_ptr<> has a conversion constructor that takes a std::auto_ptr<>.
You can use either ptr.get() if you want to obtain the pointer and still let the auto_ptr to delete it afterwards, or use ptr.release() to obtain the pointer and make the auto_ptr forget about it (you have to delete it afterwards.)
Call release() on the auto_ptr, then you can store the value in a different smart pointer or raw pointer and use it with STL containers.
| common-pile/stackexchange_filtered |
How to download a file using curl
I'm on mac OS X and can't figure out how to download a file from a URL via the command line. It's from a static page so I thought copying the download link and then using curl would do the trick but it's not.
I referenced this StackOverflow question but that didn't work. I also referenced this article which also didn't work.
What I've tried:
curl -o https://github.com/jdfwarrior/Workflows.git
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
.
wget -r -np -l 1 -A zip https://github.com/jdfwarrior/Workflows.git
zsh: command not found: wget
How can a file be downloaded through the command line?
the -o option means curl writes output to instead of stdout.
Have you made that worked with github URL?
zsh: command not found: wget mean there is no wget package installed. So to use wget you have to install wget first. @Alex Cory
The -o --output option means curl writes output to the file you specify instead of stdout. Your mistake was putting the url after -o, and so curl thought the url was a file to write to rate and hence that no url was specified. You need a file name after the -o, then the url:
curl -o ./filename https://github.com/jdfwarrior/Workflows.git
And wget is not available by default on OS X.
I am not able to download file using above command. I tried below two commands: curl -o "test.zip" -k https://github.com/jonreid/XcodeCoverage.git & curl -o "test.zip" -k https://github.com/jonreid/XcodeCoverage/archive/master.zip
Second command should have worked but it s not working. Can you help me for that?
just curious, but why would you want to use curl for this when you could just use git clone https://github.com/jonreid/XcodeCoverage.git?
@DShah the url has been redirected, so you need add -L flag to instruct cURL to follow any redirect so that you reach the eventual endpoint. This would work: curl -L -o "test.zip" -k github.com/jonreid/XcodeCoverage/archive/master.zip
There is a simple good explanation here and this may be useful. 5-curl-commands-to-download-files
the option/url are reversed, this is the correct command: curl "https://github.com/jdfwarrior/Workflows.git" -o ./filename
curl -OL https://github.com/jdfwarrior/Workflows.git
-O: This option used to write the output to a file which named like remote file we get. In this curl that file would be Workflows.git.
-L: This option used if the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place.
Ref: curl man page
+1 for mentioning relocation :) -L or --location flag is very useful. wget does this automatically, but curl does not.
I recommend to add option --fail or -f to make curl fail (= exit with a non-zero return-code) if the download was not possible. Otherwise it will successfully download an error document.
I also recommend to add option --silent or -s to make curl silent.
Best answer. So many endpoints on the internet have redirects nowadays. Lifesaver. Thanks!
The easiest solution for your question is to keep the original filename. In that case, you just need to use a capital o ("-O") as option (not a zero=0!). So it looks like:
curl -O https://github.com/jdfwarrior/Workflows.git
There are several options to make curl output to a file:
# saves it to myfile.txt
curl http://www.example.com/data.txt -o myfile.txt -L
# The #1 will get substituted with the url, so the filename contains the url
curl http://www.example.com/data.txt -o "file_#1.txt" -L
# saves to data.txt, the filename extracted from the URL
curl http://www.example.com/data.txt -O -L
# saves to filename determined by the Content-Disposition header sent by the server.
curl http://www.example.com/data.txt -O -J -L
# -O Write output to a local file named like the remote file we get
# -o <file> Write output to <file> instead of stdout (variable replacement performed on <file>)
# -J Use the Content-Disposition filename instead of extracting filename from URL
# -L Follow redirects
| common-pile/stackexchange_filtered |
wlan0 No such device found
I m new to linux.
I changed my wifi password and was trying to reconnect to it but I failed when I type
ifconfig wlan0
I get error message. something like no such device found
Welcome to U&L please edit by adding the output of iwconfig and lspci -knn | grep Net -A2 and specify your linux distro
i edited it with the output of iwconfig and lspci -knn | grep Net -A2
i m currently using my net through USB
the answer of @Zumo de Vidrio is correct
how do i connect to my new wifi please provide me steps
Are you sure that you actually have a network device called wlan0? It seems that your wifi NIC is called "wlp5s0".
So how do i connect to any wifi ?
Under systemd your interface is renamed from wlan0 to wlp5s0
After changing the wifi password , clic on Edit connections > select your Wifi > Edit > Wifi Security then change the password. Save and connect from the nm-applet
Also you can edit your connection from the terminal by runing : sudo nmtui
Edit a connection >> select the wifi connecion >> edit >> change the password >> OK
Predictable Network Interface Names
What's systemd and why does it rename the interface?
| common-pile/stackexchange_filtered |
Rubik's Cube solving API in Java
I'm currently building a robot which solves a Rubik's Cube. I use an Android phone to scan the cube and I want to solve it in Android too. Is there a library which can solve a Rubik's Cube?
Thanks in advance
See: http://stackoverflow.com/questions/1354949/easiest-to-code-algorithm-for-rubiks-cube
There is a VB 6.0 source code on this page: http://www.dutchthewiz.com/vb/games/
Porting the algorithm to Java will not be that difficult.
The problem comes in what type of cube you are doing? 2x2, 3x3, 4x4, 5x5 etc. Each of those will use the same algorithm to switch corners and edge pieces, however the trickier part will come with the center blocks.
http://www.wrongway.org/cube/solve.html is a good site to go to, you might be able to talk to the author about his algorithms.
http://www.swinburne.edu.au/ict/videos/media/Rubiks_cube_robot_480X270.html is another interesting site.
Don't be afraid to talk to people who have developed these ideas and solutions. They are sometimes willing to help you design yours.
Check out:
http://sourceforge.net/projects/rubikcube3x3pac/
| common-pile/stackexchange_filtered |
Top aligned label in WidgetKit extension
I am trying to create a WidgetKit extension for one of my apps.
I would like to have a top-aligned label and some dynamic content.
The problem is that all content is centred.
I want the label to be at the top and the container should fill the rest of the space. Within that container are the items (also not centred, starting from the top).
This is my code:
struct WidgetView : View
{
var data: DataProvider.Entry
var body: some View
{
Text("Test")
.font(Font.system(size: 14.0, weight: .medium, design: .default))
.fontWeight(.semibold)
.background(Color.white)
.foregroundColor(Color.red)
.padding(.top, 8.0)
ForEach(0 ..< 2, id: \.self)
{
_ in
Text("This is just some text")
}
}
}
This will result in the following view:
I tried adding a ScrollView and a LazyVStack. Now it looks just like I want it to look, but there is a red circle (probably not allowed in WidgetKit?):
Is this possible? This is my first contact with SwiftUI.
Use VStack with spacer at the bottom
VStack {
Text("Test")
.font(Font.system(size: 14.0, weight: .medium, design: .default))
.fontWeight(.semibold)
.background(Color.white)
.foregroundColor(Color.red)
.padding(.top, 8.0)
ForEach(0 ..< 2, id: \.self)
{
_ in
Text("This is just some text")
}
Spacer()
}
| common-pile/stackexchange_filtered |
How big would a mat multiply be for it to be more effecient to use th gpu
So I've been messing around with OpenCL kernels and I'm trying to understand GPU acceleration a bit better and I'm curious to find out how one would find the point at which it would be more computationally efficient to use GPU acceleration in place of tradition CPU computing
There is no one-fits-all sharp threshold to when GPU parallelization is better as it depends on the hardware. The data transfer from CPU to GPU and back causes latency in the range of milliseconds and needs large amounts of data to run efficiently at full PCIe bandwidth. However since compute time for matrix multiplication scales with N^2, the performance benefits of the GPU will quickly overcome the additional latency. As a rule of thumb:
3x3 matrix -> use CPU
10x10 -> probably CPU is faster
100x100 -> probably GPU is faster
1000x1000 -> definitely GPU
1000000x1000000 -> use GPU, with CPU it would probably take days
There is also cases where it makes sense to do a 3x3 matrix on the GPU: if you have millions of parallel 3x3 matrix multiplications to compute. In this case, you would not parallelize over the matrix elements, but do one 3x3 multiplication sequentially per GPU thread.
As a final remark, on the GPU you should use the cache tiling optimization for large matrix multiplications. This makes it like 10x faster by loading chunks of the matrices in local memory (L2 cache), so it does not have to access the matrix elements multiple times from global memory (VRAM).
| common-pile/stackexchange_filtered |
create new db in mysql with php syntax
I am trying to create a new db called testDB2, below is my code.
Once running the script all I am getting an error on line 7
Fatal error: Call to undefined function mysqlquery() in /home/admin/domains/domain.com.au/public_html/db_createdb.php on line 7
This is my code
<?
$sql = "CREATE database testDB2";
$connection = mysql_connect("localhost", "admin_user", "pass")
or die(mysql_error());
$result = mysqlquery($sql, $connection)
or die(mysql_error());
if ($result) {
$msg = "<p>Databse has been created!</p>";
}
?>
<HTML>
<head>
<title>Create MySQL database</title>
</head>
<body>
<? echo "$msg"; ?>
</body>
</HTML>
UPDATE, now I get error
Access denied for user 'admin_user'@'localhost' to database 'testDB2'
what does this mean?
The function is called mysql_query. Note the _
| common-pile/stackexchange_filtered |
Storybook react-native error in while running on windows not able to make proper stories.require.js file
I have implemented the storybook(v 6.5) in react-native in my root project
when i run the script to run storybook on my device which is andriod and ios
the file which is created IN .ondevice folder is story.require.js is have path issue in windows system it is proper in linux and mac but i am getting the error in windows
this is the file which created in windows system story.require.js
import {
configure,
addDecorator,
addParameters,
addArgsEnhancer,
clearDecorators,
} from "@storybook/react-native";
global.STORIES = [
{
titlePrefix: "",
directory: "./src/components",
files: "**/*.stories.?(ts|tsx|js|jsx)",
importPathMatcher:
"^\\.[\\\\/](?:src[\\\\/]components(?:[\\\\/](?!\\.)(?:(?:(?!(?:^|[\\\\/])\\.).)*?)[\\\\/]|[\\\\/]|$)(?!\\.)(?=.)[^\\\\/]*?\\.stories\\.(?:ts|tsx|js|jsx)?)$",
},
];
import "@storybook/addon-ondevice-notes/register";
import "@storybook/addon-ondevice-controls/register";
import "@storybook/addon-ondevice-backgrounds/register";
import "@storybook/addon-ondevice-actions/register";
import { argsEnhancers } from "@storybook/addon-actions/dist/modern/preset/addArgs";
import { decorators, parameters } from "./preview";
if (decorators) {
if (__DEV__) {
// stops the warning from showing on every HMR
require("react-native").LogBox.ignoreLogs([
"clearDecorators is deprecated and will be removed in Storybook 7.0",
]);
}
// workaround for global decorators getting infinitely applied on HMR, see https://github.com/storybookjs/react-native/issues/185
clearDecorators();
decorators.forEach((decorator) => addDecorator(decorator));
}
if (parameters) {
addParameters(parameters);
}
try {
argsEnhancers.forEach((enhancer) => addArgsEnhancer(enhancer));
} catch {}
const getStories = () => {
return {
"./srccomponentsCustomButtonCustomButton.stories.tsx": require("..srccomponentsCustomButtonCustomButton.stories.tsx"),
"./srccomponentsCustomCheckBoxCustomCheckBox.stories.tsx": require("..srccomponentsCustomCheckBoxCustomCheckBox.stories.tsx"),
"./srccomponentsCustomTextCustomText.stories.tsx": require("..srccomponentsCustomTextCustomText.stories.tsx"),
};
};
configure(getStories, module, false);
the file which is correctly created in linux and mac is this
is there any solution for the forword \ backword / issue that is being created with the storybook
for the .ondevice folder
I have tried the path.resolve() and replace is not working
import {
configure,
addDecorator,
addParameters,
addArgsEnhancer,
clearDecorators,
} from "@storybook/react-native";
global.STORIES = [
{
titlePrefix: "",
directory: "./src/components",
files: "**/*.stories.?(ts|tsx|js|jsx)",
importPathMatcher:
"^\\.[\\\\/](?:src\\/components(?:\\/(?!\\.)(?:(?:(?!(?:^|\\/)\\.).)*?)\\/|\\/|$)(?!\\.)(?=.)[^/]*?\\.stories\\.(?:ts|tsx|js|jsx)?)$",
},
];
import "@storybook/addon-ondevice-notes/register";
import "@storybook/addon-ondevice-controls/register";
import "@storybook/addon-ondevice-backgrounds/register";
import "@storybook/addon-ondevice-actions/register";
import { argsEnhancers } from "@storybook/addon-actions/dist/modern/preset/addArgs";
import { decorators, parameters } from "./preview";
if (decorators) {
if (__DEV__) {
// stops the warning from showing on every HMR
require("react-native").LogBox.ignoreLogs([
"clearDecorators is deprecated and will be removed in Storybook 7.0",
]);
}
// workaround for global decorators getting infinitely applied on HMR, see https://github.com/storybookjs/react-native/issues/185
clearDecorators();
decorators.forEach((decorator) => addDecorator(decorator));
}
if (parameters) {
addParameters(parameters);
}
try {
argsEnhancers.forEach((enhancer) => addArgsEnhancer(enhancer));
} catch {}
const getStories = () => {
return {
"./src/components/CustomText/CustomText.stories.tsx": require("../src/components/CustomText/CustomText.stories.tsx"),
};
};
configure(getStories, module, false);
please provide some idea to reolve the path issue in the windows
| common-pile/stackexchange_filtered |
Query dimension in Star Schema
During report creation, I've included data from only dimensions (no measures), and records from them are cross joined. Can you query only dimensions from the Star Schema in a report? For example in the following simple SSAS cube, can I query Subject and Student to see how many students were there per course?:
Can you provide a example of a query you are trying to make? The answer to your question depends on what you are trying to accomplish.
I've added more explanation if that helps...
That helps. I'll post a suggestion on weekend
Did you get time for this?
Nancy - is it possible for the students to be enrolled into a course but have no score (i.e, they are absent from the fact table)?
It is possible. But, in this case I have assumed that everyone has score.
| common-pile/stackexchange_filtered |
Displaying integer values on SliderRow
I'm trying display the integer values instead of float. I tried the following:
section.append(SliderRow() {
$0.title = "Number of items"
$0.tag = "numberOfItems"
$0.minimumValue = 1
$0.maximumValue = 10
$0.steps = 10
$0.value = 5
$0.onChange { row in
let isInteger = floor(row.value!) == row.value!
if (!isInteger) {
row.value = floor(row.value!)
}
let formattedString = String(format: "%.0f", row.value!)
row.cell.valueLabel.text = formattedString
}
})
formattedString displays the values I want but I'm not able to display them on the screen. I can access all other attributes by row.cell. I change change the text colour, for instance, but not the text. I'm guessing I'm setting the text but it gets overwritten shortly.
Is there a way to make the slider show integer values?
Thanks.
Can you pls put some more code where you are changing UILabel text or something is dependent?
@SohilR.Memon: I've updated it with the full code I use for the row. I hope that's what you meant. I think that's all the relevant code I have but please let me know if I should look into something else.
Can you put some static String to check whether its displaying or not?
I tested with a print(formattedString) right where I set the valueLabel.text. It prints, for instance, "2" in the debug window but "2.0" in the actual label
and I tried setting a static string but it doesn't display. It may still be overwritten
So now, I hope the problem is with the other code which you haven't mentioned here.
There is no other code that is relevant to this row. I can change the colour of the cell so I now I can manipulate some values but it overwrites the text. Not displaying static string doesn't prove that it's setting it correctly but getting overwritten afterwards.
since Dec 2, 2016, there's a much simpler approach.....
$0.displayValueFor = {
return "\(Int($0 ?? 0))"
}
(credit to https://github.com/xmartlabs/Eureka/issues/817 showing how to do it - and the associated fix)
This works great for showing an Int in the Eureka SliderRow as well as StepperRow
See this picture of xcode Simulator showing Int values on StepperRow and SliderRow
To resolve the issue I cloned the Eureka repository. Turns out I was right about overwriting the values. To test it I set the text to a constant value inside onChange handler, then added print statements in the SliderRow source code in valueChanged function:
if shouldShowTitle() {
print("current value: \(valueLabel.text)" )
valueLabel.text = "\(row.value!)"
print("updated value: \(valueLabel.text)" )
}
The output looked like this:
current value: Optional("xyz")
updated value: Optional("3.0")
current value: Optional("xyz")
updated value: Optional("5.0")
So I created myself a SliderRowInt class that uses integers:
public final class SliderRowInt: Row<Int, SliderCellInt>, RowType {
public var minimumValue: Int = 0
public var maximumValue: Int = 10
public var steps: UInt = 20
required public init(tag: String?) {
super.init(tag: tag)
} }
Now I'm using the integer version. Maybe not the most elegant solution but it worked fine for me.
There's a similar issue with the StepperRow which I solved the same way.
I checked in both classes to my cloned repository in case anyone encounters the same problem they can be found here: https://github.com/volkanx/Eureka/
| common-pile/stackexchange_filtered |
Converting counts to individual observations in r
I have a data set that looks as follows
df <- data.frame( name = c("a", "b", "c"),
judgement1= c(5, 0, NA),
judgement2= c(1, 1, NA),
judgement3= c(2, 1, NA))
I want to reshape the dataframe to look like this
# name judgement1 judgement2 judgement3
# a 1 0 0
# a 1 0 0
# a 1 0 0
# a 1 0 0
# a 1 0 0
# b 1 0 0
# b 0 1 0
# b 0 0 1
And so on. I have seen that untable is recommended on some other threads, but it does not appear to work with the current version of r. Is there a package that can convert summarised counts into individual observations?
Are you sure that is the wanted output? If so, please explain the rules to get that output.
Yes. I am sure. The rule would be to expand the value in each judgement column, so that there is one observation per row.
@user183974 S Rivero is pointing out that there should be 3 more name: a rows for judgement2 and judgement3.
You could try something like this:
df <- data.frame( name = c("a", "b", "c"),
judgement1= c(5, 0, NA),
judgement2= c(1, 1, NA),
judgement3= c(2, 1, NA))
rep.vec <- colSums(df[colnames(df) %in% paste0("judgement", (1:nrow(df)), sep="")], na.rm = TRUE)
want <- data.frame(name=df$name, cbind(diag(nrow(df))))
colnames(want)[-1] <- paste0("judgement", (1:nrow(df)), sep="")
(want <- want[rep(1:nrow(want), rep.vec), ])
I wrote a function that works to give you your desired output:
untabl <- function(df, id.col, count.cols) {
df[is.na(df)] <- 0 # replace NAs
out <- lapply(count.cols, function(x) { # for each column with counts
z <- df[rep(1:nrow(df), df[,x]), ] # replicate rows
z[, -c(id.col)] <- 0 # set all other columns to zero
z[, x] <- 1 # replace the count values with 1
z
})
out <- do.call(rbind, out) # combine the list
out <- out[order(out[,c(id.col)]),] # reorder (you can change this)
rownames(out) <- NULL # return to simple row numbers
out
}
untabl(df = df, id.col = 1, count.cols = c(2,3,4))
# name judgement1 judgement2 judgement3
#1 a 1 0 0
#2 a 1 0 0
#3 a 1 0 0
#4 a 1 0 0
#5 a 1 0 0
#6 a 0 1 0
#7 b 0 1 0
#8 a 0 0 1
#9 a 0 0 1
#10 b 0 0 1
And for your reference, reshape::untable consists of the following code:
function (df, num)
{
df[rep(1:nrow(df), num), ]
}
| common-pile/stackexchange_filtered |
Ubuntu 19.10 Upgrade
I upgraded my pc fomr 19.04 to ubuntu 19.10 i ran the upgrade unattended at night but when i checked the PC in the morning the power was interrupted and the PC was shutdown . I don't know when the power was interrupted .
But after swithching on the PC it Booted normally but would not show the login screen instead a message showing
dev/sda8 clean , files xxxxxx/xxxxx
blocksxxx/xxxxx
i could login to tty emergency terminal ; also random login attempts are successful the login screen appears and i am able to login or it is a login loop. but after booting into recovery mode for ubuntu 19.10 from advanced options in grub menu i was able to login, i also ran repair dsmg packages in the recovery options .Now the normal login also works but it takes long time for the Gnome Desktop to be loaded after the boot process .
Also it Displays
Ubuntu 19.10
during random boot attempts.
But other times its the maroon color background and suddenly goes black after displaying a blinking underscore AND THE FSCK MESSAGE and after a long time the Gnome DESKTOP environment Loads with the login screen. Is the Gnome DEsktop Environment corrupted or is there some other issue.
This question is specific to a release of Ubuntu which has reached its end of standard support or end of life date, and is not related to asking for help to upgrade to a supported release.
A power outage can cause severe hammock. If your technical skills are moderate, by far the fastest, easiest and best option will be to reinstall from scratch. A "fresh" reinstall, i.e., where you install the new operating system on an empty disk, is always so much better than an in-place upgrade of an existing system. It takes no more than 45 minutes on an older system to have a fully working new (but not customized) installation.
Alternatively, you could try repairing a corrupt system by reinstalling, however without reformatting the partitions. That way, your user data and user configuration is preserved. To do so, load the installer from the live CD or USB, then select "Something else" as installing option. This brings you to a partitioning screen. There, you need to indicate the same partitions as these from the previous installations, and uncheck the "Format" mark to indicate the partitions should not be reformatted before installation.
I strongly recommend a fresh re-installation, though.
but can try reinstalling the Gnome Desktop Environment to see if it solves the issue
| common-pile/stackexchange_filtered |
Saving out multiple files in Windows Store
I have a windows store app that uses an internal file library hosted in localstorage. Is there anyway to export these en masse without needing to make the user choose a location / file name for each file?
I know I can zip them up and export the zip, but I was hoping to allow the user to choose a folder and then save a series of text files into that folder. Is this possible?
I'm not looking for someone to write my code for me, just point me in the right direction
Get the files in a List (from LocalStorage)
run a foreach loop (for the List<Files>)
let user choose the location once (in phone memory or m/m card)
and then simply copy all files in the same location one by one through the foreach loop (because you have the StorageFolder, you can use StorageFile's CopyAsync method)
I've done this in my WP store App (kind of File Explorer).
Hope this helps..!
| common-pile/stackexchange_filtered |
LMEM for low number of data points?
I have DNA and RNA counts of 4 time points with 4 replicates. I want to quantitate the change in RNA copy number relative to DNA copy number for each gene in the genome. I especially interested to test if there is a linear relationship between these two. I am thinking of using linear mixed effect regression model to account for the replicates.
I am concerned that I have too few data points for calculating a slope and R squared.
Are there any alternatives to study the DNA-RNA relationship and also account for the inter-replicate variability that I can try? Or is it okay to go ahead with linear mixed effect models?
| common-pile/stackexchange_filtered |
how to fix this code in lua for splash in a scrapy splash project?
I have a [link] (https://www.psychologytoday.com/us/therapists/35801) that I want to submit a contact form for. I know I have to use 3rd party services because there is a recaptcha but I can't seem to load the script. I keep getting a table error instead of a button click
I have already done a for loop and do a mouse click but it does not work. the selector i have used is "div.result-btn-email button" and it works in chrome dev tools
function main(splash, args)
local function submit_forms()
local btns = splash:select_all('div.result-btn-email button')
if #btns == 0 then
error('no elements found')
end
for _, btn in ipairs(btns) do
print(btn, 'found button')
splash:wait(1)
btn:mouse_click()
print(btn, ' found buttn')
end
end
assert(splash:go(args.url))
assert(splash:wait(0.5))
submit_forms()
return {
html = splash:html(),
png = splash:png(),
har = splash:har(),
}
end
i know this is incomplete code but this still does not work i keep getting an error:
{
"type": "ScriptError",
"info": {
"type": "LUA_ERROR",
"message": "Lua error: [string \"function main(splash, args)\r...\"]:11: JsError({'js_error': \"TypeError: undefined is not an object (evaluating 'rect.left')\", 'type': 'JS_ERROR', 'message': 'JS error: \"TypeError: undefined is not an object (evaluating \\'rect.left\\')\"', 'js_error_message': \"undefined is not an object (evaluating 'rect.left')\", 'js_error_type': 'TypeError'},)",
"line_number": 11,
"error": "JsError({'js_error': \"TypeError: undefined is not an object (evaluating 'rect.left')\", 'type': 'JS_ERROR', 'message': 'JS error: \"TypeError: undefined is not an object (evaluating \\'rect.left\\')\"', 'js_error_message': \"undefined is not an object (evaluating 'rect.left')\", 'js_error_type': 'TypeError'},)",
"source": "[string \"function main(splash, args)\r...\"]"
},
"error": 400,
"description": "Error happened while executing Lua script"
}
I m a newbie to lua and would love some great help and resources to learn lua
| common-pile/stackexchange_filtered |
Adding subdomain constraint
I currently have the following line in route.rb file
resources :pages, only: %i[index show create]
Moving forward I want my users to access pages#show through a dedicated subdomain. So I've added the following line:
constraints subdomain: 'pages' do
get '/:id' => 'pages#show'
end
(I'm planning on keeping both routes for retro-compatibility)
Which allows users the access it through pages.mydevdomain.com/my-page-id
When doing so in development environment I get the following message:
To allow requests to pages.mydevdomain.com, add the following to your environment configuration:
config.hosts << "pages.mydevdomain.com"
Which I've done and it works. However if I got to http://pages.mydevdomain.com then I get to see the whole app I built which means that this subdomain isn't just for pages#show like I wanted it.
My understanding of this constraint is that you can only access the pages#show action through the subdomain. But you are also allowing access using the resources method. So the constraint has no effect.
You are not restricting access to any other controller. Maybe you want to wrap your routes like this:
constraints subdomain: '' do
resources :pages, only: %i[index show create]
end
constraints subdomain: 'pages' do
get '/:id' => 'pages#show'
end
The main issue is that not only resources :pages, only: %i[index show create] is accessible through the subdomain but the entire app.
Like I said. If you want to restrict access to the entire application you need put a constraint around those routes as well.
| common-pile/stackexchange_filtered |
Proper location for installing packages?
What is the 'correct' location(s) to install packages/software in a Unix file system? I realize it will vary somewhat depending on the distribution you're using and the package you're installing, but I can't seem to find any tutorials that aid in deciding where it makes sense to install something.
For example, I'm currently trying to get a Ubuntu server up and running. I'm would like to install a variety of things (mysql, mercurial, ruby on rails, radiant), and I can find plenty of tutorials that say to "install in /pick/your/directory", but nothing that seems to say what the logical choice for '/pick/your/directory' would be or how to go about deciding what '/pick/your/directory' should be (if there is no universal location).
It's rather complicated. On ubuntu, I'd install as much as possible from apt, rather than compiling your own. If you do need to compile your own, the general Unix guidelines are here, and Ubuntu follows debian packaging guidelines, which can be found here.
I agree. Your best bet is to use the packaged version if one exists. I only install manually if there's no deb package or I need a bleeding edge version. Easy updates and uninstalls are well worth having a slightly older version (assuming you have the functionality you need.)
For things like mysql etc. you should really consider installing using the ubuntu packages via apt. This makes it much easier to manage upgrades. The system packages will decide the correct locations to be installed.
If you do want/need to compile/install your own stuff manually then the correct place to do this on debian/ubuntu systems is /usr/local. The debian packaging rules specifically reserve /usr/local for software manually installed manually by the system admin.
apt-get
For Ubuntu server I'd highly recommend using apt-get:
To install a package:
sudo apt-get install packageName
To remove a package:
sudo apt-get remove packageName
apt-get will install the packages in the default directories they were intended for. This will help when you're reading the documentation and see examples in specific paths.
You might also want to look up additional apt-get commands such as "update" and "upgrade".
Roll your own
Installing the packages manually or compiling from source is a bit more difficult but just the same... take a look at the documentation and see if you can figure out where the software designers "intended" the package to go. Most of the time you can figure it out from the docs. If not, a quick Google search will usually show where "most" people put their packages.
| common-pile/stackexchange_filtered |
Implementing Background notification handler on flutter one signal sdk
I am trying to implement the background notification handler in flutter for the one signal flutter sdk. What I am trying to do is call a method in flutter side when a background notification arrives like in the OneSignal docs suggests https://documentation.onesignal.com/docs/service-extensions#android-notification-extender-service .
This is my MainActrivity.kt
import androidx.annotation.NonNull
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import com.onesignal.OneSignal.OSRemoteNotificationReceivedHandler;
var channel: MethodChannel? = null
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/notification";
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine){
super.configureFlutterEngine(flutterEngine);
channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL);
}
}
public class NotificationServiceExtension : OSRemoteNotificationReceivedHandler{
override fun remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
channel.invokeMethod("testNotification");
}
}
I have never written Kotlin code before and maybe I am doing something wrong here as this is resulting in build errors. Has anyone here done something similar before? Would really appreciate any help. Thanks in advance!
onesignal_flutter: 3.2.8
flutter doctor :
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.1, on Ubuntu 20.04.3 LTS 5.13.0-30-generic,
locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] Android Studio
[✓] VS Code
[✓] Connected device (2 available)
[✓] HTTP Host Availability
For this reason I don't use OneSignal, you can see my answer here https://stackoverflow.com/a/71331313/2877427
| common-pile/stackexchange_filtered |
Why I am not able to push a config file into logstash path using Nodejs ? The below is my code for pushing a file from localserver to logstash server
I am first downloading a config file locally then I have to push that file into logstash server in the path - /etc/logstash/conf.d
const deployLogstash = function(req , res , next){
clientscp.scp('./config-files/15287774.conf', {
host: '<IP_ADDRESS>',
port:5000,
username: 'ubuntu',
path: 'root@vm2:/etc/logstash/conf.d/newconfig.conf'
}, function(err,success) {
if(err){
console.log("files failed to upload in remote server"+err);
}
else{
console.log("files uploaded to remote server")
}
});
}
And this is the console.log
serverError: connect ECONNREFUSED <IP_ADDRESS>:5000
Is there any way I could transfer config files to that path?Please help me!
Can you explain what you are trying to do? If you want to put a file inside /etc/logstash/conf.d, you need to use scp or ssh into the server and paste the file, making a request to elasticsearch has nothing to do with deploying files in a server.
Hii @leandrojmp, yes i corrected the code and I am using scp client but now, I am getting serverError: connect ECONNREFUSED <IP_ADDRESS>:5000. The logstash server is up and running I am not sure whats wrong
SCP uses the same port as SSH, which is port 22 per default, you want to put a file in a directory on a remote server, this has no relation to Logstash or Elasticsearch. Check the link in the Answer below, this should put you in the right direction.
Adding to what @leandrojmp has already mentioned
The URI parameter you're using is of elasticsearch i.e. <hostname>:9200(elasticsearch's port) which meant for sending the contents of a files over elasticsearch indexes as events(termed as documents in Elastic-stack's terminology) But based on the information you've provided, I assume you're trying to upload a config file to your logstash's server directory.
You might wanna read about multer for uploading Files to remote server using multer-sftp, scp, ssh together as mentioned here in this link
Thanks, I tried with ssh client and now i am able to transfer files to remote server.
| common-pile/stackexchange_filtered |
How does Jira "resolved" field (or its alias name "resolutionDate") get set?
I am new to Jira and I have just joined a new team that is using Jira. We have a problem with our Jira Service Desk project's workflow. It looks like some months ago when an issue was moved to Resolved status, the Jira workflow successfully set a "resolved" field (which also has an alias name "resolutionDate") which is needed for reporting. However some months ago this field stopped updating, now it is no longer being set. It is suspected an ex-team member may have broken it while modifying the workflow. Can you guide me in how to fix this?
I can see from this fields reference page that resolution / resolutiondate is a standard field.
Is there anywhere I can find more documentation for the field? Or how Jira workflows set their standard fields?
Should I be able to see the field being set in the out-of-the-box service desk workflow somewhere? i.e. where do I need to check?
I think you should look on the triggers of that transition. Maybe compare it with the default workflow that comes with a new service desk project
You need to have admin access. Go to the admin section for the project in question and find the workflow on the left navigation bar.
You may have different workflows for different issue types. Nevertheless, the workflows should have a mapping of the arbitrary states (to do, parked, in progress, testing, etc) two 3 standard jira states: To Do, In Progress, Done.
AFAIK, moving any issue to a done state sets the resolution.
To edit the resolution fields, go to Resolution in the left pane. This article come might in handy:
https://confluence.atlassian.com/adminjiraserver073/defining-resolution-field-values-861253253.html
| common-pile/stackexchange_filtered |
jQuery append - what am I doing wrong?
I am just struggling beyond belief with jQuery. I have looked at dozens of ways of adding a new input field but keep getting stuck right at the beginning. I don't see how this could be simpler.
<div class="container">
<p>If you click on me, I will disappexxxxxxar.</p>
<p id="thisone">Click this onexxxx me away!</p>
<p id="thixxsone2">Click 2pppp22222hover me too!</p>
<input type="checkbox" id="chk">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> window.jQuery||document.write("<script src='../vendor/jquery/jquery-1.11.3.min.js'><\/script>")</script>
<script src="../vendor/bootstrap/js/bootstrap.js"></script>
<script src="../custom/js/custom.js"></script>
<script>
$("#chk").on("change",function(){
$("#chk").append('<input type="text" />');
}
)
</script>
I will be adding a if ($("#chk").is(":checked")) which seems to work fine.
I went through W3 jQuery but it was too short. Anyone know of another online "course"?
OK sorry guys have tried solutions but not working on my simple page. I need to clean it right out and start again. Thanks for efforts will report back.
The W3 - so far as I know - offer no jQuery 'course,' you may have referred to 'w3schools" which has no connection to the W3C at all, though they deliberately named themselves to imply a connection. If you want to learn about jQuery you'd be best off looking to the jQuery docs: API.jQuery.com.
With the help of an old StackOverflow question(onClick add input field), I wrote an example that uses jquery append and works:
Html
<button id="add">Add input field</button><p id="main"></p>
js
$('#add').on('click', function () {
$('#main').append('<input type="aText" id="aText"><br>');
});
https://jsfiddle.net/uhhr60pj/
Hope that helps.
Yep thanks worked great. Now all I have do is about another 20 clever things on top of this. Cannot work out why I am so slow at jQuery.
Don't worry, it just takes practice. You asked for a more online jQuery help, here's a list of jQuery courses and tutorials: http://www.tutset.com/frontend/jquery/
1st: what this line expect to do??
<script> window.jQuery||document.write("<script src='../vendor/jquery/jquery-1.11.3.min.js'><\/script>")</script>
2nd: good to wrap your code after document ready .. and you can use .append for your input parent() .. this will append new input after checkbox input
<script>
$(document).ready(function(){
$("#chk").on("change",function(){
if($(this).is(":checked")){
$(this).parent().append('<input type="text" />');
}
});
</script>
Mohamed thanks it was not working on my page but you had a fiddle up and that worked fine QED something wrong with my page. Have to leave for about an hour then will clean up page. Please stand by and thanks. Shukran
Regarding your question to the OP, "[that] line" will simply write a script element into the document if window.jQuery is a false/falsey value. It's a hideous practice, but I think that's the intent of it.
Mohamed can't get it to do anything sorry. As to the line yep found it as a check on access to google jQuery. David why is it horrible. Absolutely non essential - just curious.
@DavidThomas Thanks .. I just seeing he included jquery in a right way from ajax.googleapis.com cause of that I asked .. I thought that line can make conflicts with the main jquery .and I didn't use that line before in any of my projects . but I will read about this :)
@OldMauiMan never mind, Just you reached the answer you need .. and that's it .. Good Luck :)
Thanks. But as I want something to appear when the box is checked - that is my next step -I may be back.... You have been warned.
You have one main problem with your code in your question:
$("#chk").on("change",function(){
$("#chk").append('<input type="text" />');
});
The problem is that an <input> is a void element:
A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.
The following is a complete list of the void elements in HTML:
area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr
Citation: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements, accessed 01:00, 2015-11-23.
Because jQuery – almost always – fails silently it never alerts you to the fact that you're trying to achieve the impossible (literally: the impossible); so instead you have to append the elements elsewhere, such as after (or before) the given element.
// bind the anonymous function of the
// on() method to handle the change
// event of the '#chk' element:
$('#chk').on('change', function() {
// on the assumption you only want
// to append elements when the element
// is in fact checked:
if (this.checked) {
// creating the <input> element:
$('<input />', {
// setting its 'type' attribute/property:
'type': 'text',
// setting its 'placeholder' attribute:
'placeholder': 'input number: ' + $('input[type=text]').length
// inserting the <input> after the '#chk' element:
}).insertAfter(this);
}
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!-- I removed the irrelevant HTML -->
<label>Click to add a new input element (when checked):
<input type="checkbox" id="chk">
</label>
</div>
As you can see when you check the check-box this appends the new <input> directly after that check-box. Since I don't expect that's what you want to do, I'd suggest amending the above, to access the parent – <div> – element:
// bind the anonymous function of the
// on() method to handle the change
// event of the '#chk' element:
$('#chk').on('change', function() {
// on the assumption you only want
// to append elements when the element
// is in fact checked:
if (this.checked) {
// creating the <input> element:
$('<input />', {
// setting its 'type' attribute/property:
'type': 'text',
// setting its 'placeholder' attribute:
'placeholder' : 'input number: ' + $('input[type=text]').length
// appending the <input> element to the parentNode of the
// '#chk' element:
}).appendTo(this.parentNode);
}
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!-- I removed the irrelevant HTML -->
<label>Click to add a new input element (when checked):
<input type="checkbox" id="chk">
</label>
</div>
References:
jQuery:
appendTo().
insertAfter().
on().
David wow. This was just a two line code check. I will look at this later as my head is exploding. I DID however expect the input to come directly after the checkbox - this was just a tiny incremental test. (If I don't understand something I build it up in tiny ugly steps!) As to the input being a void element - yes I was aware of that. I did NOT realize that would be a problem (not sure why) but in any case Katie's solution worked fine. (So???) I am however extremely grateful for your full answer. Some of your code will be very helpful when I build up the next layer of ugly complexity.
| common-pile/stackexchange_filtered |
Insertion function for linklist is not working
My code:
def __init__(self):
self.data = ""
self.NextPointer = -1
def InsertLinkList(LinkList, StartPointer, FreePointer):
if FreePointer < len(LinkList):
data = int(input("Enter the data"))
newNode = FreePointer
LinkList[FreePointer].data = data
LinkList[FreePointer].NextPointer = -1
print(LinkList)
FreePointer = LinkList[FreePointer].NextPointer
if StartPointer == -1:
StartPointer = newNode
else:
currentPointer = StartPointer
while currentPointer != -1:
lastNode = currentPointer
currentPointer = LinkList[currentPointer].NextPointer
LinkList[lastNode].NextPointer = newNode
else:
print("List is full")
return LinkList, StartPointer, FreePointer
def PrintAll(LinkList):
for i in range(10):
print(LinkList[i].data)
LinkList = [Node() for i in range(10)]
StartPointer = -1
FreePointer = 0
for i in range(10):
LinkList, StartPointer, FreePointer = InsertLinkList(LinkList, StartPointer, FreePointer)
PrintAll(LinkList)
Hello everyone,
I recently uploaded my code for link list insertion, but I am encountering some issues with its functionality. The insertion process is not happening as expected, and I am in need of assistance in understanding and resolving this problem.
If anyone has expertise in working with link lists and is willing to lend a hand, I would greatly appreciate your help.
My Output Looks like:
Enter the data1
Enter the data2
Enter the data3
Enter the data4
Enter the data5
Enter the data6
Enter the data7
Enter the data8
Enter the data9
Enter the data11
1
11
FreePointer = LinkList[FreePointer].NextPointer, this makes FreePointer -1 in the first iteration onwards. So, from next time onwards the last node is being populated
When I review your code, I'm having trouble understanding it. I am currently learning about data structures, so I can provide code for inserting into a linked list.
In my code, I have tried out many ways to insert into a linked list. I have written it in a way that everyone can understand, so if there are any doubts, let me know.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# to insert node at the beginning.
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# to insert node at the specified index
def insert_at_index(self, index, data):
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current_node = self.head
i = 0
while current_node and i < index-1:
current_node = current_node.next
i += 1
if current_node is None:
print("index out of range")
else:
new_node.next = current_node.next
current_node.next = new_node
# to insert node before the specified node.
def insert_before_node(self, node_data, data):
new_node = Node(data)
if self.head.data == node_data:
new_node.next = self.head
self.head = new_node
else:
current_node = self.head
while current_node.next:
if current_node.next.data == node_data:
new_node.next = current_node.next
current_node.next = new_node
return
current_node = current_node.next
print(f"{node_data} is not in the list")
# to insert node after the specified node.
def insert_after_node(self, node_data, data):
new_node = Node(data)
current_node = self.head
while current_node:
if current_node.data == node_data:
new_node.next = current_node.next
current_node.next = new_node
return
current_node = current_node.next
print(f"{node_data} is not in the list")
# to insert node at the end.
""" if tail is provided then we can do this function in O(1) time. """
def append(self, data):
new_node = Node(data)
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
# to print the list.
def show(self):
current_node = self.head
while current_node:
print(current_node.data, end=" ")
current_node = current_node.next
list_1 = LinkedList()
list_1.insert_at_beginning(0)
list_1.append(1)
list_1.append(2)
list_1.insert_at_index(3, 3)
list_1.insert_after_node(3, 5)
list_1.insert_before_node(5, 4)
list_1.show()
| common-pile/stackexchange_filtered |
Excel VBA - convert range with pictures and buttons to HTML
I wrote a function that turns an excel range into HTML for further use in an email body. The problem is that I now want to add pictures and buttons to the range and have it then taken over into the email body.
How I can get excel to address objects in the range and convert them over as well?
Thanks
Function Range to HTML
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2013
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Copy the range and the object to a new workbook and then save the workbook as an html
That would give me a html file, what I need is the html code if the range content which I then use in an emails body.
Yes when you copy only selected range+object to a new workbook and save it as html then you get an html for only that. Read the html file in a string and then set the .HTMLBody to that string.
As I mentioned in the comments above, copy the range and the object to a new workbook and then save the workbook as an html. Read the html file in a string and then set the .HTMLBody to that string after making a slight change.
Important:
Save the html file in an empty folder. I pasted the excel file which contains the code and data in an empty folder.
Tested in Excel 2013
Let's say our workbook looks like this
See the code below. I have commented the code so you should not have a problem understanding it. Still if you do then post back.
Code:
Option Explicit
'~~> This is the temp html file name.
'~~> Do not change this as when you publish the
'~~> html file, it will create a folder Temp_files
'~~> to store the images
Const tmpFile As String = "Temp.Htm"
'~~> Do not change "Myimg". This will be used to
'~~> identify the images
Const imgPrefix As String = "Myimg"
Sub Sample()
Dim wbThis As Workbook, wbNew As Workbook
Dim tempFileName As String, imgName As String, newPath As String
Set wbThis = ThisWorkbook
Set wbNew = Workbooks.Add
'~~> Copy the relevant range to new workbook
wbThis.Sheets("Sheet1").Range("A1:J17").Copy _
wbNew.Worksheets("Sheet1").Range("A1")
newPath = ThisWorkbook.Path & "\"
tempFileName = newPath & tmpFile
'~~> Publish the image
With wbNew.PublishObjects.Add(xlSourceRange, _
tempFileName, "Sheet1", "$A$1:$J$17", xlHtmlStatic, _
imgPrefix, "")
.Publish (True)
.AutoRepublish = True
End With
'~~> Close the new file without saving
wbNew.Close (False)
'~~> Read the html file in a string in one go
Dim MyData As String, strData() As String
Dim i As Long
Open tempFileName For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Loop through the file
For i = LBound(strData) To UBound(strData)
'~~> Here we will first get the image names
If InStr(1, strData(i), "Myimg_", vbTextCompare) And InStr(1, strData(i), ".Png", vbTextCompare) Then
'~~> Insert actual path to the images
strData(i) = Replace(strData(i), "Temp_files/", newPath & "Temp_files\")
End If
Next i
'~~> Rejoin to get the new html string
MyData = Join(strData, vbCrLf)
'~~> Create the Email
Dim OutApp As Object, OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "Email address Goes here"
.Subject = "Subject Goes here"
'~~> Set the body
.HTMLBody = MyData
'~~> Show the email. Change it to `.Send` to send it
.Display
End With
'~~> Delete the temp file name
Kill tempFileName
End Sub
Output:
Converted it to a Function
Option Explicit
Private Function RngToEmail(rng As Range, eTo As String, eSubject As String)
Dim wbThis As Workbook, wbNew As Workbook
Dim tempFileName As String, imgName As String, newPath As String
'~~> Do not change "Myimg". This will be used to
'~~> identify the images
Dim imgPrefix As String: imgPrefix = "Myimg"
'~~> This is the temp html file name.
'~~> Do not change this as when you publish the
'~~> html file, it will create a folder Temp_files
'~~> to store the images
Dim tmpFile As String: tmpFile = "Temp.Htm"
Set wbThis = Workbooks(rng.Parent.Parent.Name)
Set wbNew = Workbooks.Add
'~~> Copy the relevant range to new workbook
rng.Copy wbNew.Worksheets("Sheet1").Range("A1")
newPath = wbThis.Path & "\"
tempFileName = newPath & tmpFile
'~~> Publish the image
With wbNew.PublishObjects.Add(xlSourceRange, _
tempFileName, "Sheet1", Rng.Address, xlHtmlStatic, _
imgPrefix, "")
.Publish (True)
.AutoRepublish = True
End With
'~~> Close the new file without saving
wbNew.Close (False)
'~~> Read the html file in a string in one go
Dim MyData As String, strData() As String
Dim i As Long
Open tempFileName For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Loop through the file
For i = LBound(strData) To UBound(strData)
'~~> Here we will first get the image names
If InStr(1, strData(i), "Myimg_", vbTextCompare) And InStr(1, strData(i), ".Png", vbTextCompare) Then
'~~> Insert actual path to the images
strData(i) = Replace(strData(i), "Temp_files/", newPath & "Temp_files\")
End If
Next i
'~~> Rejoin to get the new html string
MyData = Join(strData, vbCrLf)
'~~> Create the Email
Dim OutApp As Object, OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = eTo
.subject = eSubject
'~~> Set the body
.HTMLBody = MyData
'~~> Show the email. Change it to `.Send` to send it
.Display
End With
'~~> Delete the temp file name
Kill tempFileName
End Function
Usage:
Sub Sample()
RngToEmail ThisWorkbook.Sheets("Sheet1").Range("A1:J17"<EMAIL_ADDRESS>"Some Subject"
End Sub
that is an excellent sample for me to study, thank you. My only question is why did you manually define range A1:J17 in the Function under "Publishing the image"? Shouldnt this range be defined dynamically via the range given upon the function call?
Also, the range is shown in the email body as centered and with different column widths / row heights. Is there a way to keep the original formatting of the selected range?
Yes you are right. I missed that. Just replace "$A$1:$J$17" with rng.Address in the funciton. Regarding the col width and formatting I am sure that can be customized as well :)
| common-pile/stackexchange_filtered |
Twitter Bootstrap 3: Aligning columns to container content
I know how to solve this issue using CSS that overrides Bootstrap's compiled CSS, but it seems to me this alignment issue is such a common use case that I must have misunderstood how to use the Bootstrap framework. (First time with Bootstrap.)
Case: The columns in container B (JSFiddle) do not align with the content in container A, because Bootstrap generates a 15px left/right padding to each column.
<section class="container A">
<h1>About Us</h1>
<p>Lorem</p>
</section>
<section class="container B">
<div class="col-md-3">
<h2>Hiya!</h2>
<p>Lorem ipsum</p>
</div>
<div class="col-md-3">
<h2>Hiya!</h2>
<p>Lorem ipsum</p>
</div>
<div class="col-md-3">
<h2>Hiya!</h2>
<p>Lorem ipsum</p>
</div>
<div class="col-md-3">
<h2>Hiya!</h2>
<p>Lorem ipsum</p>
</div>
</section>
Question: Is there a way I can make the column content align to the container A content, by changing the HTML only, without using any CSS?
Setup: I'm required to use Twitter bootstrap 3.0.0 for the above.
OT: As you see this is my first post on SO, I'm grateful for any advice on how to improve this question and its markup.
Thanks!
Your question is great. Not too much code, link to JS Fiddle is really helpful. I believe you will receive answer in no time!
Yes, you used two containers, I updated your fiddle with two rows instead and a div with class col-md-12 to take up the whole width of the screen in the first row, check it here : http://jsfiddle.net/3ELJH/3/
| common-pile/stackexchange_filtered |
EntityObject 5.x and Self Tracking Entities 5.x
Does anyone know the if/when/where behind the self-tracking entities template for the latest version of EF? Our team would like to move forward to be able to take advantage of the performance improvements that the EF team has documented, but we haven't been able to find any reference to the new T4 templates for self-tracking entities, which we are dependent upon.
We've tried firing up the old template, but the framework has changed too much.
There's a thread on MSDN about it, but it has not been updated in a while. (http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/4993d0bf-94e8-4d14-aff1-3458b4ad467f/#889cc5f1-e267-448a-ae82-e3d705b7dfa5)
Thanks.
I would not be surprised if neither of those templates would be produced. EntityObject is mostly deprecated and self-tracking entities were replaced by WCF Data Services.
Now I see you are asking for 5.x templates - those even cannot exist because EF 5.x is only DbContext. It doesn't support EntityObject entities and STEs for DbContext never existed (at least officially).
STE exists. Got word from MS today that they are finishing up the licensing aspects of it and will release the template later this week.
You can download it from here, they are available now.
| common-pile/stackexchange_filtered |
How to update JSON data type column in MySQL 5.7.10?
I have started using MySQL 5.7.10 recently and I am liking the native JSON Data type a lot.
But I ran into a problem when it comes to updating a JSON type value.
Questions:
Below is the table format, here I want to add 1 more key in JSON data column for t1 table. Right now I have to fetch the value modify it and Update the table. So it involves an extra SELECT statement.
I can insert like this
INSERT INTO t1 values ('{"key2":"value2"}', 1);
mysql> select * from t1;
+--------------------+------+
| data | id |
+--------------------+------+
| {"key1": "value1"} | 1 |
| {"key2": "value2"} | 2 |
| {"key2": "value2"} | 1 |
+--------------------+------+
3 rows in set (0.00 sec)
mysql>Show create table t1;
+-------+-------------------------------------------------------------
-------------------------------------------------------+
| Table | Create Table |
+-------+--------------------------------------------------------------------------------------------------------------------+
| t1 | CREATE TABLE `t1` (
`data` json DEFAULT NULL,
`id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Is there a work around for this?
Why did you add data like this? it should be separate column for key and value.
@PathikVejani Like I mentioned I am trying to utilize mysql 5.7 which provides native json data type. My JSON can be huge. I can not add columns for every key value pair.
Check: 12.16 JSON Functions.
@wchiquito Thanks for pointing me in right direction. I have posted my solution, though all credit should go to you.
Yes actually there is a workaround, it is called MongoDB
If you just want to change a key, see MySQL Update or Rename a Key in JSON
Thanks @wchiquito for pointing me right direction. I solved the problem. Here is how I did it.
mysql> select * from t1;
+----------------------------------------+------+
| data | id |
+----------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "VALUE2"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+----------------------------------------+------+
4 rows in set (0.00 sec)
mysql> update t1 set data = JSON_SET(data, "$.key2", "I am ID2") where id = 2;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from t1;
+----------------------------------------+------+
| data | id |
+----------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "I am ID2"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+----------------------------------------+------+
4 rows in set (0.00 sec)
mysql> update t1 set data = JSON_SET(data, "$.key3", "I am ID3") where id = 2;
Query OK, 1 row affected (0.07 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from t1;
+------------------------------------------+------+
| data | id |
+------------------------------------------+------+
| {"key1": "value1", "key2": "VALUE2"} | 1 |
| {"key2": "I am ID2", "key3": "I am ID3"} | 2 |
| {"key2": "VALUE2"} | 1 |
| {"a": "x", "b": "y", "key2": "VALUE2"} | 1 |
+------------------------------------------+------+
4 rows in set (0.00 sec)
EDIT:
If you want to add an array, use JSON_ARRAY like
update t1 set data = JSON_SET(data, "$.key4", JSON_ARRAY('Hello','World!')) where id = 2;
This update working fine for single "key: value" . Then how to update multiple key value?.......
@siva like this - JSON_SET(@j, '$.key1', 10, '$.key2', '[true, false]')
how if I want the key from "$.(:passedData)" ? I want to update the key based on the value I get from client, it seems that I cannot pass any value thru :passedData
probably better to use
set data = IFNULL(JSON_SET(data, "$.key2", "I am ID2"), data)
what happened if I don't have any key in my column? for e.g: I have this : ["31","32"]
Ah, this worked a treat. It also works with 2D-3D JSON, just supply a daisy-chained key ex $.key1.key2.key3.
Now with MySQL 5.7.22+ it is very easy and straightforward to update the whole fragment of json (multiple key values, or even nested) in a single query like this:
update t1 set data =
JSON_MERGE_PATCH(`data`, '{"key2": "I am ID2", "key3": "I am ID3"}') where id = 2;
Hope it helps someone visiting this page and looking for a "better" JSON_SET :)
More about JSON_MERGE_PATCH here:
https://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html#function_json-merge-patch
Also it's worth mentioning that this update does not work if the current data is null (and as far as I remember prior to MySQL 8.0.13 you could not set default values to JSON columns). So you might want to do something like update t1 set data = JSON_MERGE_PATCH(COALESCE(\data`, "{}"), '{"key2": "I am ID2", "key3": "I am ID3"}') where id = 2;`
| common-pile/stackexchange_filtered |
How do I profile a real world application?
I run Debian 10 and since two weeks or so the PDF reader Atril (a fork of Evince) takes 25 seconds to start. Previously it started almost instantly. Now I'm trying to find out what causes the delay. I have downloaded the source package and built and installed it with profiling enabled:
cd "$HOME/.local/src"
apt source atril
cd atril-1.20.3
./autogen.sh
./configure CFLAGS=-pg LDFLAGS=-pg --prefix="$HOME/.local" --disable-caja
make V=1
make install
However, when I launch "$HOME/.local/bin/atril" no file named gmon.out is created. With verbose mode V=1 in the make command I can see that the option -pg is added to compilation and linking commands. Any clues? What's missing? There are several tutorials on the internet showing how to profile simple statically linked example programs but how do we profile "real world" applications?
Edit: It turned out that gmon.out was created in my home directory. However, when I run Atril through gprof the resulting output doesn't say much because the application is multi-threaded.
I personally wouldn't dig that deep. I'd recommend not building your own atril, but using the debian atril (because that's what you'll use afterwards, and also, debian gives you debugsymbols).
By order of complexity:
run top (better even: htop, and in its settings disactivate "Hide userland process threads") while starting atril. Is the process using a lot of CPU? Go to perf or gdb.
gdb is often good enough for such things:
install the debug symbols for atril, see the debian wiki
start gdb, loading atril: gdb atril (hint: gdb may tell you you're missing a few debug symbols – you can install these, too, so you can decipher backtraces more easily when they're not currently in atril)
at the (gdb) shell, say run
In the 15s of boredom, press ctrl+c. This interrupts the execution in gdb
since atril is probably multi-threaded, info threads will show you were each thread is stuck
Select the most interesting thread by its number N, by typing thread N
get a backtrace: bt. You'll see where you're coming from.
if it's not using CPU itself, it's almost certainly waiting for a system call to finish. strace atril will tell display the calls it does, live. what are the last few calls you get? maybe it tries to sleep?
if you're CPU-bound, and generally, the perf command from the linux-base package is great: sudo sysctl -w kernel.perf_event_paranoid=-1, and then perf record -ag atril will sample regularly where the execution is stuck (but it looks at all processes, so close your browser, folding at home and whatnot), and then, perf report -g from the same directory shows you browsable statistics. These get more useful if you have debugging symbols installed.
Thank you for the ambitious answer. In GDB I saw all threads being stuck at ../sysdeps/unix/sysv/linux/poll.c:29 and a bit further down the stack there was a call to g_dbus_proxy_new_sync. Then by searching the internet I found this bug report: https://bugs.launchpad.net/ubuntu/+source/dbus/+bug/1852016 with the title "Applications delayed on launch" and this is exactly my problem. With dbus-launch --exit-with-session /usr/bin/atril, Atril starts as quickly as before.
| common-pile/stackexchange_filtered |
D3D9 Hook - Overlay with Direct3D9
OK, so I'm trying to do some overlay for some extra buttons on a Direct X game.
I found a c++ sample that overlays quite nicely here: http://www.gamedev.net/topic/359794-c-direct3d-hooking-sample/
So I began to convert it to Delphi. With some logging I can see that it starts the hook on the correct process and hooks Direct3DCreate9() correctly.
Next TMyDirect3D9 is created successfully. But the process crashes from here.
My educated guess (based on some debugging in Ollydbg) that when I return MyDirect3D9 back to the original process via the hooked Direct3DCreate9() and it tries to call one of the class(interface) functions it fails.
Code follows. If I can give any other information to help let me know.
Main DLL:
library LeagueUtilityBox;
{$R *.res}
{$DEFINE DEBUG}
uses
Windows,
APIHijack in 'APIHijack.pas',
Direct3D9 in '..\DirectX 9.0\Direct3D9.pas',
uSharedMem in '..\Misc\uSharedMem.pas',
MyDirect3D9 in 'MyDirect3D9.pas',
MyDirect3DDevice9 in 'MyDirect3DDevice9.pas',
{$IFDEF DEBUG}
SysUtils,
uLog in '..\Misc\uLog.pas',
{$ENDIF}
uMisc in 'uMisc.pas';
var
SharedMem : TSharedMem;
D3DHook: SDLLHook;
hHook : DWORD;
MyDirect3D9 : TMyDirect3D9;
function GetTargetProcess: String;
const
KeyBase : DWORD = HKEY_CURRENT_USER;
KeyLocation : String = 'Software\LeagueUtilityBox';
var
RegKey : HKEY;
TargetProcess : Array[0..511] Of Char;
Count : DWORD;
begin
Result := '';
If RegOpenKeyEx(KeyBase, PChar(KeyLocation), 0, KEY_QUERY_VALUE, RegKey) = ERROR_SUCCESS Then
begin
Count := 512;
If RegQueryValueEx(RegKey, nil, nil, nil, @TargetProcess[0], @Count) = ERROR_SUCCESS Then
begin
Result := String(TargetProcess);
end;
end;
end;
type
TDirect3DCreate9 = function(SDKVersion: LongWord): Pointer; stdcall;
function MyDirect3DCreate9(SDKVersion: LongWord): Pointer; stdcall;
var
OldFunc : TDirect3DCreate9;
D3D : PIDirect3D9;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'MyDirect3DCreate9 called');
{$ENDIF}
Result := nil;
OldFunc := TDirect3DCreate9(D3DHook.Functions[0].OrigFn);
D3D := OldFunc(SDKVersion);
If D3D <> nil Then
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'D3D created: 0x' + IntToHex(DWORD(Pointer(D3D)), 8));
{$ENDIF}
New(MyDirect3D9);
MyDirect3D9 := TMyDirect3D9.Create(D3D);
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'MyDirect3D9 Created');
{$ENDIF}
Result := @MyDirect3D9;
end;
end;
procedure InitializeHook;
var
Process : String;
I : Integer;
begin
SetLength(Process, 512);
GetModuleFileName(GetModuleHandle(nil), PChar(Process), 512);
For I := Length(Process) DownTo 1 Do
begin
If Process[I] = '\' Then Break;
end;
Process := Copy(Process, I + 1, Length(Process));
If CompareString(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, PChar(GetTargetProcess), -1, PChar(Process), -1) = 2 Then
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'Found target: ' + GetTargetProcess);
{$ENDIF}
With D3DHook Do
begin
Name := 'D3D9.DLL';
UseDefault := False;
DefaultFn := nil;
SetLength(Functions, 1);
Functions[0].Name := 'Direct3DCreate9';
Functions[0].HookFn := @MyDirect3DCreate9;
Functions[0].OrigFn := nil;
end;
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'About to hook: ' + String(AnsiString(D3DHook.Name)));
{$ENDIF}
HookAPICalls(@D3DHook);
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'Hook completed: ' + String(AnsiString(D3DHook.Name)));
{$ENDIF}
end;
end;
procedure InitializeDLL;
begin
SharedMem := TSharedMem.Create('LeagueUtilityBox', 1024);
Try
hHook := PDWORD(SharedMem.Buffer)^;
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'Initializing DLL: ' + IntToStr(hHook));
{$ENDIF}
Finally
SharedMem.Free;
end;
end;
procedure UninitializeDLL;
begin
UnhookWindowsHookEx(hHook);
end;
function WindowsHookCallback(nCode: Integer; WPARAM: Integer; LPARAM: Integer): LRESULT; stdcall;
begin
Result := CallNextHookEx(hHook, nCode, WPARAM, LPARAM);
end;
procedure EntryPoint(Reason: DWORD);
begin
Case Reason Of
DLL_PROCESS_ATTACH:
begin
InitializeDLL;
InitializeHook;
end;
DLL_PROCESS_DETACH:
begin
UninitializeDLL;
end;
end;
end;
exports
WindowsHookCallback;
begin
DLLProc := @EntryPoint;
EntryPoint(DLL_PROCESS_ATTACH);
end.
The custom IDirect3D9:
unit MyDirect3D9;
interface
uses Direct3D9, Windows, uMisc, uLog;
type
PMyDirect3D9 = ^TMyDirect3D9;
TMyDirect3D9 = class(TInterfacedObject, IDirect3D9)
private
fD3D: PIDirect3D9;
public
constructor Create(D3D: PIDirect3D9);
function QueryInterface(riid: REFIID; ppvObj: PPointer): HRESULT; stdcall;
function _AddRef: DWORD; stdcall;
function _Release: DWORD; stdcall;
function RegisterSoftwareDevice(pInitializeFunction: Pointer): HResult; stdcall;
function GetAdapterCount: LongWord; stdcall;
function GetAdapterIdentifier(Adapter: LongWord; Flags: DWord; out pIdentifier: TD3DAdapterIdentifier9): HResult; stdcall;
function GetAdapterModeCount(Adapter: LongWord; Format: TD3DFormat): LongWord; stdcall;
function EnumAdapterModes(Adapter: LongWord; Format: TD3DFormat; Mode: LongWord; out pMode: TD3DDisplayMode): HResult; stdcall;
function GetAdapterDisplayMode(Adapter: LongWord; out pMode: TD3DDisplayMode): HResult; stdcall;
function CheckDeviceType(Adapter: LongWord; CheckType: TD3DDevType; AdapterFormat, BackBufferFormat: TD3DFormat; Windowed: BOOL): HResult; stdcall;
function CheckDeviceFormat(Adapter: LongWord; DeviceType: TD3DDevType; AdapterFormat: TD3DFormat; Usage: DWord; RType: TD3DResourceType; CheckFormat: TD3DFormat): HResult; stdcall;
function CheckDeviceMultiSampleType(Adapter: LongWord; DeviceType: TD3DDevType; SurfaceFormat: TD3DFormat; Windowed: BOOL; MultiSampleType: TD3DMultiSampleType; pQualityLevels: PDWORD): HResult; stdcall;
function CheckDepthStencilMatch(Adapter: LongWord; DeviceType: TD3DDevType; AdapterFormat, RenderTargetFormat, DepthStencilFormat: TD3DFormat): HResult; stdcall;
function CheckDeviceFormatConversion(Adapter: LongWord; DeviceType: TD3DDevType; SourceFormat, TargetFormat: TD3DFormat): HResult; stdcall;
function GetDeviceCaps(Adapter: LongWord; DeviceType: TD3DDevType; out pCaps: TD3DCaps9): HResult; stdcall;
function GetAdapterMonitor(Adapter: LongWord): HMONITOR; stdcall;
function CreateDevice(Adapter: LongWord; DeviceType: TD3DDevType; hFocusWindow: HWND; BehaviorFlags: DWord; pPresentationParameters: PD3DPresentParameters; out ppReturnedDeviceInterface: IDirect3DDevice9): HResult; stdcall;
end;
implementation
uses MyDirect3DDevice9;
constructor TMyDirect3D9.Create(D3D: PIDirect3D9);
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.Create');
{$ENDIF}
fD3D := D3D;
end;
function TMyDirect3D9.QueryInterface(riid: REFIID; ppvObj: PPointer): HRESULT; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.QueryInterface');
{$ENDIF}
Result := fD3D^.QueryInterface(riid, ppvObj);
end;
function TMyDirect3D9._AddRef: DWORD; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9._AddRef');
{$ENDIF}
Result := fD3D^._AddRef;
end;
function TMyDirect3D9._Release: DWORD; stdcall;
var
count : DWORD;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9._Release');
{$ENDIF}
count := fD3D^._Release;
If count = 0 Then
begin
Self.Free;
end;
Result := count;
end;
function TMyDirect3D9.RegisterSoftwareDevice(pInitializeFunction: Pointer): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.RegisterSoftwareDevice');
{$ENDIF}
Result := fD3D^.RegisterSoftwareDevice(pInitializeFunction);
end;
function TMyDirect3D9.GetAdapterCount: LongWord; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetAdapterCount');
{$ENDIF}
Result := fD3D^.GetAdapterCount;
end;
function TMyDirect3D9.GetAdapterIdentifier(Adapter: LongWord; Flags: DWord; out pIdentifier: TD3DAdapterIdentifier9): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetAdapterIdentifier');
{$ENDIF}
Result := fD3D^.GetAdapterIdentifier(Adapter, Flags, pIdentifier);
end;
function TMyDirect3D9.GetAdapterModeCount(Adapter: LongWord; Format: TD3DFormat): LongWord; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetAdapterModeCount');
{$ENDIF}
Result := fD3D^.GetAdapterModeCount(Adapter, Format);
end;
function TMyDirect3D9.EnumAdapterModes(Adapter: LongWord; Format: TD3DFormat; Mode: LongWord; out pMode: TD3DDisplayMode): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.EnumAdapterModes');
{$ENDIF}
Result := fD3D^.EnumAdapterModes(Adapter, Format, Mode, pMode);
end;
function TMyDirect3D9.GetAdapterDisplayMode(Adapter: LongWord; out pMode: TD3DDisplayMode): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetAdapterDisplayMode');
{$ENDIF}
Result := fD3D^.GetAdapterDisplayMode(Adapter, pMode);
end;
function TMyDirect3D9.CheckDeviceType(Adapter: LongWord; CheckType: TD3DDevType; AdapterFormat, BackBufferFormat: TD3DFormat; Windowed: BOOL): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CheckDeviceType');
{$ENDIF}
Result := fD3D^.CheckDeviceType(Adapter, CheckType, AdapterFormat, BackBufferFormat, Windowed);
end;
function TMyDirect3D9.CheckDeviceFormat(Adapter: LongWord; DeviceType: TD3DDevType; AdapterFormat: TD3DFormat; Usage: DWord; RType: TD3DResourceType; CheckFormat: TD3DFormat): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CheckDeviceFormat');
{$ENDIF}
Result := fD3D^.CheckDeviceFormat(Adapter, DeviceType, AdapterFormat, Usage, RType, CheckFormat);
end;
function TMyDirect3D9.CheckDeviceMultiSampleType(Adapter: LongWord; DeviceType: TD3DDevType; SurfaceFormat: TD3DFormat; Windowed: BOOL; MultiSampleType: TD3DMultiSampleType; pQualityLevels: PDWORD): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CheckDeviceMultiSampleType');
{$ENDIF}
Result := fD3D^.CheckDeviceMultiSampleType(Adapter, DeviceType, SurfaceFormat, Windowed, MultiSampleType, pQualityLevels);
end;
function TMyDirect3D9.CheckDepthStencilMatch(Adapter: LongWord; DeviceType: TD3DDevType; AdapterFormat, RenderTargetFormat, DepthStencilFormat: TD3DFormat): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CheckDepthStencilMatch');
{$ENDIF}
Result := fD3D^.CheckDepthStencilMatch(Adapter, DeviceType, AdapterFormat, RenderTargetFormat, DepthStencilFormat);
end;
function TMyDirect3D9.CheckDeviceFormatConversion(Adapter: LongWord; DeviceType: TD3DDevType; SourceFormat, TargetFormat: TD3DFormat): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CheckDeviceFormatConversion');
{$ENDIF}
Result := fD3D^.CheckDeviceFormatConversion(Adapter, DeviceType, SourceFormat, TargetFormat);
end;
function TMyDirect3D9.GetDeviceCaps(Adapter: LongWord; DeviceType: TD3DDevType; out pCaps: TD3DCaps9): HResult; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetDeviceCaps');
{$ENDIF}
Result := fD3D^.GetDeviceCaps(Adapter, DeviceType, pCaps);
end;
function TMyDirect3D9.GetAdapterMonitor(Adapter: LongWord): HMONITOR; stdcall;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.GetAdapterMonitor');
{$ENDIF}
Result := fD3D^.GetAdapterMonitor(Adapter);
end;
function TMyDirect3D9.CreateDevice(Adapter: LongWord; DeviceType: TD3DDevType; hFocusWindow: HWND; BehaviorFlags: DWord; pPresentationParameters: PD3DPresentParameters; out ppReturnedDeviceInterface: IDirect3DDevice9): HResult; stdcall;
var
hr : HRESULT;
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'TMyDirect3D9.CreateDevice');
{$ENDIF}
hr := fD3D^.CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface);
If Succeeded(hr) Then
begin
{$IFDEF DEBUG}
WriteToLog('C:\LeagueUtilityBox.log', 'fD3D^.CreateDevice Succeeded');
{$ENDIF}
ppReturnedDeviceInterface := TMyDirect3DDevice9.Create(PIDirect3D9(@Self), @ppReturnedDeviceInterface);
end;
Result := hr;
end;
end.
UPDATE:
So, since the Delphi interfaces seem to act differently than a real one (Delphi has an in between for it to successfully talk to other interfaces). So I just converted the interface to an array of pointers.
Now the program successfully calls CreateDevice(). I can see this both in the logs and stepping through in Ollydbg.
Now what happens is that when CreateDevice calls the original IDirect3D9.CreateDevice() it crashes again. When I debug in Ollydbg I notice that it is dereferencing the pointer once too much.
UPDATE 2:
Ok, fixed some pointer issues with PIDirect3D9 vs IDirect3D9 in different places. So the original IDirect3D9.CreateDevice() gets called. But it errors with D3DERR_INVALIDCALL!!
So confusing.
UPDATE 3:
Ok, with some more debugging it seems that when I call the function an extra parameter gets pushed on the stack. Which makes the first param invalid. This is proved further by DirectX Debugging which says iAdapter parameter invalid (first param).
UPDATE 4:
With using IntRefToMethPtr() to get the direct pointer to the original CreateDevice call I was able to get it to call with the stacks the same. Same result. It's looking like I've went the wrong route with trying to hook it in Delphi.
UPDATE 5:
Rewrote the hooking method. Now I'm just hooking essentially EndScene(). Hook now works fine in a test program (Vertices.exe that came with the hook demo found in the first URL in this post). But in the main game it crashes the game. Either way I've learned a lot.
I've done this a few times now, and the details are a bit extensive to put in an answer, but there are a few common gotchas and a few specific ones that you'll need to work on.
First, you need to implement the IDirect3D9 and IDirect3DDevice9 interfaces (at least) exactly as they are done in the libraries, or binary-compatible. The interfaces are based on virtual function calls (not sure the Pascal equivalent), so all methods must be virtual, the methods should be in the same order and take the same arguments (which should also be in the same order), etc.
The part I'd look closely at is how pascal is handling the functions, they need to be binary-compatible with Visual C++-built code (__thiscall, virtual, etc).
Additionally, with a few simple regexes, you can usually generate your custom header and the skeleton of your code file from the existing D3D9 header. Note that while this might sound silly, a full-blown D3D9 wrapper can (for IDirect3DDevice9 alone) come out to 2300 lines; generating the basics from the header cuts out a lot of typing that might cause errors.
To handle buttons, you'll also need to a) draw on top of the existing render and b) catch input.
a) is trivial: you simply wait for device->Present() and do your drawing before calling the real present. The only real gotcha is device states. You'll need to save the existing states, set your states for overlay drawing, then reset the device states. Not resetting them properly causes all sorts of fun issues. The states that need set depend on your app, but typically culling, depth sort/test and such are the ones you want to disable.
b) to do buttons, you'll need to also hook into the window's input somehow. Implementing the same sort of wrapper you have here, but for DInput (if its used) is probably a good idea. You can then perform your input check, rendering and logic in the I...Device9 wrapper's Present method.
There is also a decent bit of code around for wrappers like these; I have full d3d 8-to-9 (runtime translation) and 9, and I know of 2 other d3d9 wrappers that can be reused. That might be worth looking into, to either check your code or use existing code.
If there is more info you're interested in as regards to this, or anything interesting you find, I'd be happy to help/like to know.
The C++ code I'm copying off of works fine in the game. I've copied the headers from a direct x delphi headers pack. Basically the c++ code has it's own class based on IDirect3D9
class MyDirect3D9 : public IDirect3D9
And IDirect3DDevice9 in the same fashion. In it's constructor it saves the original IDirect3D9 made with the original Direct3DCreate9() and forwards everything but the CreateDevice() in which it passes on it's custom IDirect3DDevice9.
My issue is my exact copy in Delphi (to my knowledge) is crashing when it tries to use the IDirect3D9* that I passed back to it.
Also I have found many c++ examples, but not one working Direct3D9 example in Delphi. If you know of one, it would be most welcome.
I don't know of any Delphi examples, but I do know that the crash you're seeing is usually caused by the method(s) being not found or implemented wrong. It appears that delphi has a virtual keyword, which may be useful (all COM methods in C++ are virtual). The inheritance isn't strictly necessary, but does allow for some compile-time error checking (to make sure all methods are implemented correctly).
Could it be the way I am returning my custom IDirect3D9 back to the application?
Pointer to IDirect3D9 vs Pointer to TMyDirect3D9? Is there some nuance I am missing. It seems the virtual keyword is for inheritance in the code pre compile and doesn't effect anything post compile. I'm trying to do some run time debugging in Olly and it's quite..uh fun haha.
It could be the pointer, where exactly is the crash occurring (immediately after returning the pointer, or when a method is called)? I'm not sure if explicit virtual is required, but I do notice you have your methods marked as stdcall (the interface methods, in C++, will be virtual __thiscall). Nothing immediately jumps out as being incorrect in your creation code, though I've not taken it apart fully.
I don't think virtual is needed here. The reason for that is that Delphi has explicit COM interface support, and knows exactly how to prepare a compatible VMT fragment for COM interface usage.
I ended up hooking EndScene() and drawing there. Is there a difference between doing the drawing there and in Present()?
EndScene will be called much more often, so your overlay may be rendered hundreds of times per frame. There is a bit more work involved in handling the states when drawing from Present, but that is only ever called once in a frame.
That's good to know! Most of the hooks/wrappers I've encountered have used EndScene(). For the states, would a State Block be useful? (http://msdn.microsoft.com/en-us/library/bb206121(v=VS.85).aspx)
Using EndScene will work, and (with care) can be useful for other things, but not so much an overlay or any kind of post effects. I've seen that often, but it seems to just be poor design. State blocks can be useful and may be worth a try here, although I prefer to manage it by hand (typically only a few states need set). For safety/simplicity, you should have no problems with a state block.
You might want to check out existing DirextX packages for Delphi, even just to confirm (with their examples) that the constructs used are the same as one that you use.
The site I know best is Clootie's: http://clootie.ru/delphi/index.html But afaik there are multiple attempts
There are both DX9 and DX10 SDKs with examples there.
I have, I actually copy and pasted the headers.
any reupload available?
You can get a fully working D3D9 Proxy DLL if you take the clootie's D3D9 SDK
http://sourceforge.net/projects/delphi-dx9sdk/
and the "advanced" d3d9 base from GD
http://www.gamedeception.net/attachment.php?attachmentid=3035&d=1260299029
I use it on Delphi Architect XE3 and compiles and workes fine.
| common-pile/stackexchange_filtered |
Javascript : Update timeout without re-creating it
I would like to know if there is a better way to update a JS Timeout without having to recreate it.
For exemple I have something like this :
<input type="text" onchange="doSomething">
and in my script I am doing this :
let activeTimeout = null
let doSomething = (event) => {
if( activeTimeout !== null) clearTimeout(activeTimeout)
activeTimeout = setTimeout(() => {
console.log(event.target.value) // → Here i'm doing an XHR request to an API
activeTimeout = null
}, 2000)
}
So as you can see, I have to destroy the timeout and recreate it. I tried to do a console.log(activeTimeout) but it gives me a number, maybe an ID, so I was wondering if there was no way to do something like :
let activeTimeout = null
let doSomething = (event) => {
if( activeTimeout !== null) {
window.timeouts[activeTimeout].time = 2000
} else {
activeTimeout = setTimeout(() => {
console.log(event.target.value) // → Here i'm doing an XHR request to an API
activeTimeout = null
}, 2000)
}
}
Thanks for your recommendations.
Bye
Is there something wrong about your approach when recreating the timer? Or what's the reasoning behind finding an alternate solution?
Why not use a promise for the XHR? Then the timeout isn't needed.
You can do it in node but in browser you're stuck with cancel/recreate. Timeout id is an integer but you don't have direct access to the timers queue.
The simple answer is no. There's no standard way to change the expiration time of an existing timeout.
Thanks for your answers :) I was wondering the fact that there was no solution, but maybe I was wrong and could not find the solution on the internet ... that's why I asked
@evolutionxbox To explain better my code, I am doing the onchange function of an Input, every time the users change the input, I want to do a XHR Request to save the data he did write... But I don't want to have a request every character so I put a timeout to listen when the user pause, and if the pause is more than 2sec (in real life I put it to 1sec) I do the POST request to save it :) So I don't understand How a Promise could resolve my case ? Thx
| common-pile/stackexchange_filtered |
SQLiteDatabase updates only when the application is reopened
I have an android app that successfully inserts data in my database when I click a marker in the map.
I have an activity that updates its info(column) in the database. It doesn't update on my first attempt but when I close, exit the app, run it again and update the info again, it successfully updates so I believe my code is right. What would the problem?
Process:
1st open
place marker
onInfoWindowClick starts new activityForResult
fill up fields
save (button)
return values to update a row
doesn't update
re-open
when an existing marker is clicked, fill up fields, it updates when saved
when a new marker is placed, fill up fields, doesn't update (means need to reopen again)
Call to update:
ContentValues cv = new ContentValues();
cv.put(LocationsDB.FIELD_TITLE, newReminder);
cv.put(LocationsDB.FIELD_MONTH, mm_final);
cv.put(LocationsDB.FIELD_DAY, dd_final);
cv.put(LocationsDB.FIELD_YEAR, yy_final);
getContentResolver().update(LocationsContentProvider.CONTENT_URI, cv, "lat=? AND lng=?", new String[] {location_lat, location_lng});
LocationContentProvider.java:
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs){
int count;
count = mLocationsDB.update(values, selection, selectionArgs);
return count;
}
LocationsDB.java:
public int update(ContentValues contentValues, String where, String[] whereArgs){
int cnt = mDB.update(DATABASE_TABLE, contentValues, where, whereArgs);
return cnt;
}
Please show some code that illustrates the issue and no more than necessary.
Where did you put the update function?
@m170897017 the update call is placed in onActivityResult()
@Code-Apprentice I included the code. But like I said, it updates when the app is reopened and not when there is a new inserted value
Are you certain that the database doesn't update? Or is the problem that the data isn't shown in your views? How are you displaying the data?
What is LocationsDB? Does it extend SQLiteOpenHelper? If so, you don't need to implement your own update() function as the super class already provides it. In fact, the only two methods you should have in LocationsDB are onCreate() and onUpgrade().
@Code-Apprentice Yes I am certain that it is not updating. LocationsDB extends LocationContentProvider.
For all of the code you have given, please show the enclosing class and declarations for any pertinent member variables.
Also please describe how you know that the database isn't updating. Did you connect to the device with abd? Did you open the.db file with sqlite3?
Most likely, your SQLite database has changed, but the ContentResolver does not know it. In your the update() method of your ContentProvider, add this line of code:
this.getContext().getContentResolver().notifyChange(uri, null);
This notifies the ContentResolver that a change has occurred. The resolver will then update an UI components that depend on the data.
| common-pile/stackexchange_filtered |
Calculate $\mathrm{Hom}_{\mathbb{Z}/m\mathbb{Z}}(\mathbb{Z}/p\mathbb{Z}, \mathbb{Z}/m\mathbb{Z})$ and more
I'm working on the following exercise on Weibel's An introduction to homological algebra:
Exercise 3.3.2: When $R={\mathbb{Z}/m\mathbb{Z}}$ and $B={\mathbb{Z}/p\mathbb{Z}}$ with $p \mid m$, show that
$$
0 \rightarrow {\mathbb{Z}/p\mathbb{Z}} \xrightarrow{\iota} {\mathbb{Z}/m\mathbb{Z}} \xrightarrow{p} {\mathbb{Z}/m\mathbb{Z}} \xrightarrow{m/p} {\mathbb{Z}/m\mathbb{Z}} \xrightarrow{p} {\mathbb{Z}/m\mathbb{Z}} \rightarrow \cdots
$$
is an infinite periodic injective resolution of $B$. Then compute the group $\mathrm{Ext}_{{\mathbb{Z}/m\mathbb{Z}}}^{n}(A,{\mathbb{Z}/p\mathbb{Z}})$ in terms of $A^{\ast}:= \mathrm{Hom}_{\mathbb{Z}/m\mathbb{Z}}(A, \mathbb{Z}/m\mathbb{Z})$. In particular, show that when $p^2 \mid m$, then $\mathrm{Ext}_{{\mathbb{Z}/m\mathbb{Z}}}^{n}({\mathbb{Z}/p\mathbb{Z}},{\mathbb{Z}/p\mathbb{Z}})={\mathbb{Z}/p\mathbb{Z}}$ for all $n$.
I have shown that the chain is indeed an injective resolution and worked out the $\mathrm{Ext}$ in the general case. But for the "in particular" part, I got stuck.
Question 1: What is the map $\iota$ explicitly? I naively think that the map ${\mathbb{Z}/m\mathbb{Z}} \rightarrow {\mathbb{Z}/p\mathbb{Z}}$ is more natural, by modulo $p$ further for the residue classes modolo $m$, yet I'm quite confused on how to canonically give $\iota$.
Question 2: How to calculate $\mathrm{Hom}_{\mathbb{Z}/m\mathbb{Z}}(\mathbb{Z}/p\mathbb{Z}, \mathbb{Z}/m\mathbb{Z})$? It seems that this is the key, but I am quite frustrated calculating this. It seems that any $f \in \mathrm{Hom}_{\mathbb{Z}/m\mathbb{Z}}(\mathbb{Z}/p\mathbb{Z})$ is completely determined by $f(1)$. But this is the intuition from "$\mathbb{Z}$-module" and I'm not sure for this case. Moreover, since I'm quite puzzled on Question 1, I find it hard to really capture which residue classes in $\mathbb{Z}/m\mathbb{Z}$ play the role of $f(1)$.
Question 3: Jumping out of this question, let $m, n$ be divisors of $\ell$, I wonder if there are general "formula"s for $\mathrm{Hom}_{\mathbb{Z}/\ell\mathbb{Z}}(\mathbb{Z}/m\mathbb{Z}, \mathbb{Z}/n\mathbb{Z})$? Or even $\mathrm{Ext}_{\mathbb{Z}/\ell\mathbb{Z}}^{k}(\mathbb{Z}/m\mathbb{Z}, \mathbb{Z}/n\mathbb{Z})$ and $\mathrm{Tor}^{\mathbb{Z}/\ell\mathbb{Z}}_{k}(\mathbb{Z}/m\mathbb{Z}, \mathbb{Z}/n\mathbb{Z})$ for general $k$. I have underestimated the difficulty of calculating all these after trying to solve this exercise. Are there any references that have calculated these?
Thank you all for answering and commenting!
It is better only to ask only one question at a time.
@DietrichBurde Thank you for your comment. I shall improve my style of posting questions in the future. In this post, the "Question 1-3" are in fact, at least from my own naiive view, closely related, so actually it seems to be a single question with few "sub-question"s, and in this way, I hope to show my attempts. Thank you for your suggestion and I will bear it in mind! :)
Could someone explain the downvote please, if it is not the problem of "asking only one question at a time"?
I did not downvote the question, if you want to know this. I know that some people just jump to the next question here if they see several questions as sub- and subsub-questions of a question. Therefore my advice.
@DietrichBurde Haha, thank you! I only want to improve my post to let it better fit the site and at the same time useful not only for me, but also for later viewers. Maybe my non-mathematical English is not that well to express my emotion, yet I'm definitely not complaining on either you or the downvoters. Sorry if my words may sound rude or impolite. I definitely not mean that. So sorry if that has made anyone feel not well.
Question 1: this map is $1 \mapsto m/p$
Question 2: Any map of abelian groups (so $\mathbb{Z}$-modules) $\mathbb{Z}/p \to \mathbb{Z}/m$ is a map of $\mathbb{Z}/p$ and $\mathbb{Z}/m$-modules because multiplying by $p$ or $m$ gives $0$. Hence, you only need the maps of abelian groups, which is $p$-torsion. This is clearly isomorphic to $\mathbb{Z}/(m/p)$ (all of the multiples of $m/p$ in the range $0,...,m-1$).
Thank you for your answer! Do you mean that $$\mathrm{Hom}{\mathbb{Z}/\mathbb{mZ}}(\mathbb{Z}/\mathbb{pZ}, \mathbb{Z}/\mathbb{mZ}) = \mathrm{Hom}{\mathbb{Z}/\mathbb{pZ}}(\mathbb{Z}/\mathbb{pZ}, \mathbb{Z}/\mathbb{mZ}) = \mathrm{Hom}_{\mathbb{Z}}(\mathbb{Z}/\mathbb{pZ}, \mathbb{Z}/\mathbb{mZ}) ?$$ Then by the post https://math.stackexchange.com/questions/381891/computing-mathrmhom-mathbb-z-n-mathbb-z-m-as-mathbb-z-module , the final result seems to be $\mathbb{Z}/p\mathbb{Z}$ since the gcd of $m$ and $p$ is $p$? Sorry for being too silly.
| common-pile/stackexchange_filtered |
What will happen if we subtract two raster with different cell size using Raster Calculator?
I want to subtract a topography raster with a depth raster. The problem is the two rasters have different cell size. The topography raster have a square cell size of 5, 5 while the depth raster have a rectangular cell size of 10, 3.
How the Raster Calculator work with that way? Does it give accurate result?
when to rasters have different cell sizes, the raster calculator will internally resample the rasters in order to have pixels of the same size. You can select the type of resampling in the environment settings of your geoprocessing tool, using:
minimum
maximum
same as one layer
custom size
In your case, you don't have a pixel size that is a multiple of the other cell size. Therefore the resampling will be lossy if you use a pixel size from your layers.
If you want full control on how the substraction will be done, I recommend that you first resample each image with one by one pixels (chosing bilinear or cubic interpolation to avoid "stair like" artefacts and snapping the extent of the first raster to the second raster). You can store those rasters in_memory if they are not too big to avoid duplicating your data.
| common-pile/stackexchange_filtered |
Why we shouldn't dynamically allocate memory on stack in C?
We have functions to allocate memory on stack in both in windows and Linux systems but their use is discouraged also they are not a part of the C standard? This means that they provide some non-standard behavior. As I'm not that experienced I cannot understand what could be the problem when allocating memory from stack rather then using heap?
Thanks.
EDIT: My view: As Delan has explained that the amount of stack allocated to a program is decided during compile time so we cannot ask for more stack from the OS if we run out of it.The only way out would be a crash.So it's better to leave the stack for storage of primary things like variables,functions,function calls,arrays,structures etc. and use heap as much as the capacity of the OS/machine.
THERE IS NO C/C++ STANDARD! THERE IS NO C/C++ LANGUAGE! AAAARGH!
try to realize the truth: there is no spoon.
Stack memory has the benefit of frequently being faster to allocate than heap memory.
However, the problem with this, at least in the specific case of alloca(3), is that in many implementations, it just decreases the stack pointer, without giving regard or notification as to whether or not there actually is any stack space left.
The stack memory is fixed at compile- or runtime, and does not dynamically expand when more memory is needed. If you run out of stack space, and call alloca, you have a chance of getting a pointer to non-stack memory. You have no way of knowing if you have caused a stack overflow.
Addendum: this does not mean that we shouldn't use dynamically allocate stack memory; if you are
in a heavily controlled and monitored environment, such as an embedded application, where the stack limits are known or able to be set
keeping track of all memory allocations carefully to avoid a stack overflow
ensuring that you don't recurse enough to cause a stack overflow
then stack allocations are fine, and can even be beneficial to save time (motion of stack pointer is all that happens) and memory (you're using the pre-allocated stack, and not eating into heap).
:Thanks,especially the second para is useful.Please read the EDIT part and tell whether I am right.Also is there a way to know at runtime how much stack mem. was allocated and how much of it is left.Thanks again.
No problem. If you feel that my answer is appropriate for your question, feel free to accept it.
In most situations, your understanding of the safe uses for the stack are right on. Of course, there are situations when allocating on the stack are good, given the right conditions, as outlined in my edited answer.
Thanks.Also in my first comment I asked whether in a normal desktop app. can we know the stack size and how much of it is left at some moment.
For a normal desktop app, there are ways to find the stack size sometimes, but it's inconsistent and you should play it safe by avoiding array allocations on the stack. There definitely isn't a way, in any case, to find out how much is left -- you must keep track of that yourself.
Memory on stack (automatic in broader sense) is fast, safe and foolproof compared to heap.
Fast: Because it's allocated at compile time, so no overhead involved
safe: It's exception safe. The stack gets automatically wound up, when exception is thrown.
full proof: You don't have to worry about virtual destructors kind of scenarios. The destructors are called in proper order.
Still there are sometimes, you have to allocate memory runtime, at that time you can first resort on standard containers like vector, map, list etc. Allocating memory to row pointers should be always a judicious decision.
Uh, I believe that this is not true. You can easily cause a stack overflow without knowing, as there is no mechanism in place to discern whether a stack-allocated pointer is actually still in the stack.
@Delan, I never said stackoverflow cannot happen.
Well, it's not really safe then, is it?
@Delan, please read my answer. I have evaluated the meanings of each term.
I think you're over-generalising its safety with one reason, while ignoring one glaring other reason that makes it unsafe (without proper care; I'm not saying that all stack allocations are bad).
| common-pile/stackexchange_filtered |
How to Change placeholder of textBox of search row in radGridView WinForm?
I'm coding with winForms (c# in visualStudio 2019).
I'm using RadGridView Telerik, and Enable its SearchRow.
In SearchTextBox, there is a default text: "Enter text to search".
I want to change this text. how can I do this?
I don't use Telerik's controls myself but see if this helps.
Indeed, using a custom RadGridLocalizationProvider and specifying the RadGridStringId.SearchRowTextBoxNullText is a suitable approach for changing the text in RadGridView. Additional information on how to use the provider is available in the following help article: https://docs.telerik.com/devtools/winforms/controls/gridview/localization/localization
| common-pile/stackexchange_filtered |
JSF 2.0: Why does f:ajax send all the form fields and not only those marked with execute-attribute?
Seems like I am having a bunch of JSF related questions these days... here it goes again: why does AJAX call declared with f:ajax post all the fields of the form and not only those declared with execute? This question was already asked in the Sun forums, but as they are now closed I cannot reply there. The thread there is a stub with no real answer to this.
What's the point of submitting all the form fields if I need to use only some of them?
FYI: I opened a ticket for this: http://java.net/jira/browse/JAVASERVERFACES-1908
I just checked the JSF ticket that Tuuka had posted way back in Jan 2011. It said that this behavior (submitting all the form fields) is consistent with the JSF spec, and the issue was closed.
The JSF developers have posted a spec change notice that this should be modified in an upcoming spec. This had a date of Jan 31, 2013. https://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1098
"f:ajax doesn't obey the 'execute' attribute but always sends all the
fields in a form. Mojarra does, however, only process the listed
fields as supposed. However, excess fields shouldn't be sent because
it increases request size."
"Status: open Priority: major"
This seems to be a bug in the jsf.js
The getViewState function returns all the parameters (instead of filtering them), which are then sent to the server in the request string.
example:
j_idt15=j_idt15&j_idt15%3Avalue1=4444&j_idt15%3Avalue2=555&j_idt15%3Avalue3=6664&javax.faces.ViewState=-6275268178907195611%3A5276476001199934151&javax.faces.source=j_idt15%3Avalue1&javax.faces.partial.event=blur&javax.faces.partial.execute=j_idt15%3Avalue1%20j_idt15%3Avalue1&javax.faces.partial.render=value1out&javax.faces.partial.ajax=true
Here you can see that the even though javax.faces.partial.execute is correctly specified as:
j_idt15:value1, the request still contains all the values
So the bug resides in javascript level - that's why it works in the Java level (JSF only setting the bean fields marked with execute despite of all fields sent). Note that the bug is not only about filtering the right fields, if two or more different forms are specific by execute, only the fields in the wrapping form are still sent. So it's a bit bigger issue. I am going to raise a ticket for this in the Mojarra tracker once it's available again after ongoing infrastrcture migration.
Hmm, seems like I forgot to accept this ages ago. Picking it now!
I am not 100% sure, but this might be a bug in Mojarra. See a similar question about the special @all keyword.
In short: Mojarra doesn't obey the list of forms entered for execute attribute of f:ajax but always submits only the enclosing form. The same probably applies to a more detailed field level as well - Mojarra does not obey the execute attribute when choosing what fields to submit, but simply sends them all. It does obey the execute attribute when processing the data in the server-side, however.
Can anyone test if the behavior differs from this with Apache Myfaces?
| common-pile/stackexchange_filtered |
C# Multithreading with a Singleton object involved
Somewhere on my main thread i make a new thread which creates an object that is only allowed to be instantiated once through the entire application time.
Further down my main thread i have a function that makes use of this object that is also a global variable by the way.
So i wish to run this function on the same thread that the object was created.
Question is how can i achieve this when it is the Main threads decision when this function should be called?
// global variable
private static IWebDriver driver;
// Main Thread thread creation
Thread thread = new Thread(() =>
{
driver = new ChromeDriver(@"myPath");
});
thread.Start();
// some click event on main thread
myFunctionUsingDriverObject();
So i need some way to tell the function to run on the same thread as driver was created. Usually you would use the methodInvoker but the IWebDriver does not have such a method. So is there another way i can invoke the function into the thread of driver?
If anyone is wondering why i want to do this. Then it is because the UI is run on the Main Thread and then the function will freeze the UI until completion if it is also run on the main thread.
Why not create a new thread? Simplest and uglies way is to create a new thread and put a while (true) to check if the driver is still null, then continue with myFunctionUsingDriverObject()?
@SoroushFalahati I believe OP wants to implement functionality similar to "UI thread" and Dispatcher.Invoke in WPF where some objects must be only accessed on "UI thread". This is quite common requirement as some objects (particularly Windows UI once) may behave incorrectly when used from thread that is different from one that created them.
I think you are looking for https://www.bing.com/search?q=c%23+schedule+task+particular+thread like https://stackoverflow.com/questions/30719366/run-work-on-specific-thread. (May be even duplicate)
@AlexeiLevenkov, I am not sure. He says that he cant create a new ChromeDriver as it blocks the main thread. Then he wants to run myFunctionUsingDriverObject() with the resulting ChromeDriver from the other thread.
@SoroushFalahati yes, exactly what I tried to say - replicate "UI thread" + Invoke functionality with custom thread "My Special Thread" + MySpecialThreadInvoke...
It is not chromeDriver that blocks UI thread. It is the function that blocks the UI thread. However The instantiation of ChromeDriver and the call to the function has to be performed on the same thread or else you will get a SystemInvalidOperationException due to Cross-Thread operation. Remember ChromeDriver can only be instantiated once through the entire application time.
Add a reference to the WindowsBase.dll and write this code:
private static IWebDriver driver;
private static Dispatcher dispatcher = null;
AutoResetEvent waitHandle = new AutoResetEvent(false);
var thread = new Thread(() =>
{
dispatcher = Dispatcher.CurrentDispatcher;
waitHandle.Set();
Dispatcher.Run();
});
thread.Start();
waitHandle.WaitOne();
// Now you can use dispatcher.Invoke anywhere you want
dispatcher.Invoke(() =>
{
driver = new ChromeDriver(@"myPath");
});
// And async for not blocking the UI thread
dispatcher.BeginInvoke(new Action(() =>
{
myFunctionUsingDriverObject();
}));
// or using await
await dispatcher.InvokeAsync(() =>
{
});
// And when you are done, you can shut the thread down
dispatcher.InvokeShutdown();
You could use a singleton class or if you wanted to ensure that this could only run once for all applications, a service class that is based on a Mutex. I will show you the former as this seems more applicable as far as I can make out
public interface IDriverService
{
void StartDriverService();
void StopDriverService();
void PerformDriverAction();
}
Now an implementation
public class ChromeDriverService : IDriverService
{
private static ChromeDriverService instance;
private readonly Thread _thread;
private readonly ConcurrentQueue<Action> _actions = new ConcurrentQueue<Action>();
private volatile bool _running;
private ChromeDriverService()
{
_thread = new Thread();
_thread.Start();
}
public static IDriverService Instance()
{
if (instance == null)
instance = new ChromeDriverService();
return instance;
}
// This will run on the "target" _thread
public void StartDriverService()
{
while (true)
{
Action action;
if (_actions.TryDequeue(out action))
{
try
{
action();
}
catch (Exception ex) { // Handle }
}
else
{
if (!_running && _actions.IsEmpty)
return;
}
}
}
public void StopDriverService()
{
_running = false;
// IMPORTANT: Finish the logic here - we have a chance for race conditions. Dequeuing before the
// last action runs for example. This is primative, but you will have to take care of this.
while (!_actions.IsEmpty)
{
// Do stuff.
}
}
// Called from some other thread.
public void PerformDriverAction(Action action)
{
if (_running)
_actions.Enqueue(action);
}
}
This is a primitive example and I have not attempted to run or compile this (I am on my phone).
Note, I am not doing anything with the actual ChromeDriver. This class can be simply edited to work with such an object.
I hope this helps.
| common-pile/stackexchange_filtered |
What is a word like "negate" but even worse?
I suspect this is going to be a "oh yeah, duh" moment, but I'm looking for a word that is like "negate," but worse. Here's an example sentence:
I could cram for this test all night, but the sleep deprivation I'd experience could negate the effort.
I believe this sentence means, "cramming for the test could be canceled out by the sleep deprivation." But what I really want to say is, "the negatives of sleep deprivation could be worse than the benefits of cramming.
Is there a word with the latter meaning that could be swapped out for negate in the example sentence?
EDIT: I probably wasn't clear because a lot of the answers are giving me stronger words with the same meaning of "negate." But I'm looking for a word with a different, yet related, meaning.
May be tagging it with synonyms because the confusion. But whenever I look up synonyms in a thesaurus, the list includes words with closely related meanings, too.
Negate, nullify, void, etc. can be interpreted as bringing you back to zero. I'm not looking for that, I'm looking for a word that fits the first example and means net negative.
Good question! I'm not sure that there is a singular word or even idiom in English that means precisely as you intend. You could of course re-word the sentence to include something like "I could do X in an attempt to improve Z, but because of B that would simultaneously hinder more than improve Z.", where in your example X:=stay up all night studying, Z:=increase test score, B:=fact that said night directly precedes test, that:=X in this context (day before test).
Simple, but: "undermine" ?
@Karl yeah that's a good one, and I think I thought of that before asking the question, but, afaict, the word doesn't mean net negative. It could mean that, but it doesn't have to mean that.
I think outweigh conveys the right meaning here
To be more significant than; exceed in value or importance
e.g. "The benefits outweigh the risks."
The sentence in the question would be
I could cram for this test all night, but the sleep deprivation I'd experience could outweigh the effort.
A synonym that also works here is "outbalance", but that's much less commonly used.
I think that "outbalance" most closely resembles the denotative meaning seeked, conveying a sense of dichotomy as opposed to multidimensionality (that doesn't really affect the net effect of relevance). +1, btw.
As a native British English speaker, I would find the use of "outbalance" very odd in this sentence.
I do not think it's the effort that would be outweighed by the sleep deprivation. Maybe "... outweigh any benefit" or "... outweigh the added preperation" would be better?
As a native American English speaker, I would also find the use of "outbalance" very odd in this sentence.
As a native American English speaker, I find "outweigh" odd (but acceptable in very informal contexts) here because you are not comparing similar referents. Can efforts to accomplish a goal be outweighed by sleep deprivation? No, but efforts in one direction can be outweighed by efforts in another. "Outweigh" is a comparison word, not related to cause and effect.
@piojo the OP says "the negatives of sleep deprivation could be worse than the benefits of cramming." "Worse" is a comparative term. So they are looking for a comparative term. A side-effect, of any effect, is caused by the effect and the side-effect's impact can be comparatively evaluated against the impact of the effect which caused the side-effect. So comparative vs cause-and-effect are not mutually exclusive.
@grovkin I agree, but (I suspect) in general comparisons will sound awkward when comparing "sleep deprivation" to "effort". To be more correct in this sense, the sentence in this answer would need to be wordier--for example, comparing the "effect of X" to the "effect of Y".
FWIW, I accepted this answer because of "outweigh" not because of "outbalance."
I don't think outweigh carries the expected meaning: the sleep deprivation would make me so tired I could fail the exam in spite of the extra efforts. The effects of sleep deprivation outweigh the benefits of cramming for the exam, but for the given phrase construction, I would go for "the sleep deprivation I'd experience could nullify the effort." or "the sleep deprivation I'd experience could void the effort."
counteract verb act against (something) in order to reduce its force or neutralize it.
void verb nullify, annul
nullify verb to make of no value or consequence
backfire verb rebound adversely on the originator; have the opposite effect to what was intended.
"counteract" could be used, so long as the simultaneous (lesser in magnitude) anti-counteraction of the counteracting thing is conveyed. "void" and "nullify" don't convey the full meaning asked for.
Maybe I'm not understanding the definitions, but to me, none of these work because they are synonymous with 'negate.' Using 'counteract' as an example, googling says the definition is, act against (something) in order to reduce its force or neutralize it. And the definition of neutralize is, render (something) ineffective or harmless by applying an opposite force or effect.
@DanielKaplan counteract just means create an action in the opposite direction. The two trends can add up to a negative, or not, depending on how strong the counteracting trend is. But I'll add a word which means exclusively net-negative.
Nullify means to cancel out - "null" indicates that something has or is associated with the value zero. Nullification does not have a net negative effect, it results in a net neutral effect.
Obliterate
From latin, litera, it means to erase, or strike out, something. It's popular use is more on the violent side, to destroy, to demolish.
I'd use it here, it fits both popular use and historical meaning.
I think this could work but it could also not work; one could argue that erasing something brings it back to it's natural state, i.e., zero.
A very strong word that you might use is "annihilate."
Definition 2: to cause to be of no effect : nullify
Here are other definitions.
Selected synonyms: demolish, eradicate, extinguish, liquidate, vitiate, negate...
Now, this does not exactly have the sense that "the negatives of sleep deprivation could be worse than the benefits of cramming." But it seems to me you could use that phrase itself if that's what you mean. If you want to say that cramming has no benefit due to the loss of sleep, "annihilate" will get the listener's or reader's attention.
Either preclude or perhaps obviate the benefit would work here. Merriam-Webster defines preclude as:
to make impossible by necessary consequence : rule out in advance
and obviate as
to anticipate and prevent (something, such as a situation) or make (an action) unnecessary
Sleep deprivation wouldn’t preclude or obviate the cramming, because that comes first, and either means prevent something else from happening. But you might preclude or obviate any benefit from it.
ETA
Or, even closer to the original sense: if you undo or invalidate the point of an action you took, you vitiate it. (I see wastref mentioned this in passing.)
I find obviating benefit at best odd usage, perhaps even incorrect.. effort isn't made 'unnecessary'. (More may be required! But that's beside the point.) Even if arguably correct, I think it's worth saying it's usually used with a negative - i.e. the impact of the obviation is positive, the bad thing was avoided.
Preclude doesn't have that problem ('preclude success') but it doesn't make sense to say that it 'precludes effort' - the effort already happened. 'The resulting sleep deprivation may preclude success despite the effort' works, for example.
@OJFord "obviate" was actually the word I was struggling to remember, but couldn't, when I wrote my answer. M-W's "Did you know?" section on "obviate" seems to agree with you though.
@OJFord I think they both work, but I agree it’s more common to obviate something undesirable, like “the need for cramming.”
“Obviate” would also be very appropriate if you were staying up as a form of self-sabotage.
I like invert here, but maybe subvert is even better.
: to overturn or overthrow from the foundation : ruin
I can't think of a single word, but the idiom "do more harm than good" might fit your meaning
OED:
vitiate, v.
1. a. transitive. To render incomplete, imperfect, or faulty; to impair or spoil.
1738 W. Warburton Divine Legation Moses I. 166 Time, which naturally and fatally viciates and depraves all things.
1794 J. Hutton Diss. Philos. Light 124 It would only lead us into error, and thus vitiate the science or philosophy in which it were employed.
Maybe consider the word Invalidate. Sleep deprivation could also be considered counter-productive to your aim of getting good grades or just simply counter-intuitive.
Given the sample sentence:
I could cram for this test all night, but the sleep deprivation I'd
experience could negate the effort.
I think either counteract, nullify, or cancel out would fit.
Perhaps even vitiate would work, too, although it may sound too formal for the casual-sounding conversation in the example.
If you're fine with using a few words in place of negate, I might suggest entirely cancel out.
I could cram for this test all night, but the sleep deprivation I'd experience could entirely cancel out the effort.
The sleep deprivation could invert the benefits of cramming.
Rather than negate, which can be interpreted as being synonymous with nullify, perhaps you could choose invert. This captures the essence of flipping a positive to a negative, similar to 11qq00's observation of this being an example of an instance where the "one step forward, two steps back" analogy applies.
I agree with nullify. The word "eliminate" would also work. Negate is a pretty strong word already
Since you are trying to cram extra info into your memory, the term "expunge" may be applicable.
I could cram for this test all night, but the sleep deprivation I'd experience could expunge all I know on the topic.
One of the definitions of expunge is "to eliminate from one's consciousness", which seems to be close to what I interpret the original question is aiming at.
How about "I could cram for this test all night, but the sleep deprivation would make the effort counter-productive."
Bringing in some abstract examples from literature and cinema to help I would suggest some verbs, some of them compound, to substitute for your "negate":
I could cram for this test all night, but the sleep deprivation I'd experience could prevail over the effort. ("Sometimes intuition prevails over the facts" - from the film "Naomi");
I could cram for this test all night, but the sleep deprivation I'd experience could override the effort.("Langdon seemed hesitant, as if his own academic curiosity were threatening to override sound judgment and drag him back into Fache's hands" - from Dan Brown's "The Da Vinci Code");
I could cram for this test all night, but the sleep deprivation I'd experience could mock the effort. ("The massive blister mocked my efforts" - Willie Morris);
I could cram for this test all night, but the sleep deprivation I'd experience could trump the effort. ("Money trumps feelings every time" - from the TV series "Castle");
I could cram for this test all night, but the sleep deprivation I'd experience could stultify the effort.("Marriage might...and would... stultify my mental processes" - from "Lady Chatterley's Lover");
I could cram for this test all night, but the sleep deprivation I'd experience could overrule the effort.("His desire to retreat will overrule all his clarity, his power, and his knowledge" - from Carlos Castañeda's "The Teachings of Don Juan: A Yaqui Way of Knowledge").
| common-pile/stackexchange_filtered |
JQuantlib on Google App Engine
I have been wondering: Has anyone successfully deployed a Google App Engine which uses JQuantlib? JQuantLib is a free, open-source, comprehensive framework for quantitative finance, written in 100% Java.
Does anyone know whether this is possible at all? I understand that libraries need to be whitelisted by google to run on app engine. However I am wondering whether it is possible to build the library from source and send it along with the application - given of course that the dependencies are fulfilled.
Any input is appreciated.
Thanks,
Christoph
You can upload any library you want to App Engine. It needs to use white-listed java APIs.
From the quick squiz I did on JQuantlib, I can't see any reason why it won't work. So, go for it.
Hi Chris, I would also to try this out. Have you been successful with this ?
| common-pile/stackexchange_filtered |
How can I identify 3 objects to read data from a file (Java)
I want to read all the data from 3 object which all stay in the same Arraylist. For example, I have 3 classes which are Vehicle, Taxi, car. Taxi, car classes is inheritance from supclass Vehicle. Arraylist called vehiclelist contain taxi, car, vehicle. When I write object into a file, they got different properties. Here my Vehicle file
AAA232,23,TM,GG,222,123
ABC234,23,TA,ga,23,123,ATC
LMC232,23,TC,ga,23,123
The things is when I read these from Vehicle.txt back to an Arraylist. How can computer understand which one is belongs to Car or Taxi and if the Car have got 7 properties but the Taxi only have 6 properties, how can I solve it. Here my code, to read the file:
static void readVehicleFile() {
try {
File f = new File("Vehicle.txt");
Scanner SCF = new Scanner(f);
while (SCF.hasNext()) {
String record = SCF.nextLine();
Scanner SCR = new Scanner(record);
SCR.useDelimiter(",");
String plateNum,model,make;
int capacity,year,ownerID;
plateNum = SCR.next();
capacity = SCR.nextInt();
make = SCR.next();
model = SCR.next();
year=SCR.nextInt();
ownerID=SCR.nextInt();
Vehicle vehicle = new Vehicle(plateNum,capacity,year,model,make,ownerID);
vehicleList.add(vehicle);
}
SCF.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null,"There is a error when saving file","Motor Vehicle Registration System",JOptionPane.ERROR_MESSAGE);
}
}
As you can see, they all read by the vehicle not a car or taxi because if I use car object then vehicle cant not run because the vehicle only have 6 properties. Is there any solutions for it.
I would read the whole line, then test to see how many delimiters there are, based upon this count, instantiate the necessary Object.
Did you try to count the number of values in a row to determine whether it's a car?
Hello! First think about how you would decide as a human reading the file decide which line is of what type. Then you should implement that logic in your code.
How do you distinguish Taxi and Vehicle? Do these types have 6 columns per row in the file?
Fix the file format so it shows the datatype.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.