qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
15,821,461
I am currently learning javascript. I have created a calculator to find invesment future value. It is giving me an incorrect value when it displays the `future value`. I have checked the formula several times but it still gives me an error. Also, I have set alerts to appear if the interest is less than `0` or greater than `20` but nothing is showing. How would i be able to properly display the correct future value and alerts when necessary? [Example](http://webprolearner2346.zxq.net/calculator/future_value.html) **Javascript** ``` var $ = function (id) { return document.getElementById(id); } var calculate_click = function () { var investment = parseFloat( $("investment").value ); var annualRate = parseFloat( $("rate").value ) /100; var years = parseInt( $("years").value ); $("futureValue").value = ""; if (isNaN(investment) || investment <= 0) { alert("Investment must be a valid number\nand greater than zero."); } else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) { alert("Annual rate must be a valid number\nand less than or equal to 20."); } else if(isNaN(years) || years <= 0 || years > 50) { alert("Years must be a valid number\nand less than or equal to 50."); } else { //var monthlyRate = annualRate / 12; //var months = years * 12; var futureValue = 0; for ( i = 1; i <= years; i++ ) { futureValue = ( futureValue + investment ) * ( 1 + annualRate ); } $("futureValue").value = futureValue.toFixed(2); } } var clear_click = function () { $("investment").value = ""; $("rate").value = ""; $("years").value = ""; $("futureValue").value = ""; } window.onload = function () { $("calculate").onclick = calculate_click; $("investment").focus(); $("clear").onclick = clear_click; } ```
2013/04/04
[ "https://Stackoverflow.com/questions/15821461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513531/" ]
Using `.value` is incorrect, its javascript, while this is jquery, try adding a `#` in front and use `.val()` instead. Its similar to this: [jquery function val() is not equivalent to "$(this).value="?](https://stackoverflow.com/questions/4524702/jquery-function-val-is-not-equivalent-to-this-value) EDIT He's not using jquery, ignore this.
If I remember the future value correctly, you are messing up the formula, which is why you aren't getting the expected value. Change: ``` for ( i = 1; i <= years; i++ ) { futureValue = ( futureValue + investment ) * ( 1 + annualRate ); } ``` To: ``` futureValue = investment*Math.pow((1+annualRate), years); ``` Not quite sure why you are looping through each year, but it should be based on powers to the number of years (again, if I remember correctly)
70,601,691
I am trying to build a simple bot that can kick, ban, and say "Hi" to a member. Kick and ban work perfectly fine and do their job, but when I add an "on\_message" function, the on\_message function works but cancels out kick and ban. Any ideas? My code: ``` import discord from discord.ext import commands bot = commands.Bot(command_prefix="!") @bot.command() async def kick(ctx, member: discord.Member, *, reason=None): await member.kick(reason=reason) @bot.command() async def ban(ctx, member: discord.Member, *, reason=None): await member.ban(reason=reason) @bot.event async def on_message(message): if "!hello" == message.content: await message.channel.send(f"Hi") await bot.process_commands(message) bot.run("my token") ```
2022/01/06
[ "https://Stackoverflow.com/questions/70601691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16979809/" ]
When you define a variable as a union, it means that that variable can be any of the items within the union. Therefore, TypeScript will assert that an operation is valid for all types within the union before you are able to do it. Therefore, if you did want your code to work when you know the type of the config at compile-time (like a constant object) and also when you dynamically create it (e.g. from some CLI input params) then you can create a helper function that simply wraps the config: ``` type TestConfig = { file: string; name: string; } type CakeConfig = { run: string; } function createConfig<T extends TestConfig | CakeConfig>(config: T): T extends TestConfig ? TestConfig : CakeConfig { return config as any; // cast is required for generic return } createConfig({ run: "hey" }); // CakeConfig createConfig({ file: "", name: "" }); // TestConfig createConfig({ run: "dynamic" } as any); // CakeConfig | TestConfig // an example of the safe inference const config = createConfig({ // CakeConfig run: 'run!' }); declare function doSomething(config: TestConfig | CakeConfig): void; doSomething(config); // works! declare function doSomethingWithCake(config: CakeConfig): void; doSomethingWithCake(config); // works! ```
You are using your `typeCheck` like this: ```js console.log(typeCheck.test.run) ``` This statement presupposes that `typeCheck.test` has a `run` property. At the same time `TestConfig` hasn't one. So it's a contradiction, because any variable of `MixConfig` type could have a `test` of `TestConfig`. Thus to have this working, you have to add the `run` property to your `TestConfig`.
21,623,614
I need to find the first set bit in a binary number from right to left; I came up with this solution: ``` int cnt=0; while (number& 1 ==0) { cnt++; number>>=1; } ``` Is there a better way of doing it? Some clever bit manipulation technique?
2014/02/07
[ "https://Stackoverflow.com/questions/21623614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want it to be fast, bitscan instruction (`bsf`, `bsr`) or [bit-twiddling hack](http://graphics.stanford.edu/~seander/bithacks.html) is the target to go. **EDIT: The idea of using switch-case table to improve performance is nothing but immature.**
Your code ``` int cnt=0; while (number& 1 ==0) { cnt++; number>>=1; } ``` has a bug. For example if number is equal to 0 then the loop will be infinite. I would rewrite it the following way ``` int cnt = 0; if ( number ) while ( !( number & ( 1 << cnt++ ) ) ); ``` In this case if number is not equal to 0 then the position (cnt) of the set bit will be count starting from 1. Otherwise the position will be equal to 0.
37,489,647
I have a DIV with an H2 inside. The DIV is completely separate from all the other work, placed at the bottom of the HTML, yet for some reason it is sticking to the top of the page, inside one of the other DIVs. I've tried Googling but to no avail, I need it below the background to start working on a new section. What should I be looking at? <https://jsfiddle.net/5vLvm3xx/> ps. I dont know how many people browse these forums, but I've been asking alot of questions here today because I keep running into these small issues that stop me from continuing (im a beginner). I hope it is no bother. :) HTML ``` <!doctype html> <html> <head> <meta charset="utf-8"> <title>onepageskiw</title> <link href="styles.css" rel="stylesheet" type="text/css"> <script src="js.js"></script> </head> <body> <div> <nav> <ul id="menu"> <li><a href="#">Top</a></li> <li><a href="#">Om Eventet</a></li> <li><a href="#">Lokation</a></li> <li><a href="#">Kontakt</a></li> </ul> </nav> </div> <div id="logodiv"> <img src="../design/logotop.png"> </div> <div id="overskrift"> <h1>EVENTET STARTER OM</h1> </div> <div id="countdowner"> <table id="table"> <tr> <div id="countdown"> <td id="id1"></td> <td id="id2"></td> <td id="id3"></td> <td id="id4"></td> </div> <tr> <tr> <td class="timeLabel">DAGE</td> <td class="timeLabel">TIMER</td> <td class="timeLabel">MIN</td> <td class="timeLabel">SEK</td> </tr> </tr> </tr> </table> </div> <script> CountDownTimer('06/25/2016 10:00 AM', 'id'); function CountDownTimer(dt, id) { var end = new Date(dt); var _second = 1000; var _minute = _second * 60; var _hour = _minute * 60; var _day = _hour * 24; var timer; function showRemaining() { var now = new Date(); var distance = end - now; if (distance < 0) { clearInterval(timer); document.getElementById(id).innerHTML = 'EXPIRED!'; return; } var days = Math.floor(distance / _day); var hours = Math.floor((distance % _day) / _hour); var minutes = Math.floor((distance % _hour) / _minute); var seconds = Math.floor((distance % _minute) / _second); document.getElementById(id+"1").innerHTML = days; document.getElementById(id+"2").innerHTML = hours; document.getElementById(id+"3").innerHTML = minutes; document.getElementById(id+"4").innerHTML = seconds; } timer = setInterval(showRemaining, 1000); } </script> <div id="information"> <h2>Help me. I'm stuck.</h2> </div> </body> </html> ``` CSS ``` @charset "utf-8"; @import url(https://fonts.googleapis.com/css? family=Montserrat:400|Raleway:100,400|); body { margin:0; } html { background:url(http://www.freelargeimages.com/wp- content/uploads/2014/12/Black_background.jpg) no-repeat center center fixed; background-size: cover; background-repeat: no-repeat; /*background-position: top center;*/ } #logodiv { position:relative; text-align:center; } #logodiv>img { width:15%; } h1 { font-family:raleway; font-weight:100; position:absolute; width:100%; text-align:center; color:white; letter-spacing:11px; position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-230%); font-size:2.5em; white-space: nowrap; } #countdowner { font-family:sans-serif; color:white; position:absolute; margin:0; padding:0; width:100%; font-size:2em; top: 50%; left: 50%; transform: translateX(-50%) translateY(-20%); } #id1 { font-size:2.5em; } #id2 { font-size:2.5em; } #id3 { font-size:2.5em; } #id4 { font-size:2.5em; } .timeLabel { font-size:0.7em; color:#f1a01e; font-family:montserrat; font-weight:700; } #table { margin:0 auto; text-align:center; } #table td{ padding:0px 45px; } #menu { position:absolute; padding:0; width:100%; bottom:0; text-align:center; } #menu>li { font-size:20px; list-style:none; display:inline-block; text-transform:uppercase; letter-spacing:3px; font-family:raleway; font-weight:400; } #menu>li>a { padding:0 15px; text-decoration:none; color:white; } #menu>li>a:hover { color:#f1a01e; } #information { position:relative; clear:both; color:red; } ```
2016/05/27
[ "https://Stackoverflow.com/questions/37489647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6012587/" ]
I use both IBM MQ and ActiveMQ on a regular basis. This example below will show you some sample configuration options. Please make sure you configure these to your own use cases. ``` //ActiveMQ connection factory <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent" destroy-method="doStop"> <property name="configuration"> <bean class="org.apache.camel.component.jms.JmsConfiguration"> <property name="concurrentConsumers" value="1" /> <property name="maxConcurrentConsumers" value="1" /> <property name="acceptMessagesWhileStopping" value="true" /> <property name="acknowledgementModeName" value="CLIENT_ACKNOWLEDGE" /> <property name="cacheLevelName" value="CACHE_CONSUMER" /> <property name="connectionFactory"> <bean class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop"> <property name="maxConnections" value="1" /> <property name="MaximumActiveSessionPerConnection" value="500" /> <property name="connectionFactory"> <bean class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="${activemq1.brokerUrl}" /> <property name="userName" value="${activemq1.username}" /> <property name="password" value="${activemq1.password}" /> <property name="redeliveryPolicy"> <bean class="org.apache.activemq.RedeliveryPolicy"> <property name="maximumRedeliveries" value="-1" /> </bean> </property> </bean> </property> </bean> </property> </bean> </property> </bean> //IBM MQ connection factory <bean id="ibmmq" class="org.apache.camel.component.jms.JmsComponent" destroy-method="doStop"> <property name="concurrentConsumers" value="1" /> <property name="maxConcurrentConsumers" value="1" /> <property name="connectionFactory"> <bean class="org.springframework.jms.connection.SingleConnectionFactory" destroy-method="destroy"> <constructor-arg> <bean class="com.ibm.mq.jms.MQQueueConnectionFactory"> <property name="transportType" value="1" /> <property name="channel" value="${channel}" /> <property name="hostName" value="${hostname}" /> <property name="port" value="${port}" /> <property name="queueManager" value="${queueManager}" /> </bean> </constructor-arg> </bean> </property> </bean> ```
You can use users camel extra component <https://github.com/camel-extra/camel-extra/blob/master/components/camel-wmq/README.md> to get messages from wmq without using the JMS wrapping and then send messages to ActiveMQ with custom camel component <https://camel.apache.org/components/latest/activemq-component.html>. See also a similar topic [Apache Camel with IBM MQ](https://stackoverflow.com/questions/35085762/apache-camel-with-ibm-mq).
555,010
Until this morning, I'd been using sshfs quite nicely to mount a directory from a linux machine in my office. Today, it stopped. Here's my sshfs command: ``` sshfs -osshfs_sync,volname=linux-builder3 linux-builder3:/home/cnorum /Users/carl/linux-builder3 ``` I get this error, but the sshfs process seems to still be running (that is, it just sits there, never returning to the shell prompt): ``` mount_osxfusefs: failed to mount /Users/carl/linux-builder3@/dev/osxfuse1: Socket is not connected ``` The system log on the Mac has these messages: ``` 2/20/13 12:57:27.476 PM KernelEventAgent[43]: tid 00000000 received event(s) VQ_DEAD (32) 2/20/13 12:57:27.000 PM kernel[0]: OSXFUSE: force ejecting (no response from user space 5) 2/20/13 12:57:27.000 PM kernel[0]: OSXFUSE: user-space initialization failed (57) ``` And here's `/var/log/auth.log` on the linux machine: ``` Feb 20 12:56:28 linux-builder3 adclient[1599]: INFO <fd:22 PAMIsUserAllowedAccess> audit User 'cnorum' is authorized Feb 20 12:56:28 linux-builder3 sshd[29648]: Accepted publickey for cnorum from 10.0.40.65 port 49850 ssh2 Feb 20 12:56:28 linux-builder3 sshd[29648]: pam_unix(sshd:session): session opened for user cnorum by (uid=0) Feb 20 12:56:28 linux-builder3 sshd[29729]: subsystem request for sftp ``` sshfs connections to other machines (linux-builder and linux-builder2 in my case) seem to be fine. Does anybody have any suggestions for what went wrong and how I might fix it? I can get any logs you might want to see!
2013/02/20
[ "https://superuser.com/questions/555010", "https://superuser.com", "https://superuser.com/users/12727/" ]
I think it's fixed. I had this line in the `.bashrc` on the linux box: ``` CLIENT_PATH_PREFIX="$(ssh ${CLIENT_ADDR} 'echo ${SSHFS_PATH_PREFIX}')/$(hostname)/$(whoami)" ``` It didn't need to be run by non-interactive shells, so I pushed that off to a different file, and it's better now. I don't really understand *why*, but I'm happy it works.
My problem was that the RSA host key for my host changed, so I had to run ``` ssh-keygen -R site.com ```
50,908,313
This is often suggested, as a way to initialize a struct to zero values: ``` struct foo f = {0}; ``` It is also mentioned that `{}` could be used under gcc, but that this is not standard C99. I wonder if this works for a struct whose layout may vary outside my control. I'm anxious because `0` is not a valid initializer for an array or struct. However `gcc --std=c99` (gcc-8.1.1-1.fc28.x86\_64) seems to accept `{0}` even in such cases. **Question** Does C99 accept `{0}` as an initializer for any struct? (Or a later C standard? Or contrawise, is there any reason not to rely on this? Are there compilers where `{0}` could cause an error or a warning that would discourage its use?) **What I have tried** gcc warnings (enabled with `-Wall`) suggest that this is some form of edge case in the standard, where gcc has been forced to accept `0` as an initializer for any type of struct field, but it will warn about it unless you are using the common `{0}` idiom. ``` struct a { int i; }; struct b { struct a a; struct a a2; }; struct c { int i[1]; int j[1]; }; struct a a = {0}; /* no error */ struct b b = {0}; /* no error */ struct c c = {0}; /* no error */ /* warning (no error): missing braces around initializer [-Wmissing-braces] */ struct b b2 = {0, 0}; /* warning (no error): missing braces around initializer [-Wmissing-braces] */ struct c c2 = {0, 0}; struct a a2 = 0; /* error: invalid initializer */ int i[1] = 0; /* error: invalid initializer */ ```
2018/06/18
[ "https://Stackoverflow.com/questions/50908313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799204/" ]
Yes. Inside an initialization list, "missing braces around initializer" is allowed by the standard. C99: > > If the aggregate or union contains elements or members that are aggregates or unions, > these rules apply recursively to the subaggregates or contained unions. > If the initializer of > a subaggregate or contained union begins with a left brace, the initializers enclosed by > that brace and its matching right brace initialize the elements or members of the > subaggregate or the contained union. > Otherwise, only enough initializers from the list are > taken to account for the elements or members of the subaggregate or the first member of > the contained union; any remaining initializers are left to initialize the next element or > member of the aggregate of which the current subaggregate or contained union is a part. > > >
`= {0}` tells the compiler to perform *aggregate initialisation*, and the first member is set to the value that it would be assumed if the `struct` had static storage duration. In such an aggregate initialisation, if there are fewer initialisers in the list than there are members in the `struct`, then each member not explicitly initialised is default-initialised. So yes, a C compiler will accept `= {0}` as an initialiser for any struct.
11,324,640
I want to check if a web host is available so i used the code down below, it works, but sometimes if the site is slow in response it keep waiting, how do i implant a timeout into it? if no response from the host withen 2-3 second, return false also. Please help me out ``` - (BOOL)isDataSourceAvailable { static BOOL checkNetwork = YES; static BOOL _isDataSourceAvailable = NO; if (checkNetwork) { // Since checking the reachability of a host can be expensive, cache the result and perform the reachability check once. checkNetwork = NO; Boolean success; const char *host_name = "google.com"; //HOST SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name); SCNetworkReachabilityFlags flags; success = SCNetworkReachabilityGetFlags(reachability, &flags); _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); CFRelease(reachability); } return _isDataSourceAvailable; } ```
2012/07/04
[ "https://Stackoverflow.com/questions/11324640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1480092/" ]
You need to find a way to identify a "checkbox set" use the object spy or a dom inspector to see what identifies the set (probably some kind of `div` or `span`) for the sake of this answer I'll assume that it's a `div` with a specific `class` `"chkbxGrp"`. Then look for the first checkbox contained within this group and check it. Note that scrolling the checkboxs into view is done automatically by QTP. If you need to fail this when an expected group doesn't exist you will have to find out how to identify specific groups and then use the expected values in the test rather than iterating over all such groups. ``` ' Untested code Set Desc = Description.Create() Desc("html tag").Value = "div" Desc("html tag").RegularExpression = False Desc("class").Value = "chkbxGrp" ' Find all groups Set groups = Browser("B").Page("P").ChildObjects(Desc) For i = 0 To groups.Count -1 ' in each group check the first checkbox groups(i).WebCheckBox("index:=0").Set "ON" Next ```
You can "identify" the checkbox using QTP index. It's not the best option to do, though if you need only the 1st checkbox. Just look for all Objects on the page of a type "CheckBox", and if the result set > 0, get the first one. The second option is to "locate" the Checkbox by the nearby elements, but in this case you need to be sure that their location is NOT to be changed. BTW, are you sure they are completely identical? In QTP there is an option to set necessary attributes for elements location. You can add any attribute which is unique for the CheckBoxes appearing in your app.
35,463,769
I am trying to extract substring like \*\*\*.ini from string. For example, I have ``` 000012: 378:210 File=test1.ini Cmd:send command1 000512: 3378:990 File=test2.ini Cmd:send command2 File=not.ini Cmd: include command ``` I need to extract the substring after the first "File=", and the substring after the first File=\*\*\*.ini which is "Cmd: ..." till the end. So the result I want is: ``` test1.ini Cmd:send command1 ``` and ``` test2.ini Cmd:send command2 File=not.ini Cmd: include command ``` I tried: ``` re.match("(.*) File=(.*).ini(.*)Cmd:(.*)", line, re.M\re.I) ``` this works well with the first line, but for the second line, I get: ``` test2.ini Cmd:send command2 File=not.ini #which is wrong, wanted is: test.ini Cmd: include command ``` Anyone please help. Thanks. LJ
2016/02/17
[ "https://Stackoverflow.com/questions/35463769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1558064/" ]
run below query ``` select * from sys.databases ``` it shows all the information for a database. there is no unique information for database but name and database\_id BTW, I don't know why you are concern about it!
This query returns the GUID you need, for the current Database. ``` SELECT database_guid FROM sys.database_recovery_status WHERE database_id = DB_ID() ``` Of course the user can always rename his database after this GUID.
16,124,821
I wonder how to convert a string to an HTMLElement ? I have tryed : ``` $('<i data-icon="'+icon+'" class="smiley-big"></i>') ``` But in console it shows type: [object Object] If I log existing ellements in the Dom like this: ``` $('[class^="smiley"]').each(function(){ console.log(this); }); ``` I get [object HTMLElement] Thanks for your help
2013/04/20
[ "https://Stackoverflow.com/questions/16124821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2071284/" ]
My Idea would be something like: **Short version:** 1. change task interval to 1 minute; 2. add `unsetAllTokensIfNeeded` method to `SessionTokenService` that will be invoked every minute but will just clean the tokens list if it is really needed (in this case the decision is done based on the time). **Detailed Version:** Your scheduled task will run every minute invoking the `unsetAllTokensIfNeeded` method implemented by `SessionToken`. The method implementation will check the last time token list was clean and invoke `unsetAllTokens` if it was an hour ago. But in order to invoke it in every single session scoped `SessionTokenService` you will need the list of existing `SessionTokenService`s, that could be achieved by registering it at creation time to the service that will clean it (here you shall use a `WeakHashMap` to avoid hard references, this would avoid the objects to be collected by garbage collector). The implementation would be something like this: **Session Tokens:** Interface: ``` public interface SessionTokenService extends Serializable { public boolean isTokenValid(String token); public String getLatestToken(); public boolean unsetToken(String token); public void unsetAllTokens(); public boolean unsetAllTokensIfNeeded(); } ``` Implementation: ``` @Service @Scope("session") public final class SessionToken implements SessionTokenService, DisposableBean, InitializingBean { private List<String> tokens; private Date lastCleanup = new Date(); // EDIT {{{ @Autowired private SessionTokenFlusherService flusherService; public void afterPropertiesSet() { flusherService.register(this); } public void destroy() { flusherService.unregister(this); } // }}} private static String nextToken() { long seed = System.currentTimeMillis(); Random r = new Random(); r.setSeed(seed); return Long.toString(seed) + Long.toString(Math.abs(r.nextLong())); } @Override public boolean isTokenValid(String token) { return tokens == null || tokens.isEmpty() ? false : tokens.contains(token); } @Override public String getLatestToken() { if(tokens==null) { tokens=new ArrayList<String>(0); } tokens.add(nextToken()); return tokens.isEmpty() ? "" : tokens.get(tokens.size()-1); } @Override public boolean unsetToken(String token) { return !StringUtils.isNotBlank(token) || tokens==null || tokens.isEmpty() ? false : tokens.remove(token); } @Override public void unsetAllTokens() { if(tokens!=null&&!tokens.isEmpty()) { tokens.clear(); lastCleanup = new Date(); } } @Override public void unsetAllTokensIfNeeded() { if (lastCleanup.getTime() < new Date().getTime() - 3600000) { unsetAllTokens(); } } } ``` Session Token Flusher: Interface: ``` public interface SessionTokenFlusherService { public void register(SessionToken sessionToken); public void unregister(SessionToken sessionToken); } ``` Implementation: ``` @Service public class DefaultSessionTokenFlusherService implements SessionTokenFlusherService { private Map<SessionToken,Object> sessionTokens = new WeakHashMap<SessionToken,Object>(); public void register(SessionToken sessionToken) { sessionToken.put(sessionToken, new Object()); } public void unregister(SessionToken sessionToken) { sessionToken.remove(sessionToken); } @Scheduled(fixedDelay=60000) // each minute public void execute() { for (Entry<SessionToken, Object> e : sessionToken.entrySet()) { e.getKey().unsetAllTokensIfNeeded(); } } } ``` In this case you shall use the annotation driven task feature from Spring: ``` <task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/> <task:scheduler id="taskScheduler" pool-size="10"/> ``` From my point of view this would be a simple and good solution. **EDIT** With this approach you are more or less registering the `SessionToken` to the `Flusher` when spring ends the bean configuration and removing it when spring destroys the bean, this is done when the session is terminated.
It seems the token remover periodic job you setup did not run in the context of a particular user session -- nor all user sessions. I'm not sure if there's any mechanism for you to scan through all active sessions and modify it, however the alternative I'm proposing is: Store a pair of unique token with a timestamp on the server side. Only send the token to the user (never the timestamp) when you present the form. When the form is submitted, lookup when that token is generated -- if it's past the timeout value, reject it. This way you don't even need a timer to delete all the token. Using a timer would also delete newly created token
205,664
How do I remove Windows Mobile Device Center from Windows 7? When I connect any mobile device, I don't want Windows Mobile Device Center to pop up, like ActiveSync 4.5 did.
2010/11/01
[ "https://superuser.com/questions/205664", "https://superuser.com", "https://superuser.com/users/22580/" ]
User [flapjack](http://forum.xda-developers.com/member.php?u=574279)'s solution on [xda-developers forum](http://forum.xda-developers.com/showthread.php?t=394984): > > I was able to fix this. First, I > stopped and disabled both WMDC > services under Computer Management > > Services. Then, I found mobsync.exe in > the Windows/System32 folder, went into > "Permissions" for it, took ownership, > then removed all the accounts except > the "Everyone" permissions. For > Everyone, I set it to "Deny All". > > > I now have no WMDC or sync stuff > popping up. It's great. I can still > browse the phone from My Computer > > TYTN II. I can also still use > MyMobiler to control the phone from > Windows, so this doesn't kill the USB > connection at all. > > > Hope this helps someone. > > >
Another user from the xda.developers forums has created a program that achieves just what you're looking for: <http://forum.xda-developers.com/showpost.php?p=1843786&postcount=2>.
70,537,742
I have a block of text in a .txt file that reads: OVERVIEW OF FINDINGS --datatext1 OVERVIEW OF FINDINGS --datatext2 OVERVIEW OF FINDINGS --datatext3 SUMMARY OF FINDINGS OVERVIEW OF FINDINGS can happen a random number of times, or only once. I am ONLY interested in datatext3 (a variable amount of text). That is, only the text that lies between the last occurrence of "OVERVIEW OF FINDINGS" and "SUMMARY OF FINDINGS". There are a few posts on how to use `re` and how to split strings to get the right text. From them I was able to find a solution that works below. However, it's multiple for loops and an if/elif append loop. It seems extremely convoluted, and I'm wondering if I am overlooking a far simpler solution? ``` #Index all occurrences of OVERVIEW OF FINDINGS and SUMMARY OF FINDINGS: x = [] y = [] for i in re.finditer('OVERVIEW OF FINDINGS', data): x.append(i.start()) for j in re.finditer('SUMMARY OF FINDINGS', data): y.append(j.start()) #Append to overview only when the next overview index is after the next summary index n = 0 overview = [] for m in range(0,len(x)): if x[m] == x[-1]: #condition for last value in x or if only one value in x overview.append(data[x[m]+21:y[n]]) #(Note: OVERVIEW OF FINDINGS = +21) elif x[m+1] > y[n]: overview.append(data[x[m]+21:y[n]]) if y[-1] == y[n]: break else: n += 1 ```
2021/12/30
[ "https://Stackoverflow.com/questions/70537742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17500135/" ]
Regular expressions aren't necessary here; just split the string on the substrings you're looking for. ``` start = 'OVERVIEW OF FINDINGS' end = 'SUMMARY OF FINDINGS' result = text.split(start)[-1].split(end)[0].strip() ```
If you're open to using regular expressions, we can use `re.findall` here: ```py inp = """OVERVIEW OF FINDINGS --datatext1 OVERVIEW OF FINDINGS --datatext2 OVERVIEW OF FINDINGS --datatext3 SUMMARY OF FINDINGS""" text = re.findall(r'\bOVERVIEW OF FINDINGS\b(?!.*\bOVERVIEW OF FINDINGS\b)\s*(\S+)\s+SUMMARY OF FINDINGS', inp, flags=re.S)[0] print(text) # --datatext3 ``` The regex pattern uses a negative lookahead to assert that the `OVERVIEW OF FINDINGS` only matches if it be the *last* one in the entire text. Here is an explanation of the regex pattern: ```regex \bOVERVIEW OF FINDINGS\b match 'OVERVIEW...' (?!.*\bOVERVIEW OF FINDINGS\b) assert that no more 'OVERVIEW...' occurs \s* optional whitespace (\S+) match content \s+ match whitespace SUMMARY OF FINDINGS match 'SUMMARY...' ```
92,288
In the EU, a person will soon be able to perform certain activities (going to concerts, to sports events, etc.) only if they can present a valid Green Pass that certifies that the bearer has been vaccinated, or has recovered from Covid, or has been tested negative in the recent past. The Green Pass is basically a QR code that contains information encrypted with public-key cryptography (see [here](https://gir.st/blog/greenpass.html) for details). As soon as it was introduced, spammers started promoting fake Green Passes for people who did not want to get vaccinated. Some of these are clearly attempts at identity theft, since the spammers claim that they need a copy of a valid ID to generate the Green Pass. I'd like to know whether the Green Pass scheme has actually been broken¹; the few sources that I've found are clearly unreliable (their technical explanations are gibberish). NOTE: I've had my shots and have a valid Pass; I'm only interested in the technical aspect (i.e. robustness) of the scheme. --- ¹ **Moderator note: we are on a cryptographic forum, and *if* we discuss that subject, at least we should stick strictly to it's *cryptographic* aspects.**
2021/07/27
[ "https://crypto.stackexchange.com/questions/92288", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/92940/" ]
The [specification](https://github.com/ehn-dcc-development/hcert-spec/releases/download/1.0.5/dgc_spec-1.0.5-final.pdf#page=6) mentions that the signature is per [ECDSA](https://www.secg.org/sec1-v2.pdf#subsection.4.1) on curve "P-256" (aka [secp256r1](https://www.secg.org/sec2-v2.pdf#subsection.2.4)), or [RSASSA-PSS](https://pkcs1grieu.fr/#page=28) with a modulus of 2048 bits in combination with the [SHA–256](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf#page=3) hash (I guess with [MGF1](https://pkcs1grieu.fr/#page=50) with SHA-256; can't be sure for [salt size](https://crypto.stackexchange.com/a/1222/555)). These are state-of-the-art, unbroken *algorithms*. I find it unbelievable that a *cryptographic* attack would let emit fake passes that are accepted with proper validation per this specs, with forged user data.
Answering the question what is broken, with focus on cryptographic aspects: "Green Pass" title implies **yes/no decision**, while the application actually **scans** the name, birthday, and vaccination info from QR-code, and **prints** it in cleartext. To achieve the goal, it requires infrastructure like **publicly accessible database** with medical information, and **manual ID check**. No attempt is suggested in the technical description to use any well-known cryptographic tool for **data privacy**. Even worse, signatures require all the signed data to be available in the cleartext. Declaring signatures short-lived with X.509 attributes is not the solution to privacy. To be constructive, please let me remind zero-knowledge proofs were considered for democratic voting since late 80s. According to ["Interoperability of health certificates Trust framework V.1.0 2021-03-12"](https://ec.europa.eu/health/sites/default/files/ehealth/docs/trust-framework_interoperability_certificates_en.pdf) section "7 Verification protocol", scanner verifies signature and **prints** the the signed data (offline part): > > Once this digital signature has been verified, the verification > software can decode the information in the 2D barcode and rely on its > content. > > > UVCI part of the certificate is the searching key into a database expected later (function creep): > > Online verification will rely on the UVCI and it will be incorporated > in the next version of the specifications (V2). > > > EU Commission [was asked](https://www.europarl.europa.eu/doceo/document/P-9-2021-001985_EN.html) on zero knowledge applicability: > > Parliamentary questions, 13 April 2021, Pier Nicola Pedicini > (Verts/ALE) > ... > Is the Commission considering: > > > 1. using ZKP for the Digital Green Certificate; > ... > > > Brian Behlendorf (Linux Foundation) [did say](https://www.wilsoncenter.org/event/vaccine-passports-public-health-solution-or-ethical-legal-minefield) at the "Vaccine Passports: A public health solution or ethical & legal minefield?": > > There’s been recent advancements in cryptography and mathematics that > are much better aligned with this idea of being able to prove a thing > without having to show a lot of information about that thing. .. That > same kind of zero-knowledge system and zero-knowledge proof needs to > be something that we standardize across the system. > > > Update: cryptographic aspects of the [recent data leak](https://www.politico.eu/article/macron-health-pass-data-breach-more-health-care-workers-identified/) may include reasoning like untraceability of copying signed data that was sent out for verification at least twice, and precise meaning of "unavailable" of that signed data.
32,885,630
When trying to map, I got this error: > > Association references unmapped class: System.Object > > > My class: ``` public partial class MessageIdentifier { public virtual int ID { get; set; } public virtual object Item { get; set; } } ``` And the convention: ``` public class MyUsertypeConvention : IPropertyConvention { public void Apply(IPropertyInstance instance) { if (instance.Type.Name == "Object") instance.CustomType<string>(); } } ``` Kindly suggest how to map?
2015/10/01
[ "https://Stackoverflow.com/questions/32885630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210986/" ]
As a simple *(quick, naive)* solution - I would suggest to create and map real `string` property. And then let your *setter* and *getter* *(or some AOP or listener)* to do the "to/from string conversion": ``` public partial class MessageIdentifier { public virtual int ID { get; set; } public virtual object Item { get { return ... my conversion from string; } set { ItemString = ...my conversion to string; } } public virtual string ItemString { get; set; } } ``` A smart and preferred *(but a bit more challenging)* is to create `CustomType` - which will hide that conversion and support REUSE. Check e.g. here * [NHibernate Pitfalls: Custom Types and Detecting Changes](http://weblogs.asp.net/ricardoperes/nhibernate-pitfalls-custom-types-and-detecting-changes) * [Creating and Testing a Custom NHibernate User Type](http://jarrettmeyer.com/post/9293603159/creating-and-testing-a-custom-nhibernate-user-type)
Not a satisfactory answer. It doesn't work with class that is generated from xsd by using XML. You can try the following: ``` public partial class MessageIdentifier { public virtual int ID { get; set; } private object itemField; public object Item { get { return this.itemField; } set { this.itemField = value; } } } ```
36,389,377
``` class BO2Offsets { public: struct Prestige { u32 Offset { 0x000000 }; char One { 0x01 }, Two { 0x02 }, Three { 0x03 }, Four { 0x04 }, Five { 0x05 }, Six { 0x06 }, Seven { 0x07 }, Eight { 0x08 }, Nine { 0x09 }, Ten { 0x0A }, MasterPrestige { 0x0B }, CheatedPrestige { 0x0C }; }; }; BO2Offsets BO2; ``` main.c ``` BO2 *BO3; ``` I'm creating a new element as BO2 but it's returned me an error: ``` error: 'BO3' was not declared in this scope ``` How can I resolve this ? EDIT: When I declare BO3 like that: ``` BO2Offsets *BO3; ``` I use BO3 like this: ``` BO3->Prestige->Offset ``` And I'm getting an error: error: invalid use of 'struct BO2Offsets::Prestige'|
2016/04/03
[ "https://Stackoverflow.com/questions/36389377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5898943/" ]
You need a `typedef` there. What you have right now is a variable declaration. Change `BO2Offsets BO2;` to `typedef BO2Offsets BO2;` --- As to your second question, you can't use `Prestige` like that because it is not data member. If you need to access the inner type, you need `BO2Offsets::Prestige::Offset`
BO2 isn't type, is only variable name, and compiler want type. use ``` BO2Offsets * B03; ``` EDIT: in the second place use ``` BO3->Prestige.anyName.Offset; ``` EDIT2; OK folks, if everyone edit his contents, I edit too: struct is improperly introduced, field cannot bee accessed. Now such concept compiles OK on modern GCC. BTW such introduction of `Prestige` isn't too useful, is similar like 'anonymous class' (to some degree). I allays declare struct / class at higher level. In this fragment can bee omitted. But give name for field (my `anyName`) is important to access his internal fields. ``` class BO2Offsets { public: struct Prestige { u32 Offset { 0x000000 }; char One { 0x01 }, Two { 0x02 }, Three { 0x03 }, Four { 0x04 }, Five { 0x05 }, Six { 0x06 }, Seven { 0x07 }, Eight { 0x08 }, Nine { 0x09 }, Ten { 0x0A }, MasterPrestige { 0x0B }, CheatedPrestige { 0x0C }; } anyName; // here !!! }; ```
38,668,067
I am new to programming and was trying to solve a problem. What I want is to have two loops simultaneously decreasing. ``` for i in range(1000,100,-1): for j in range(1000,100,-1): product=j*k ``` If I'am not wrong, this would give me 1000\*1000, 1000\*999, 1000\*998 and so on. What if I want 1000\*1000, 999\*999, 998\*998 and so on?
2016/07/29
[ "https://Stackoverflow.com/questions/38668067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6656096/" ]
For this case, you should just use one loop: ``` for i in range(1000, 100, -1): product = i*i ... ``` For the general case of wanting to advance two loop variables simultaneously instead of nesting the loops, you want `zip`: ``` for i, j in zip(some_iterable, some_other_iterable): ... ```
I do not see the point why you should need two loops surely you would do: ``` for i in range(1000,100,-1): product=i*i ```
1,971,141
Is it possible to add a button to a tabbed pane like in firefox. ![enter image description here](https://i.stack.imgur.com/vtVsG.png) The plus-button is what I want. Thanks
2009/12/28
[ "https://Stackoverflow.com/questions/1971141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155137/" ]
I think you should be able to manage it by building your own `JTabbedPaneUI` and setting it on the `JTabbedPane` using `setUI`. Your `ComponentUI` has methods to get a hold of the accessible children. If you specify a `JButton` and a `JLabel` then you may be in business. I haven't attempted this myself though. This is "at your own risk" :)
I have tried several solutions and came with this one: ``` import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; public class TestTab { public static void main(String[] args) { JFrame parent = new JFrame(); final JTabbedPane tabEntity = new JTabbedPane(); tabEntity.addTab("Details", null, new JScrollPane()); tabEntity.addTab("Context", null, new JScrollPane()); tabEntity.addTab("", null, new JScrollPane()); addButtonToTab(tabEntity); parent.add(tabEntity); parent.setSize(new Dimension(400, 200)); parent.setVisible(true); } public static void addButtonToTab(final JTabbedPane tabEntity) { tabEntity.setTabComponentAt(tabEntity.getTabCount() - 1, new JButton( "+")); } } ``` So you have: [![Button near tab example](https://i.stack.imgur.com/mTXML.png)](https://i.stack.imgur.com/mTXML.png)
9,072,563
Take this code: ``` var obj = { init: function(){ console.log(obj.count); //or console.log(this.count); }, count: 1, msg: 'hello' } obj.init(); ``` I can access property of obj by `this` or the variable name `obj` both. Is there any advantage in using **`this`** ? Because in my opinion using the object name `obj` adds clarity to the code.
2012/01/30
[ "https://Stackoverflow.com/questions/9072563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/702469/" ]
As already mentioned in paislee's answer, this is a variation on the [knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem). In fact, this specific problem is called the [subset sum problem](https://en.wikipedia.org/wiki/Subset_sum_problem), and like the knapsack problem, it is NP-complete. The linked Wikipedia page shows how to solve the problem using dynamic programming, but note that due to its NP completeness it will always be slow/impossible to solve if you make your list of integers too large. Here are some more related SO questions: * [Subset sum Problem](https://stackoverflow.com/questions/4355955/subset-sum-algorithm) * [Subset Sum algorithm](https://stackoverflow.com/questions/4355955/subset-sum-algorithm) * [Optimizing subset sum implementation](https://stackoverflow.com/questions/6236684/optimizing-subset-sum-implementation)
Read other answers/comments first. Here is a solution that could be used for a *small* set of data. ``` double[] nums = new double[] { 10,20,30,40,50,60,70,80,90,100,150,200,250,300,400,500}; Parallel.ForEach(GetIndexes(nums.Length), list => { if (list.Select(n => nums[n]).Sum()==350) { Console.WriteLine(list.Aggregate("", (s, n) => s += nums[n] + " ")); } }); IEnumerable<IEnumerable<int>> GetIndexes(int count) { for (ulong l = 0; l < Math.Pow(2, count); l++) { List<int> list = new List<int>(); BitArray bits = new BitArray(BitConverter.GetBytes(l)); for (int i = 0; i < sizeof(ulong)*8; i++) { if (bits.Get(i)) list.Add(i); } yield return list; } } ```
3,812,621
The idea is simple - I have two tables, categories and products. Categories: ``` id | parent_id | name | count 1 NULL Literature 6020 2 1 Interesting books 1000 3 1 Horrible books 5000 4 1 Books to burn 20 5 NULL Motorized vehicles 1000 6 5 Cars 999 7 5 Motorbikes 1 ... ``` Products: ``` id | category_id | name 1 1 Cooking for dummies 2 3 Twilight saga 3 5 My grandpa's car ... ``` Now while displayed, the parent category contains all the products of all the children categories. Any category **may have children categories**. The count field in the table structure contains (or at least I want it to contain) count of all products displayed in this particular category. On the front-end, I select all subcategories with a simple recursive function, however I'm not so sure how to do this in a SQL procedure (yes it has to be a SQL **procedure**).The tables contain about a hundread categories of any kind and there are over 100 000 products. Any ideas?
2010/09/28
[ "https://Stackoverflow.com/questions/3812621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371707/" ]
As you havent accepted an answer yet i thought i'd post my method for handling trees in mysql and php. (single db call to non recursive sproc) Full script here : <http://pastie.org/1252426> or see below... Hope this helps :) **PHP** ``` <?php $conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306); $result = $conn->query(sprintf("call product_hier(%d)", 3)); echo "<table border='1'> <tr><th>prod_id</th><th>prod_name</th><th>parent_prod_id</th> <th>parent_prod_name</th><th>depth</th></tr>"; while($row = $result->fetch_assoc()){ echo sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row["prod_id"],$row["prod_name"],$row["parent_prod_id"], $row["parent_prod_name"],$row["depth"]); } echo "</table>"; $result->close(); $conn->close(); ?> ``` **SQL** ``` drop table if exists product; create table product ( prod_id smallint unsigned not null auto_increment primary key, name varchar(255) not null, parent_id smallint unsigned null, key (parent_id) )engine = innodb; insert into product (name, parent_id) values ('Products',null), ('Systems & Bundles',1), ('Components',1), ('Processors',3), ('Motherboards',3), ('AMD',5), ('Intel',5), ('Intel LGA1366',7); delimiter ; drop procedure if exists product_hier; delimiter # create procedure product_hier ( in p_prod_id smallint unsigned ) begin declare v_done tinyint unsigned default 0; declare v_depth smallint unsigned default 0; create temporary table hier( parent_id smallint unsigned, prod_id smallint unsigned, depth smallint unsigned default 0 )engine = memory; insert into hier select parent_id, prod_id, v_depth from product where prod_id = p_prod_id; /* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */ create temporary table tmp engine=memory select * from hier; while not v_done do if exists( select 1 from product p inner join hier on p.parent_id = hier.prod_id and hier.depth = v_depth) then insert into hier select p.parent_id, p.prod_id, v_depth + 1 from product p inner join tmp on p.parent_id = tmp.prod_id and tmp.depth = v_depth; set v_depth = v_depth + 1; truncate table tmp; insert into tmp select * from hier where depth = v_depth; else set v_done = 1; end if; end while; select p.prod_id, p.name as prod_name, b.prod_id as parent_prod_id, b.name as parent_prod_name, hier.depth from hier inner join product p on hier.prod_id = p.prod_id inner join product b on hier.parent_id = b.prod_id order by hier.depth, hier.prod_id; drop temporary table if exists hier; drop temporary table if exists tmp; end # delimiter ; call product_hier(3); call product_hier(5); ```
What you want is a common table expression. Unfortunately it looks like mysql doesn't support them. Instead you will probably need to use a loop to keep selecting deeper trees. I'll try whip up an example. To clarify, you're looking to be able to call the procedure with an input of say '1' and get back all the sub categories and subsub categories (and so on) with 1 as an eventual root? like ``` id parent 1 null 2 1 3 1 4 2 ``` ? Edited: This is what I came up with, it seems to work. Unfortunately I don't have mysql, so I had to use sql server. I tried to check everythign to make sure it will work with mysql but there may still be issues. ``` declare @input int set @input = 1 --not needed, but informative declare @depth int set @depth = 0 --for breaking out of the loop declare @break int set @break = 0 --my table '[recursive]' is pretty simple, the results table matches it declare @results table ( id int, parent int, depth int ) --Seed the results table with the root node insert into @results select id, parent, @depth from [recursive] where ID = @input --Loop through, adding notes as we go set @break = 1 while (@break > 0) begin set @depth=@depth+1 --Increase the depth counter each loop --This checks to see how many rows we are about to add to the table. --If we don't add any rows, we can stop looping select @break = count(id) from [recursive] where parent in ( select id from @results ) and id not in --Don't add rows that are already in the results ( select id from @results ) --Here we add the rows to the results table insert into @results select id, parent, @depth from [recursive] where parent in ( select id from @results ) and id not in --Don't add rows that are already in the results ( select id from @results ) end --Select the results and return select * from @results ```
4,644,929
What regular expression would match any characters (including spaces), but have a maximum of 255 characters? Is this it? ``` ^[a-zA-Z0-9._]{1,255}$ ```
2011/01/10
[ "https://Stackoverflow.com/questions/4644929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/495365/" ]
Well, *anything* would be: ``` ^.{1,255}$ ``` `.` doesn't allow new lines. If that's a problem, you can use the dot-all flag (usually `/s`). If you want to add spaces to your regex, try this (note the space): * `^[a-zA-Z0-9._ \t]{1,255}$` - Allow spaces and tabs. * `^[a-zA-Z0-9._\s]{1,255}$` - Allow all whitespaces. * `^[\s\w.]{1,255}$` - Same as the above (unless your flavor supports Unicode).
Well that would not allow anything, if you want anything, you're better off using `^.{1,255}$`. Or, if you want to allow nothing as well: `^.{0,255}$`
15,376,688
I have a program that I'm trying to use which crashes often, and one of the fixes for this is to set it to only use one processor. I can easily do this through task manager manually, but I'd much prefer a solution along the lines of doubleclicking a shortcut. I've tried making at .bat file with this line of code: C:\Windows\System32\cmd.exe /C start /affinity 1 KSP.exe However, it just refuses to run. removing the /C switch only starts the cmdbox. Trying to type /affinity 1 KSP.exe into the cmdbox (Thankfully the cmdbox starts with the directory the .bat file is in, which is the same folder that the .exe isin so no problems there) simply gives this error: Invalid switch - "/affinity".
2013/03/13
[ "https://Stackoverflow.com/questions/15376688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2163655/" ]
I just ran into this same issue myself trying to run KSP on an older Win XP 32-bit rig. cmd.exe did not receive the /affinity switch until Vista, IIRC. I realize OP is over a year old, however it is still currently an issue for some users. The solution is to use psexec.exe from Sysinternals in lieu of cmd.exe, which can be found here: <http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx> Microsoft's Sysinternal's psexec's -a flag can set processor affinity on Windows XP: ``` Usage: psexec [\\computer[,computer2[,...] | @file][-u user [-p psswd]][-n s][-l][-s|-e][-x][-i [session]][-c [-f|-v]][-w directory][-d][-][-a n,n,...] cmd [arguments] -a Separate processors on which the application can run with commas where 1 is the lowest numbered CPU. For example, to run the application on CPU 2 and CPU 4, enter: "-a 2,4" ``` For example: ``` psexec -a 2 cmd /c "E:Games\KSP\KSP.exe" ``` Will run KSP on the 2nd core. (Core 1 in Task Manager) Just correct the path for your system and put that in a .bat or the Target field of a shortcut. And as an aside, you need to extract the PsTools (or simply PsExec.exe) either into C:\Windows or another folder that in the system path, or put it in your KSP root.
first be aware, you have to provide Administrator right to your program, either by right clic, and sart as admin, or by creating a task. So, after you started your cmd with those admin right, you can start your program this way: ``` <code>`start /AFFINITY 1 /B notepad.exe`</code> ``` Using procexp, and right click + set affinity on the notepad process, you will see that it use only processor 0. Doing: ``` <code>`start /AFFINITY 1 /B notepad.exe`</code> ``` And you'll see it running on processor 2. Then if you want your process running on half of the core ? Do this: ``` <code>`start /AFFINITY AA /B notepad.exe`</code> ``` On a octo core, it will run on processor 1, 3, 5, 7 * /AA is for half of the cores, the odd, (1, 3, 5, 7) * /A is for quart of the cores, odd , (1, 3) * /F is for the first half, (0, 1, 2, 3) * /FF is for all, ( 0, 1, 2, 3, 4, 5, 6, 7) Regards.
10,651
How do you justify new purchases? Do you set guidelines for yourself? "After this project, you get a new toy/tool"? Or, "Because of this new project, you get a new toy/tool"? Or do you have strict boundaries about what new tools you allow into your arsenal?
2011/10/02
[ "https://sound.stackexchange.com/questions/10651", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/28/" ]
I;ve said this before in another answer about going debt. I think it still applies: One of the rules i've learned to follow is this: "Will spending this amount of money, on that piece of gear, allow me to work better/faster/for other people/projects? If the answer is yes and you have the money reserved, do it. If in doubt, wait for better times. In other words, i only buy stuff i really need and almost never treat myself on gear. Maybe in a future time of luxury i will, but for now i save up for what's needed most, like Shaun said. I must admit that at this moment i'm doubting between buying a new laptop or an extra mkh60 for a very good price. Buying both is not an option... Question is which piece of gear is needed most right now... I'm leaning towards laptop. It's always difficult i think, so just take your time and never buy on impulse, unless you're loaded with money and 80+years old :)
The greatest asset and piece of gear is the mind and experience.
41,985,466
I'm currently doing some tests to see if my app runs correctly on Retina Macs. I have installed Quartz Debug for this purpose and I'm currently running a scaled mode. My screen mode is now 960x540 but of course the physical size of the monitor is still Full HD, i.e. 1920x1080 pixels. When querying the monitor database using `CGGetActiveDisplayList()` and then using `CGDisplayBounds()` on the individual monitors in the list, the returned monitor size is 960x540. This is what I expected because `CGDisplayBounds()` is said to use the global display coordinate space, not pixels. To my surprise, however, `CGDisplayPixelsWide()` and `CGDisplayPixelsHigh()` also return 960x540, although they're explicitly said to return pixels so I'd expect them to return 1920x1080 instead. But they don't. This leaves me wondering how can I retrieve the real physical resolution of the monitor instead of the scaled mode using the `CGDisplay` APIs, i.e. 1920x1080 instead of 960x540 in my case? Is there any way to get the scaling coefficient for a `CGDisplay` so that I can compute the real physical resolution on my own? I know I can get this scaling coefficient using the `backingScaleFactor` method but this is only possible for `NSScreen`, how can I get the scaling coefficient for a `CGDisplay`?
2017/02/01
[ "https://Stackoverflow.com/questions/41985466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197719/" ]
You need to examine the *mode* of the display, not just the display itself. Use `CGDisplayCopyDisplayMode()` and then `CGDisplayModeGetPixelWidth()` and `CGDisplayModeGetPixelHeight()`. These last two are relatively newer functions and the documentation primarily exists in the headers. And, of course, don't forget to `CGDisplayModeRelease()` the mode object.
From Ken's answer it is not obvious how you find the native mode(s). To do this, call `CGDisplayModeGetIOFlags` and choose from the modes that have the `kDisplayModeNativeFlag` set (see `IOKit/IOGraphicsTypes.h`, the value is 0x02000000). ``` const int kFlagNativeMode = 0x2000000; // see IOGraphicsTypes.h const CGFloat kNoSize = 100000.0; NSScreen *screen = NSScreen.mainScreen; NSDictionary *desc = screen.deviceDescription; unsigned int displayID = [[desc objectForKey:@"NSScreenNumber"] unsignedIntValue]; CGSize displaySizeMM = CGDisplayScreenSize(displayID); CGSize nativeSize = CGSizeMake(kNoSize, kNoSize); CFStringRef keys[1] = { kCGDisplayShowDuplicateLowResolutionModes }; CFBooleanRef values[1] = { kCFBooleanTrue }; CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, (const void**)keys, (const void**)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ); CFArrayRef modes = CGDisplayCopyAllDisplayModes(displayID, options); int n = CFArrayGetCount(modes); for (int i = 0; i < n; i++) { CGDisplayModeRef mode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i); if (CGDisplayModeGetIOFlags(mode) & kFlagNativeMode) { int w = CGDisplayModeGetWidth(mode); // We get both high resolution (screen.backingScaleFactor > 1) // and the "low" resolution, in CGFloat units. Since screen.frame // is CGFloat units, we want the lowest native resolution. if (w < nativeSize.width) { nativeSize.width = w; nativeSize.height = CGDisplayModeGetHeight(mode); } } // printf("mode: %dx%d %f dpi 0x%x\n", (int)CGDisplayModeGetWidth(mode), (int)CGDisplayModeGetHeight(mode), CGDisplayModeGetWidth(mode) / displaySizeMM.width * 25.4, CGDisplayModeGetIOFlags(mode)); } if (nativeSize.width == kNoSize) { nativeSize = screen.frame.size; } CFRelease(modes); CFRelease(options); float scaleFactor = screen.frame.size.width / nativeSize.width; ```
17,196,117
Sometimes you need to check whether you Linux 3D acceleration is really working (besides the `glxinfo` output). This can be quickly done by the `glxgears` tool. However, the FPS are often limited to the displays vertical refresh rate (i.e. 60 fps). So the tool becomes more or less useless since even a software render can produce 60FPS glxgears easily on modern CPUs. I found it rather hard to get a quick and easy solution for this, I answer my own question. Hopefully it saves your time.
2013/06/19
[ "https://Stackoverflow.com/questions/17196117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/884474/" ]
The `vblank_mode` environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others. ``` $> vblank_mode=0 glxgears ```
If you're using the NVIDIA closed-source drivers you can vary the vertical sync mode on the fly using the [`__GL_SYNC_TO_VBLANK` environment variable](http://us.download.nvidia.com/XFree86/Linux-x86_64/304.43/README/openglenvvariables.html): ``` ~$ __GL_SYNC_TO_VBLANK=1 glxgears Running synchronized to the vertical refresh. The framerate should be approximately the same as the monitor refresh rate. 299 frames in 5.0 seconds = 59.631 FPS ~$ __GL_SYNC_TO_VBLANK=0 glxgears 123259 frames in 5.0 seconds = 24651.678 FPS ``` This works for me on Ubuntu 14.04 using the 346.46 NVIDIA drivers.
22,650
Is there an XDM variant (kdm, gdm etc.) that allows graphical login without a physical keyboard? I have a tablet computer (like iPad, but Intel i5) running KDE and would prefer that users have to login to use it. However, the virtual keyboard is not available in the xdm screens I have seen. I could plug in keyboard, but that is kludgy; I'd prefer to do something more like Android's gesture login. Do you know of any options?
2011/10/15
[ "https://unix.stackexchange.com/questions/22650", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/11146/" ]
I know that GDM in recent versions of Fedora runs a panel with accessibility options available so that an on-screen keyboard can be run. I'm not sure how it's configured to do so though.
If you are gdm user you can add some kind of onscreen keaboard or gesture grapper to `/etc/gdm/Init/Default` just before `exit 0` This [mini howto for screen keaboard](http://ubuntuforums.org/showpost.php?p=7959338&postcount=8) will give you examples how to do it with `kdm` and with different virtual keyboards. Here's an example with `onboard`. ``` onboard -s 684x200 -x 170 -y 568 & exit 0 ``` I've also just updated an answer to [Iphone type login screen question](https://unix.stackexchange.com/a/29767/14267) that will give you a quick'n'dirty way of getting login gestures. I do not advice it to be *the* solution because of security concerns.
20,351,637
I'm trying to create a proxy server to pass `HTTP GET` requests from a client to a third party website (say google). My proxy just needs to mirror incoming requests to their corresponding path on the target site, so if my client's requested url is: ``` 127.0.0.1/images/srpr/logo11w.png ``` The following resource should be served: ``` http://www.google.com/images/srpr/logo11w.png ``` Here is what I came up with: ``` http.createServer(onRequest).listen(80); function onRequest (client_req, client_res) { client_req.addListener("end", function() { var options = { hostname: 'www.google.com', port: 80, path: client_req.url, method: client_req.method headers: client_req.headers }; var req=http.request(options, function(res) { var body; res.on('data', function (chunk) { body += chunk; }); res.on('end', function () { client_res.writeHead(res.statusCode, res.headers); client_res.end(body); }); }); req.end(); }); } ``` It works well with html pages, but for other types of files, it just returns a blank page or some error message from target site (which varies in different sites).
2013/12/03
[ "https://Stackoverflow.com/questions/20351637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2808025/" ]
Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing `url =` and it will automatically set HTTP and HTTPS stuff without manually doing it. ``` /* eslint-disable @typescript-eslint/no-var-requires */ // https://stackoverflow.com/a/63602976/470749 const express = require('express'); const app = express(); const https = require('https'); const http = require('http'); // const { response } = require('express'); const targetUrl = process.env.TARGET_URL || 'https://jsonplaceholder.typicode.com'; // Run localtunnel like `lt -s rscraper -p 8080 --print-requests`; then visit https://yourname.loca.lt/todos/1 . const proxyServerPort = process.env.PROXY_SERVER_PORT || 8080; // eslint-disable-next-line max-lines-per-function app.use('/', function (clientRequest, clientResponse) { const parsedHost = targetUrl.split('/').splice(2).splice(0, 1).join('/'); let parsedPort; let parsedSSL; if (targetUrl.startsWith('https://')) { parsedPort = 443; parsedSSL = https; } else if (targetUrl.startsWith('http://')) { parsedPort = 80; parsedSSL = http; } const options = { hostname: parsedHost, port: parsedPort, path: clientRequest.url, method: clientRequest.method, headers: { 'User-Agent': clientRequest.headers['user-agent'], }, }; const serverRequest = parsedSSL.request(options, function (serverResponse) { let body = ''; if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) { serverResponse.on('data', function (chunk) { body += chunk; }); serverResponse.on('end', function () { // Make changes to HTML files when they're done being read. // body = body.replace(`example`, `Cat!`); clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers); clientResponse.end(body); }); } else { serverResponse.pipe(clientResponse, { end: true, }); clientResponse.contentType(serverResponse.headers['content-type']); } }); serverRequest.end(); }); app.listen(proxyServerPort); console.log(`Proxy server listening on port ${proxyServerPort}`); ``` [![enter image description here](https://i.stack.imgur.com/gSCst.png)](https://i.stack.imgur.com/gSCst.png) [![enter image description here](https://i.stack.imgur.com/NNw1f.png)](https://i.stack.imgur.com/NNw1f.png)
Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on *v8.1.0*). I've found it particular useful for integration testing so here's my share: ``` /** * Once this is running open your browser and hit http://localhost * You'll see that the request hits the proxy and you get the HTML back */ 'use strict'; const net = require('net'); const http = require('http'); const PROXY_PORT = 80; const HTTP_SERVER_PORT = 8080; let proxy = net.createServer(socket => { socket.on('data', message => { console.log('---PROXY- got message', message.toString()); let serviceSocket = new net.Socket(); serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => { console.log('---PROXY- Sending message to server'); serviceSocket.write(message); }); serviceSocket.on('data', data => { console.log('---PROXY- Receiving message from server', data.toString(); socket.write(data); }); }); }); let httpServer = http.createServer((req, res) => { switch (req.url) { case '/': res.writeHead(200, {'Content-Type': 'text/html'}); res.end('<html><body><p>Ciao!</p></body></html>'); break; default: res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('404 Not Found'); } }); proxy.listen(PROXY_PORT); httpServer.listen(HTTP_SERVER_PORT); ``` <https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999>
55,598,481
I know there is a package called dart:convert which let me decode base64 image. But apparently, it doesn't work with pdf files. How can I decode the base64 PDF file in Flutter? I want to store it in Firebase Storage (I know how to do it) but I need the File variable to do it. I have a web service written in node js where I have a POST route. There, I create a pdf file and encode it to base 64. The response is a base64 string, look at the code. ``` router.post('/pdf', (req, res, next) => { //res.send('PDF'); const fname = req.body.fname; const lname = req.body.lname; var documentDefinition = { content: [ write your pdf with pdfMake.org ], styles: { write your style }; const pdfDoc = pdfMake.createPdf(documentDefinition); pdfDoc.getBase64((data) => { res.send({ "base64": data }); }); }); ``` As you can see, it returns the pdf as a base64 string. Now, in Flutter, I have written this: ``` http.post("https://mypostaddreess.com",body: json.encode({"data1":"data"})) .then((response) { print("Response status: ${response.statusCode}"); print("Response body: ${response.body}"); var data = json.decode(response.body); var pdf = base64.decode(data["base64"]); }); } ``` I have the PDF in the variable 'pdf' as you see. But I don't know how to decode it to download the pdf or show it in my Flutter app.
2019/04/09
[ "https://Stackoverflow.com/questions/55598481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10405853/" ]
@SwiftingDuster a little added, maybe besides decoding, it's also necessary to create a pdf file and open it. ``` createPdf() async { var bytes = base64Decode(widget.base64String.replaceAll('\n', '')); final output = await getTemporaryDirectory(); final file = File("${output.path}/example.pdf"); await file.writeAsBytes(bytes.buffer.asUint8List()); print("${output.path}/example.pdf"); await OpenFile.open("${output.path}/example.pdf"); setState(() {}); } ``` library needed: 1. open\_file 2. path\_provider 3. pdf
I think it's better to get the BufferArray and convert it into a pdf file. Check out my answer from here : [Get pdf from blob data](https://stackoverflow.com/questions/57111488/how-to-convert-bytebuffer-to-pdf/68320545#68320545)
432,176
If my service is inserting into a varchar column with a certain max length, I can either 1. validate its length prior to inserting to avoid getting an error from the database if the string is too long 2. try inserting it as is and then handle the error if the database say it's too long, and giving the consumer a validation error in that case The first seems to have the advantage of not causing to be returned by the database, but I would have to define the max length both in my application code and database schema (so that it could become inconsistent due to programmer oversight).
2021/09/23
[ "https://softwareengineering.stackexchange.com/questions/432176", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/276066/" ]
You should do ***both*** (and, if there's a web-based User Interface involved, you should be *limiting* the length of the input field *there* as well!) Yes, it means you have the length of this field defined in multiple places but that's no different to having field names in SQL in the Application code. If those become "inconsistent due to programmer oversight" then the code breaks then as well. That's what **Testing** is for. The database can throw *all sorts* of things back at you (depending on how much constraint you place on the arriving data) and you should be prepared for this but there's *nothing* wrong with a bit of Defensive Programming to reduce the number of times it has to get all "upset" with you. Also, the database will probably baulk at the *first* errant field - your code can be more "intelligent" and check *every* field at once (within reason) and present a single response containing multiple errors.
This is not an answer to the literal question you posed, but based on the (supposedly) underlying requirement. You typically declare a varchar length because you know that longer strings are invalid for that field, because of some business logic / domain analysis. In my experience, all cases with a limited string length also had some syntax requirements as well. So, rejecting only strings that exceed some length limit still allows for invalid data. What you really need is a powerful syntax checker. The preferred language for expressing syntax requirements is [Regular Expressions](https://en.wikipedia.org/wiki/Regular_expression). And as databases typically don't support regex-based constraints, this validation has to be done in the application anyway. Then, the length limitation comes for free, as part of your regex. You have to decide yourself then whether the length constraint still makes sense in the database (e.g. see the next paragraph). One more argument for not limiting length in database: Validity constraints can change over time (e.g. nowadays we have internet top-level domains with more than 4 characters), and installing a new application software version is much easier and faster than migrating a big database table from varchar(4) to varchar(32).
134,301
I would like to have some clarification on the below question and its given answer. > > Does the following statement agree with the views of the writer in given passage? > You have to answer, > > > * True: *If the statement agrees with the writer* > * False: *If the state does not agree with the writer* > * Not given: *if there is no information about this in the passage* > > > Statement: > > > **Guitar was used in rock and roll from the 1940s.** > > > Passage: > > > **In the earliest rock and roll styles of the late 1940s and early 1950s, either the piano or saxophone was often the lead instrument, but these were generally replaced or supplemented by guitar in the middle to late 1950s.** > > > According to the tutor, the answer is **FALSE** but I think the answer to this question should actually be **NOT GIVEN**. The passage says guitar generally became the LEAD instrument in the 1950s, It DOES NOT SAY clearly whether guitars were used in 1940s or not. Hence the answer should be **NOT GIVEN**. Which is the correct answer?
2017/07/03
[ "https://ell.stackexchange.com/questions/134301", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/56324/" ]
The answer is **false**. The passage of text talks about the piano or saxophone being the lead instrument, but then says they were "replaced **or supplemented by** the guitar in the middle to late 1950s." If it only said "replaced", then you could make an argument for "not given", because the piano or saxophone being replaced by the guitar as the **lead** instrument doesn't say anything about the presence of guitars prior to that point. However, that leaves the "or supplemented by" part, so let's look at the definition for the verb "supplement": > > to complete, **add to**, or extend by a supplement. > > [dictionary.com](http://www.dictionary.com/browse/supplement?s=t) (emphasis mine) > > > Saying that rock and roll music was "supplemented by the guitar in the middle to late 1950s" is the same as saying "the guitar was added to rock and roll music in the middle to late 1950s". If you're adding something, it wasn't present before, so the guitar wasn't involved at all in the 1940s.
I think the teacher had a point. It is highly possible that the lead instrument thing was all but a distractor. Closely look at the statement: Guitar was used in **rock and roll from the 1940s.** The statement implies 2 aspects: * Firstly, rock and roll **has been around from the 1940s**. * Secondly, guitar was available for use in rock and roll by that same period of time. The 1st line of the passage mentioned: In the **earliest** rock and roll styles of **the late 1940s and early 1950s** * It can be drawn from the passage that rock and roll **didn't exist** from the 1940s until late 1940s. Probably that's what make the statement false, not the lead instrument thing.
564,922
I keep getting this error when I start Android Studio. I am running Ubuntu, I did a fresh install and this happened upon start up. > > ADB not responding. If you'd like to retry, then please manually kill > "adb" and click 'Restart' > > > I have [tried](https://stackoverflow.com/questions/22381790/adb-not-responding-wait-more-or-kill-adb-or-restart-ubuntu-13-64-bit) this solution. I tried making an AVD, and it doesn't want to run on there. I double checked that ADB is added to my PATH. Is there more information I can provide? Any response with information or questions is helpful.
2014/12/24
[ "https://askubuntu.com/questions/564922", "https://askubuntu.com", "https://askubuntu.com/users/299593/" ]
I had same problem while configuring Android Studio. I tried following command in terminal. ``` sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6 ``` If that doesn't helps make sure that "adb" in "AndroidStudioSdk/platform-tools/" folder is executable. If its executables permission are not set than set it with following command. ``` chmod uog+x abd ``` Hopes this will help.
I've been having this same problem but under a Linux system (32-bit), after searching t'interweb and finding nothing that helped me I went about fixing this issue myself. I found that if I try to execute certain binaries that are bundled with Android Studio they would not execute, infact both adb and java threw the same error: > > java/adb: cannot execute binary file: Exec format error > > > The fix for java is to use the system jdk not the one bundled with Android Studio. So I thought what the hell and changed the bundled adb binary. First thing is to backup the bundled adb: ``` mv '/path/to/bundled/adb' '/path/to/bundled/adb~' ``` I then symlinked my system adb to Android Studio's sdk folder: (your systems adb may be in a different location) ``` ln -s '/usr/bin/adb' '/path/to/bundled/adb' ``` And voila it works! I think it may be due to the binaries being for a 64-bit CPU but I dunno, can anyone confirm this??
3,799
I've got following problem: - We have set of N people - We have set of K images - Each person rates some number of images. A person might like or not like an image (these are the only two possibilites) . - The problem is how to calculate likelihood that some person likes a particular image. I'll give example presenting my intuition. N = 4 K = 5 + means that person likes image - means that person doesn't like image 0 means that person hasn't been asked about the image, and that value should be predicted ``` x 1 2 3 4 5 1 + - 0 0 + 2 + - + 0 + 3 - - + + 0 4 - 0 - - - ``` Person 1 will probably like image 3 because, person 2 has similar preferences and person 2 likes image 3. Person 4 will probably not like image 2 because no one else likes it and in addition person 4 does not like most images. Is there any well known method, which can be used to calculate such likelihood?
2010/10/20
[ "https://stats.stackexchange.com/questions/3799", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/1643/" ]
I used Lisrel, AMOS, Mplus before but only R. In R, one can do almost every step to fit SEM with the data, from exploring pattern to fitting the model and improving the model. Recently (2012), there are many new R packages and updated ones, which allow us to fit SEM intuitively. Moreover, R is free and open-source software. Here is a review on using R to run/fit SEM, and still updating. <http://pairach.com/2011/08/13/r-packages-for-structural-equation-model/>
THANK-YOU!! I tried a few of these but the free software Dia is all I need to draw my structural equation model (4 latent variables). I viewed a few Youtube tutorials and went to the wiki as needed <https://wiki.gnome.org/Apps/Dia/Documentation> I did this in an evening or in about 3 hours had my full model developed and edited.
20,635
This question has been nagging me for ages. I've read a lot of Sheldon Brown's site and actually tend to use bikes from the 70s-80s because they're more economical for daily use and especially for a student like me. But I've noticed that *some* of his opinions can be controversial (his discussion of "lawyer lips"), can fly in the face of industry practices (that all leather saddles, 'properly cared for', are better than any plastic saddle), questionable (that the Peugeot UO-8 makes for the greatest touring bike of all time) and then, sometimes, his opinions seem on a troll level, which I can't think of any examples off the top of my head, but have caught myself falling prey to them. A lot of his material is either very enlightening (his discussion of brake usage) or helpful in that you simply can't find the topic anywhere else on the web. So the question is, is Sheldon Brown's site really the one-stop for all knowledge pertaining especially to older bicycles, or should he be taken simply as a prolific writer who wrote on a great many topics and should be taken with a large grain of salt? I guess the real question is, how much do bike mechanics especially and others depend on his work, or is it simply a convenient online resource for people new to the sport?
2014/03/08
[ "https://bicycles.stackexchange.com/questions/20635", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/8649/" ]
Sheldon Brown was a good man, a good cyclist, and he spent an inordinate amount of time writing answers for everybody to questions that every new cyclist has. In a lot of ways, his answers were pretty dead on. However, like any person with the energy and commitment that Mr. Brown showed with his site, he was very opinionated on a number of issues which are controversial now. Because he was also among the first cyclists to use the internet to spread his ideas and knowledge to anyone willing to listen, his ideas are often treated as canonical, even when time and science have moved on. As with any science, new ideas and equipment overtake the old, and new methodologies, for fitting, for bike construction, and for fitness are tested, and either adopted or discarded. There are cyclists who adhere to what Mr. Brown said on any topic, regardless of the evidence to the contrary which is available now. But then, there are dogmatics in any religion, and cycling is a religion for many. And if cycling was a religion, then Mr. Brown was its first, or at least best known, Internet age missionary. He deserves respect for his efforts, but not dogmatic adherence to his viewpoints. Try his ideas and use what works. If something doesn't work for you, discard it, and find something that does. He would be the first to tell you to think for yourself.
Every theory in science can be discussed. No one can say something absolute - even things, that looks now like "the only truth", can be overridden the next year (or even before). Sheldon Brown was a great bicyclist, that knew the theory and physics of bikes. He also was a rider with lot of experience in it. He wrote his own feelings and practice. His opinion may be discussed (especially in such subjective things like saddle), and it is in some books. Yet his posts are highly honored by many cyclists.
17,601,473
I'm creating a batch to turn my laptop into wifi an make my life easier to type lines in cmd each time. The trouble is the wifi name always get set to **key=** insted of the one which I enter. Here is what I did: ``` @echo OFF set /p option="Enter 1 to create wifi, Enter 2 to stop wifi " IF %option% EQU 1 ( set /p id="Enter wifi Name:" set /p key="Set password:" netsh wlan set hostednetwork mode=allow ssid = %id% key = %key% netsh wlan start hostednetwork ) IF %option% EQU 2 ( netsh wlan set hostednetwork mode=disallow ) timeout /t 5 ```
2013/07/11
[ "https://Stackoverflow.com/questions/17601473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809307/" ]
``` @echo off setlocal enabledelayedexpansion SET /P myvar="Enter variables: " set argCount=0 for %%x in (%myvar%) do ( set /A argCount+=1 set "argVec[!argCount!]=%%~x" ) echo Number of processed arguments: %argCount% for /L %%i in (1,1,%argCount%) do ( echo %%i- "!argVec[%%i]!" ) ``` The result of calling the function will be: ``` function.bat Enter variables: a b c 1- "a" 2- "b" 3- "c" ``` In this way, we can call the function with parameters, use the parameters in another part of the function, and iterate using new inputs from SET.
Here is another way to do it. I also removed the spaces around ssid= and key= as that may be an issue. ``` @echo OFF set "option=" set /p "option=Enter a name to create wifi, or just press Enter to stop wifi: " IF not defined option ( netsh wlan set hostednetwork mode=disallow goto :EOF ) set /p key="Set password:" netsh wlan set hostednetwork mode=allow ssid=%option% key=%key% netsh wlan start hostednetwork timeout /t 5 ```
20,028,186
``` public class Employee2 implements java.io.Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` i first serialized the Employee2 object.Then added one more field i.e age under Employee2. Now deserialize the Employee2 and get the below error > > java.io.InvalidClassException: Test.Employee2; local class > incompatible: stream classdesc serialVersionUID = -342194960183674221, > local class serialVersionUID = -8890407383319808316 > > > This is expected as structure of the class has been modified ( hence serialVersionUID got modified which is calculated internally at the time of serialization and deserialization) Now if i declare the below field under Employee2 and repeat the scenario, as per my understanding i should not get InvalidClassException because serialVersionUID is same at the time of serialization and deserialization but still i am getting InvalidClassException exception. Why? If serialization process still using serialVersionUID calculated at run time instead of manually defined under class then what is the use of declaring it? > > static final Long serialVersionUID = 1L; > > >
2013/11/17
[ "https://Stackoverflow.com/questions/20028186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/802050/" ]
Look again. 'Long' isn't the same as 'long', and 1L isn't the same as -342194960183674221L, which is what is in the stream.
An serialVersionUID is a hash of its originating class. If the class is updated, for example with different fields, the serialVersionUID can change. You have four (at least) possible courses of action: 1. Leave out the serialVersionUID. This tells the runtime that there are no differences between versions of classes when serialising and deserialising. 2. Always write a default serialVersionUID, which looks like the heading of this thread. That tells the JVM that all versions with this serialVersionUID count as the same version. 3. Copy an serialVersionUID from a previous version of the class. That tells the runtime that this version and the version the SUID came from are to be treated as the same version. 4. Use a generated serialVersionUID for each version of the class. If the serialVersionUID is different in a new version of the class, that tells the runtime that the two versions are different and serialised instances of the old class cannot be deserialised as instances of the new class. Source : <http://www.coderanch.com/t/596397/java/java/private-static-final-long-serialVersionUID>
49,292,556
I have to project some fields of javascript to new object. for example I have a below object ``` var obj = { fn : 'Abc', ln : 'Xyz', id : 123, nt : 'Note', sl : 50000} ``` and i want new object containing `fn and id` ``` var projectedObj = { fn : 'Abc', id : 123 } ``` on the basis of projection ``` var projection = { fn : 1, id : 1 } ``` something like this ``` var projectedObj = project(obj, projection); ``` So what is the best way or optimized way to do this.
2018/03/15
[ "https://Stackoverflow.com/questions/49292556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4231809/" ]
Just loop through the projection object and get the keys projected. For example, ``` function project(obj, projection) { let projectedObj = {} for(let key in projection) { projectedObj[key] = obj[key]; } return projectedObj; } ```
As an alternative approach of not passing in a projection object but instead listing up the properties to project as a comma separated string, this module can do that. Note that this module supports not object, but arrays. ``` var linqmodule = (function() { projection = function(members) { var membersArray = members.replace(/s/g, "").split(","); var projectedObj = {}; for (var i = 0; i < this.length; i++) { for (var j = 0; j < membersArray.length; j++) { var key = membersArray[j]; if (j === 0) { projectedObj[i] = {}; } projectedObj[i][key] = this[i][key]; } } return projectedObj; }; Array.prototype.select = projection; dumpmethod = function(arrayobj) { var result = ""; result += "["; for (var i = 0; i < Object.keys(arrayobj).length; i++) { var membersArray = Object.keys(arrayobj[i]); for (var j = 0; j < membersArray.length; j++) { if (j === 0) { result += "{"; } var key = membersArray[j]; result += "key: " + key + " , value: " + arrayobj[i][key] + (j < membersArray.length - 1 ? " , " : ""); if (j === membersArray.length - 1) { result += "}" + (i < Object.keys(arrayobj).length - 1 ? "," : "") + "\n"; } } } result += "]"; return result; }; return { dump: dumpmethod }; })(); ``` To project your array of Json objects you can then use this example as a guide: ``` var someCountries = [ { country: "Norway", population: 5.2, code: "NO" }, { country: "Finland", population: 5.5, code: "SU" }, { country: "Iceland", population: 0.4, code: "IC" }, { country: "Sweden", population: 10.2, code: "SW" } ]; var result = someNums.select("country,population"); console.log(linqmodule.dump(result)); ``` And the resulting array then contains the projected result (and copied into a new array) without the field 'code'. This does not answer the question, as it asked about a single object and a projection object, but it shows how to achieve the same with an array of objects (having the same fields in each object of the array). So many will then find it useful for similar scenarios.
4,631,960
I just want to be able to split my VIM buffers/windows vertically and/or horizontally with a keyboard shortcut. I would like to use the following shortcuts: Vertical split ``` ,v ``` Horizontal split ``` ,h ``` That would be a **,** *(comma)* followed by a **v** to vertically split a buffer & **,** (comma) followed by a **h** to horizontally split a buffer.
2011/01/08
[ "https://Stackoverflow.com/questions/4631960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523883/" ]
``` nnoremap ,v <C-w>v nnoremap ,h <C-w>s ```
``` nnoremap ,v :vsplit<CR> nnoremap ,h :split<CR> ```
32,489,812
First off, I'm new to the Entity Framework and am migrating an existing project from a database framework that I wrote myself so I have a fair amount of flexibility in the solution I choose. From what I've researched so far everything appears to be set up correctly. However, when my database is constructed, the table for a helper class I wrote has no columns in it (outside of its primary key). The most simplified version of the classes are included below with their relationships defined in the fluent API. **Classes** ``` public class Concept { public long ID { get; set; } [Index(IsUnique = true), MaxLength(255)] public string Name { get; set; } } public class Tag { public long ID { get; set; } public virtual Content Subject { get; set; } public virtual Concept Concept { get; set; } } public class Helper { public long ID { get; set; } public virtual Content Subject { get; set; } public virtual List<Tag> Instances { get; set; } // Helper functionality } public class Content { public long ID { get; set; } public virtual Helper Helper { get; set; } public Content() { Helper = new Helper() { Subject = this }; } } ``` **Context** ``` protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Tag>() .HasRequired(t => t.Concept); modelBuilder.Entity<Tag>() .HasRequired(t => t.Subject); modelBuilder.Entity<Helper>() .HasRequired(t => t.Subject) .WithRequiredDependent(c => c.Helper); modelBuilder.Entity<Helper>() .HasMany(t => t.Instances); modelBuilder.Entity<Content>() .HasRequired(c => c.Helper) .WithRequiredPrincipal(); base.OnModelCreating(modelBuilder); } ``` **Program.cs** ``` static void Main(string[] args) { Content content = null; using (var context = new Context()) { content = context.Content.Find(1); if (content == null) { content = new Content(); context.Content.Add(content); context.Helper.Add(content.Helper); context.SaveChanges(); } } } ``` It's also worth mentioning that when the data is saved, the Helper is assigned an ID but on loading the parent class (Content) the second time around, the Helper is not lazy loaded as I would expect from the 'virtual' keyword. I suspect that this is caused by the same issue causing the absence of data in the table. I have tried both the data annotation and fluent API approaches that EF provides but it seems that there is something fundamental that I am misunderstanding. I would like to retain this helper class as it helps organize the code far better. As I have spent a fair amount of time researching these relationships / APIs, and scouring Google / SO without found anything to solve this issue in particular any help would be greatly appreciated! Updated: Solution ================= Thanks to a question in the comments, I realized that I was expecting to see the keys of a many-to-many relationship in the tables for the entity types themselves (i.e. in the Helpers table). However, in a many-to-many relationship, the keys will always be placed in a separate table (concatenation of type names) which was not being previously created. By adding '.WithMany();' to the Helper section of the OnModelCreating function as below ``` modelBuilder.Entity<Helper>() .HasMany(t => t.Instances) .WithMany(); ``` the many-to-many relationship became properly defined and the HelperTags table generated as expected. This is due to the fact that the many-to-many relationship is one way (Helpers always refer to Tags, Tags never refer to Helpers). This is also why the 'WithMany' does not have any arguments (since no Helper properties exist in the Tag class). Fixing this simple oversight solved the problem!
2015/09/09
[ "https://Stackoverflow.com/questions/32489812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5318738/" ]
I had a similar case where I needed such a functionality. What I did was to add an event to the cell and consume it in my `UITableViewSource` which has a reference to the controller.
If you want to maintain an iOS feel, you would use the iOS Delegate pattern (see the section on [Events, Delegates and Protocols](https://developer.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events/) on the Xamarin site). Basically, you would declare a protocol (an Interface in C# parlance) to notify the observing class (in your case the UITableViewController instance) e.g. ``` public interface CartCellStepperDelegate { void cartCellValueChanged(int value); } ``` A weak reference to the delegate should be maintained in your observing class which the instance of CartCell can communicate with. It would be as simple as implementing the interface in the UITableViewController instance and acting accordingly once actioned. This is sort of analagous to a C# event (which, by the way, is another option that you could use where you define an event in the CartCell class and bind it to the touch event on the Stepper).
287
There are a lot of companies that provide domain whois but I've heard of a lot of people who had bad experiences where the domain was bought soon after the whois search and the price was increased dramatically. Where can I gain access to a domain whois where I don't have to worry about that happening? **Update:** **Apparently, the official name for this practice is called Domain Front Running and some sites go as far as to create explicit policies stating that they don't do it.** > > This is where a domain registrar or an intermediary (like a domain lookup site) mines the searches for possibly attractive domains and then either sells the data to a third-party, or goes ahead and registers the name themselves ahead of you. In one case a registrar took advantage of what's known as the "grace period" and registered every single domain users looked up through them and held on to them for 5 days before releasing them back into the pool at no cost to themselves. > > > ***Source: [domainwarning.com](http://www.domainwarning.com/)*** **And apparently, after ICANN was notified of the practice, they wrote it off as a coincidence of random 'domain tasting'.** ***Source: [See for yourself](http://www.icann.org/en/committees/security/sac022.pdf)***
2010/07/08
[ "https://webmasters.stackexchange.com/questions/287", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/120/" ]
I'm a little surprised that no one has mentioned the official [ICANN whois lookup website](https://whois.icann.org/en).
I have registered 100+ domains with both Namecheap and GoDaddy and I have never faced this types of issue. I think this happens with only small comapnies. So if you check it on big companies like NameCheap or GoDaddy, you won't face this problem.
26,768,167
I have searched extensively for a relevant answer, but none quite satisfy what I need to be doing. For our purposes I have a column with a 50 character binary string. In our database, it is actually hundreds of characters long. There is one string for each unique item ID in our database. The location of each '1' flags a specific criteria being true, and a '0' false, so the indexed location of the ones and zeros are very important. Mostly, I care about where the 1's are. I am not updating any databases, so I first decided to try and make a loop to look through each string and create a list of the 1's locations. ``` declare @binarystring varchar(50) = '10000010000110000001000000000000000000000000000001' declare @position int = 0 declare @list varchar(200) = '' while (@position <= len(@binarystring)) begin set @position = charindex('1', @binarystring, @position) set @list = @list + ', ' + convert(varchar(10),@position) set @position = charindex('1', @binarystring, @position)+1 end select right(@list, len(@list)-2) ``` This creates the following list: ``` 1, 7, 12, 13, 20, 50 ``` However, the loop will bomb if there is not a '1' at the end of the string, as I am searching through the string via occurrences of 1's rather than one character at a time. I am not sure how satisfy the break criteria when the loop would normally reach the end of the string, without there being a 1. Is there a simple solution to my loop bombing, and should I even be looping in the first place? I have tried other methods of parsing, union joining, indexing, etc, but given this very specific set of circumstances I couldn't find any combination that did quite what I needed. The above code is the best I've got so far. I don't specifically need a comma delimited list as an output, but I need to know the location of all 1's within the string. The amount of 1's vary, but the string size is always the same. This is my first time posting to stackoverflow, but I have used answers many times. I seek to give a clear question with relevant information. If there is anything I can do to help, I will try to fulfill any requests.
2014/11/05
[ "https://Stackoverflow.com/questions/26768167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4220466/" ]
You aren't loading the jquery-ui properly. You need a closing bracket.
HTML: ``` <input type="text" id="your_input" name="your_input" /> ``` JS: ``` <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script> $(function() { $( "#your_input" ).datepicker(); }); </script> ``` Optional Fast load datapicker: ``` <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script> $(function() { $('body').on('focus',"#your_input", function(){ $(this).datepicker({ dateFormat: 'dd-mm-yy' }); }); }); </script> ```
68,844,811
In my Laravel (5.7) controller, I have set pagination + 'on each side navigation' to 2 items. However, this is not working on my view. I'm getting much more items than 2, which causes my window to break out on small mobile devices. What can be the cause of this and how can I fix it? I mean, I can get it fixed with CSS, but I would like to get it fixed the proper way. My code in the controller: ``` public function index(Request $request) { $type = 'all'; if ($request->has('type')) { if ($request->type == 'all') { $materials = Material::paginate(10)->onEachSide(2); } else { $type = $request->type; $materials = Material::where('type', $type)->paginate(10)->onEachSide(2); } } else { $materials = Material::paginate(10)->onEachSide(2); } $stock = array( 'enkelzitKajaks' => Material::where('type', 'Enkelzitkajak')->count(), 'dubbelzitKajaks' => Material::where('type', 'Dubbelzitkajak')->count(), 'canadeseKanos' => Material::where('type', 'Canadese kano')->count(), 'langePeddels' => Material::where('type', 'Lange peddel')->count(), 'kortePeddels' => Material::where('type', 'Korte peddel')->count(), 'tonnetjes' => Material::where('type', 'Tonnetje')->count(), 'zwemvesten' => Material::where('type', 'Zwemvest')->count() ); return view('materials.index')->with('materials', $materials)->with('stock', $stock)->with('type', $type); } ``` My code in the view: ``` <section class="pagination"> <div class="container"> <div class="row"> <div class="col-12"> {{ $materials->links() }} </div> </div> <hr> </div> </section> ``` A screenshot of my view on small devices: [![enter image description here](https://i.stack.imgur.com/rXet3.png)](https://i.stack.imgur.com/rXet3.png)
2021/08/19
[ "https://Stackoverflow.com/questions/68844811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15117732/" ]
First of all The laravel pagination ***onEachSide(x)*** has **leading and tailing parts besides the middle section**. Leading two pages and tailing two pages. You are trying with ***onEachSide(2)*** and on the 6th page. So now we try to look at the logic in pagination. In laravel when using ***onEachSide(2)*** it will show pagination like this | leadingTwoPages | currentPage - 2 | currentPage | currentPage +2 | tailingTwoPages | | --- | --- | --- | --- | --- | | 1,2 | 4,5 | 6 | 7,8 | 22,23 | Then think about the first part of pagination it needs to show the 1st page to the 8th page without the 3rd page. Instead of page number three, it needs to be a show button with dots. Then instead of showing a button with dots for page number three, it will show the original 3rd-page number. *After the 6th page the laravel pagination onEachSide(2) will work fine*
You should use `onEachSide` this in blade. Remove the `onEachSide` from the controllers. Using `onEachSide` in controllers will be helpful when you are creating APIs. Instead use `onEachSide` in blade file. ``` <section class="pagination"> <div class="container"> <div class="row"> <div class="col-12"> {{ $materials->onEachSide(1)->links() }} </div> </div> <hr> </div> </section> ``` Use can manage the link window by changing the parameter in `onEachSide` <https://laravel.com/docs/8.x/pagination#adjusting-the-pagination-link-window>
66,801,794
I have a code in HomeController.php in the Laravel framework, but I could not access the index/homepage it redirects to the login page. what is the blunder I am committing? ``` <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { $users = User::get(); return view('home', compact('users')); } public function user($id){ $user = User::find($id); return view('user', compact('user')); } public function ajax(Request $request){ $user = User::find($request->user_id); $response = auth()->user()->toggleFollow($user); return response()->json(['success'=> $response]); } } ```
2021/03/25
[ "https://Stackoverflow.com/questions/66801794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025906/" ]
The answer is simple. In the `__construct()` method, you specified that every function under this controller must use the `auth` `middleware`. This will redirect to `login` page is the user is not logged in. There are a number of ways to work around this, the first being to remove the `__construct` entirely. However, this is not so recommended. Another would be to add an `except()` function ``` public function __construct() { $this->middleware('auth')->except('index'); } ``` This will allow the condition to apply anywhere else other than the `index` function.
Based on the code you posted, the homepage route is protected by the 'auth' middleware, which means users have to login to access the resource page (Home page), so you should first login and then it will direct you to the intended page. If you don't want the page to be protected, then you could either remove the `$this->middleware('auth')` in your constructor, or you could put the index() function separately in a different Controller file and leave it unprotected
16,149,453
If user is inactive for some specific duration, then it should autometically log out. So how I can do this using codeigniter? OR how to check whether user is active or not after login on that site?
2013/04/22
[ "https://Stackoverflow.com/questions/16149453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286294/" ]
You can save the time that your user logged-in in a `session` or a `cookie` Example: `$this->session->set_userdata('time', time());` and use a javascriptjQuery function (Exp. `$.getJSON('time.php', function (data) {alert(data.serverTime);});`) or anything else to check the current time. Then, log your user out when needed. However, next time, please place code or something else that shows your efforts.
``` <?php $minutes=3;//Set logout time in minutes if (!isset($_SESSION['time'])) { $_SESSION['time'] = time(); } else if (time() – $_SESSION['time'] > $minutes*60) { session_destroy(); header(‘location:login.php’);//redirect user to a login page or any page to which we want to redirect. } ?> ``` ... which was originally taken from ~~skillrow.com/log-out-user-if-user-is-inactive-for-certain-time-php/~~ (now 404).
26,773,830
I am doing ajax post to post the data from javascript in mvc4 but it fails with following exception ``` string exceeds the value set on the maxJsonLength property. Parameter name: input System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. ``` I have already tried setting the configurations in web config but it is not working ``` <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="2147483647"/> </webServices> </scripting> </system.web.extensions> ``` I also tried below link but nothing works: <http://forums.asp.net/t/1751116.aspx?How+to+increase+maxJsonLength+for+JSON+POST+in+MVC3> ``` var editorText = eval(htmlEditor).GetHtml(); $.ajax({type: 'POST', cache: false, contentType: 'application/json; charset=utf-8', url: "../Home/SaveExceptionLetter", data: JSON.stringify({ message: editorText }), datatype: 'json', success: function () { }); } }); [HttpPost] [ValidateInput(false)] public void SaveExceptionLetter(string message){ //processing this message } string exceeds the value set on the maxJsonLength property. Parameter name: input System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Parameter name: input at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) at System.Web.Mvc.ControllerBase.get_ValueProvider() at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) ```
2014/11/06
[ "https://Stackoverflow.com/questions/26773830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2826273/" ]
Hi @usFarswan this is exactly what I came across just half an hour ago , and the solution is <http://forums.asp.net/t/1751116.aspx?How+to+increase+maxJsonLength+for+JSON+POST+in+MVC3> And you can implement it like that, in **global.asax** add the following lines pointed by ///\*\*\*\*\*. ``` namespace MyWebApp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); XmlConfigurator.Configure(); DbHelper.getSessionFactory(); ///// ********** JsonValueProviderFactory jsonValueProviderFactory = null; foreach (var factory in ValueProviderFactories.Factories) { if (factory is JsonValueProviderFactory) { jsonValueProviderFactory = factory as JsonValueProviderFactory; } } //remove the default JsonVAlueProviderFactory if (jsonValueProviderFactory != null) ValueProviderFactories.Factories.Remove(jsonValueProviderFactory); //add the custom one ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());** /////************* } } ///******** public sealed class CustomJsonValueProviderFactory : ValueProviderFactory { private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value) { IDictionary<string, object> d = value as IDictionary<string, object>; if (d != null) { foreach (KeyValuePair<string, object> entry in d) { AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value); } return; } IList l = value as IList; if (l != null) { for (int i = 0; i < l.Count; i++) { AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]); } return; } // primitive backingStore[prefix] = value; } private static object GetDeserializedObject(ControllerContext controllerContext) { if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { // not JSON request return null; } StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream); string bodyText = reader.ReadToEnd(); if (String.IsNullOrEmpty(bodyText)) { // no JSON data return null; } JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength. This could be read in from the web.config if you prefer object jsonData = serializer.DeserializeObject(bodyText); return jsonData; } public override IValueProvider GetValueProvider(ControllerContext controllerContext) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } object jsonData = GetDeserializedObject(controllerContext); if (jsonData == null) { return null; } Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); AddToBackingStore(backingStore, String.Empty, jsonData); return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture); } private static string MakeArrayKey(string prefix, int index) { return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]"; } private static string MakePropertyKey(string prefix, string propertyName) { return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName; } } ///************* } ```
there is a another setting in web.config which you can try to increase: ``` <system.web> // the default request size is 4096 KB (4 MB) this will increase it to 100 MB <httpRuntime targetFramework="4.5" maxRequestLength="102400" /> <system.web> ```
961,079
I have gotten the code to work so that when I press the button, "Add More", it adds more combo boxes to the form with the names dayBox1, dayBox2, and so on. This is the code for that: ``` private void addMoreBtn_Click(object sender, EventArgs e) { //Keep track of how many dayBoxes we have howMany++; //Make a new instance of ComboBox ComboBox dayBox = new System.Windows.Forms.ComboBox(); //Make a new instance of Point to set the location dayBox.Location = new System.Drawing.Point(Left, Top); dayBox.Left = 13; dayBox.Top = 75 + dayLastTop; //Set the name of the box to dayBoxWhateverNumberBoxItIs dayBox.Name = "dayBox" + howMany.ToString(); //The TabIndex = the number of the box dayBox.TabIndex = howMany; //Make it visible dayBox.Visible = true; //Set the default text dayBox.Text = "Pick One"; //Copy the items of the original dayBox to the new dayBox for (int i = 0; i < dayBoxO.Items.Count; i++) { dayBox.Items.Add(dayBoxO.Items[i]); } //Add the control to the form this.Controls.Add(dayBox); //The location of the last box's top with padding dayLastTop = dayBox.Top - 49; } ``` What is the best way to print the selected member of the boxes added with the button event? The way I was printing the information I wanted to a file before was like this (from only one box): ``` public void saveToFile() { FileInfo t = new FileInfo("Workout Log.txt"); StreamWriter Tex = t.CreateText(); Tex.WriteLine("---------------Workout Buddy Log---------------"); Tex.WriteLine("------------------- " + DateTime.Now.ToShortDateString() + " ------------------"); Tex.Write(Tex.NewLine); if (dayBoxO.Text != "Pick One") { Tex.WriteLine("Day: " + dayBoxO.Text); } else { Tex.WriteLine("Day: N/A"); } } ``` I want to be able to do this for every box, each on a new line. So, it would be like: Day: (the text of box1) Day: (the text of box2) Day: (the text of box3) and so on... Thanks!
2009/06/07
[ "https://Stackoverflow.com/questions/961079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49549/" ]
I know this is an old question but since it's one of the first results when searching for this issue I figured I should post what worked for me. I had a query that took less than 10 seconds when I used SQL Server JDBC driver but more than 4 minutes when using jTDS. I tried all suggestions mentioned here and none of it made any difference. The only thing that worked is adding this to the URL ";prepareSQL=1" See [Here](http://jtds.sourceforge.net/faq.html#urlFormat) for more
Two connections instead of two Statements ========================================= I had one connection to SQL server and used it for running all queries I needed, creating a new Statement in each method that needed DB interaction. My application was traversing a master table and, for each record, fetching all related information from other tables, so the first and largest query would be running from beginning to end of the execution while iterating its result set. ``` Connection conn; conn = DriverManager.getConnection("jdbc:jtds:sqlserver://myhostname:1433/DB1", user, pasword); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select * from MASTER + " ;"); // iterating rs will cause the other queries to complete Entities read from MASTER // ... Statement st1 = conn.createStatement(); ResultSet rs1 = st1.executeQuery("select * from TABLE1 where id=" + masterId + ";"); // st1.executeQuery() makes rs to be cached // ... Statement st2 = conn.createStatement(); ResultSet rs2 = st2.executeQuery("select * from TABLE2 where id=" + masterId + ";"); // ... ``` This meant that any subsequent queries (to read single records from the other tables) would cause the first result set to be cached entirely and not before that the other queries would run at all. The solution was running all other queries in a second connection. This let the first query and its result set alone and undisturbed while the rest of the queries run swiftly in the other connection. ``` Connection conn; conn = DriverManager.getConnection("jdbc:jtds:sqlserver://myhostname:1433/DB1", user, pasword); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select * from MASTER + " ;"); // ... Connection conn2 = DriverManager.getConnection("jdbc:jtds:sqlserver://myhostname:1433/DB1", user, pasword); Statement st1 = conn2.createStatement(); ResultSet rs1 = st1.executeQuery("select * from TABLE1 where id=" + masterId + ";"); // ... Statement st2 = conn2.createStatement(); ResultSet rs2 = st2.executeQuery("select * from TABLE2 where id=" + masterId + ";"); // ... ```
67,549,532
I pass an array variable from PHP to JavaScript. My variable content in JavaScript console is: ``` [ { "function": "change", "parameter": "link", "err_msg": "It seems your input is not valid", "id": "element1" }, { "function": "change", "parameter": "check", "err_msg": "please enter a valid input", "id": "element2" } ] ``` I want to know is this possible to use this variable to fire JavaScript/jquery on change event for element1 and element2 elements? I use following codes for this but not works. ``` jQuery.each( passed_variable, function( key, element ) { jQuery( '#' + element.id + '-source' ).on( element.function, function() { switch ( element.parameter ) { case 'link' : reg_match = new RegExp('^<.* rel=("|\').*("|\') .*href=("|\').*("|\').*>$'); if ( ! reg_match.test(element.value) ) { this.setCustomValidity( validation.err_msg ); this.reportValidity(); } else { this.setCustomValidity(''); } } }); }); ```
2021/05/15
[ "https://Stackoverflow.com/questions/67549532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7278940/" ]
Ok, this was an interesting challenge and though it seemed deceptively simple, I couldn't find a simple elegant way. Here's a working approach (though hardly elegant) that seems to not suffer from the race condition of using `PrefixUntilOutput`/`Concatenate` combo. The idea is to use `combineLatest`, but one that emits as soon as the first publisher emits, with the other value being `nil` so that we don't lose the initial values. Here's a convenience operator that does that that I called `combineLatestOptional`: ``` extension Publisher { func combineLatestOptional<Other: Publisher>(_ other: Other) -> AnyPublisher<(Output?, Other.Output?), Failure> where Other.Failure == Failure { self.map { Optional.some($0) }.prepend(nil) .combineLatest( other.map { Optional.some($0) }.prepend(nil) ) .dropFirst() // drop the first (nil, nil) .eraseToAnyPublisher() } } ``` Armed with the above, the second step in the pipeline uses `Scan` to collect values into an accumulator until the other publisher emits the first value. There are 4 states of the accumulator that I'm representing this state with a `State<L, R>` type: ``` fileprivate enum State<L, R> { case initial // before any one publisher emitted case left([L]) // left emitted; right hasn't emitted case right([R]) // right emitted; left hasn't emitted case final([L], [R]) // final steady-state } ``` And the final operator `combineLatestLossless` is implemented like so: ``` extension Publisher { func combineLatestLossless<Other: Publisher>(_ other: Other) -> AnyPublisher<(Output, Other.Output), Failure> where Failure == Other.Failure { self.combineLatestOptional(other) .scan(State<Output, Other.Output>.initial, { state, tuple in switch (state, tuple.0, tuple.1) { case (.initial, let l?, nil): // left emits first value return .left([l]) // -> collect left values case (.initial, nil, let r?): // right emits first value return .right([r]) // -> collect right values case (.left(let ls), let l?, nil): // left emits another return .left(ls + [l]) // -> append to left values case (.right(let rs), nil, let r?): // right emits another return .right(rs + [r]) // -> append to right values case (.left(let ls), _, let r?): // right emits after left return .final(ls, [r]) // -> go to steady-state case (.right(let rs), let l?, _): // left emits after right return .final([l], rs) // -> go to steady-state case (.final, let l?, let r?): // final steady-state return .final([l], [r]) // -> pass the values as-is default: fatalError("shouldn't happen") } }) .flatMap { status -> AnyPublisher<(Output, Other.Output), Failure> in if case .final(let ls, let rs) = status { return ls.flatMap { l in rs.map { r in (l, r) }} .publisher .setFailureType(to: Failure.self) .eraseToAnyPublisher() } else { return Empty().eraseToAnyPublisher() } } .eraseToAnyPublisher() } } ``` The final `flatMap` creates a `Publishers.Sequence` publisher from all the accumulated values. In the final steady-state, each array would just have a single value. The usage is simple: ``` let c = pub1.combineLatestLossless(pub2) .sink { print($0) } ```
Edit ---- After stumbling on this [post](https://forums.swift.org/t/combine-what-are-those-multicast-functions-for/26677/12) I wonder if the problem in your example is not related to the `PassthroughSubject`: > > PassthroughSubject will drop values if the downstream has not made any demand for them. > > > and in fact using : ``` var subject1 = Timer.publish(every: 1, on: .main, in: .default, options: nil) .autoconnect() .measureInterval(using: RunLoop.main, options: nil) .scan(DateInterval()) { res, interval in .init(start: res.start, duration: res.duration + interval.magnitude) } .map(\.duration) .map { Int($0) } .eraseToAnyPublisher() var subject2 = PassthroughSubject<String, Never>() let bufferedSubject1 = Publishers.Concatenate(prefix: Publishers.PrefixUntilOutput(upstream: subject1, other: subject2).collect().flatMap(\.publisher), suffix: subject1) let cancel = bufferedSubject1.combineLatest(subject2) .sink(receiveCompletion: { c in print(c) }, receiveValue: { v in print(v) }) subject2.send("X") DispatchQueue.main.asyncAfter(deadline: .now() + 3) { subject2.send("Y") } ``` I get this output : ``` (1, "X") (2, "X") (3, "X") (3, "Y") (4, "Y") (5, "Y") (6, "Y") ``` And that seems to be the desired behavior. --- I don't know if it is an elegant solution but you can try to use [`Publishers.CollectByTime`](https://developer.apple.com/documentation/combine/publishers/collectbytime) : ``` import PlaygroundSupport import Combine PlaygroundPage.current.needsIndefiniteExecution = true let queue = DispatchQueue(label: "com.foo.bar") let cancellable = letters .combineLatest(indices .collect(.byTimeOrCount(queue, .seconds(1), .max)) .flatMap { indices in indices.publisher }) .sink { letter, index in print("(\(index), \(letter))") } indices.send(1) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { indices.send(2) indices.send(3) } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { letters.send("X") } DispatchQueue.main.asyncAfter(deadline: .now() + 3.3) { indices.send(4) } DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) { letters.send("Y") } DispatchQueue.main.asyncAfter(deadline: .now() + 3.7) { indices.send(5) indices.send(6) } ``` Output : ``` (X, 1) (X, 2) (X, 3) (Y, 3) (Y, 4) (Y, 5) (Y, 6) ```
59,944
I am using `emacs` under `iTerm2` on Mac. I am using mouse to scroll up and down. Please not that I haven't face with the issue when I remotely connected into a linux machine, which has exactly same emacs setup. When I scroll to bottom `OBB` character is generated and emacs is hangs. When I scroll to top section `OAA` character is generated and hangs again. Than emacs crashes/suspends itself and generated following output: ``` ^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OB^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA^[OA [1] + 5999 suspended TERM=xterm-256color emacs -nw -nw --no-site-file --debug-init ``` => Another case, when I keep scroll to bottom of the buffer and when the cursor ends up on the bottom, `emacs` halts. I try to enter character or scroll back nothing happens. In another terminal when I try to close emacs, it gets closed and the characters I already entered would show up on the terminal. My setup: ``` (setq fast-but-imprecise-scrolling 't) (setq jit-lock-defer-time 0) (setq max-lisp-eval-depth 10000) (setq echo-keystrokes 0.1 inhibit-startup-screen t initial-major-mode 'emacs-lisp-mode uniquify-buffer-name-style 'forward mouse-yank-at-point t) ``` --- ``` $ ssh -tx4C user@IP zsh -i $ echo $TERM xterm-256color $ emacs -nw file.txt ```
2020/08/03
[ "https://emacs.stackexchange.com/questions/59944", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/18414/" ]
The Elisp code below shows how it can be done. First, some notes: 1. You can use the [`display` text property](https://www.gnu.org/software/emacs/manual/html_node/elisp/Replacing-Specs.html#Replacing-Specs) to replace characters visually with other text. 2. If you want to display the bullet in red, propertize the replacement text. You can use [text properties in strings](https://www.gnu.org/software/emacs/manual/html_node/elisp/Text-Props-and-Strings.html) for that purpose. 3. Use the `OVERRIDE` flag `prepend` or `append` for the [font lock keyword](https://www.gnu.org/software/emacs/manual/html_node/elisp/Search_002dbased-Fontification.html). This is the most sensible choice if you modify an existing mode through personal configuration. It ensures that the fontification of the original mode and your own fontification is combined and none of the two overrides the other completely. If you do not add this `OVERRIDE` flag and prepend your own fontification to that one of the original mode your fontification prevents tweaks by the original mode. If you append your fontification without `OVERRIDE` it has no effect if the original mode fontifies the same stretch of text. 4. Add the keyword at the end of `font-lock-keywords` so that your fontification is not overridden by other rules (`HOW` argument of [`font-lock-add-keywords`](https://www.gnu.org/software/emacs/manual/html_node/elisp/Customizing-Keywords.html#Customizing-Keywords)). 5. Note, a regexp as matcher is not sufficient since it also gives false positives. For an example, matches in source blocks are also highlighted. That is the reason why I introduced the matcher function `org+-match-item-marker`. ```el (require 'org-element) (defun org+-match-item-marker (bound) "Match the bullet of itemizations." (and (re-search-forward "^ *\\(-\\) " bound t) (save-match-data (save-excursion (goto-char (match-end 1)) (eq (org-element-type (org-element-at-point)) 'item))))) (font-lock-add-keywords 'org-mode '((org+-match-item-marker ;; matcher (1 ;; subexpression '(face default display #("•" 0 1 (face (:foreground "red")))) ;; face append ;; override ))) t) ;; how ```
This is a complementary answer to the one posted by Tobias. I noticed that the following worked for me too: ```el (setq red-unicode-dot (propertize "•" 'font-lock-face '(:foreground "red"))) (font-lock-add-keywords 'org-mode '(("^ *\\([-]\\) " (0 (prog1 () (put-text-property (match-beginning 1) (match-end 1) 'display red-unicode-dot)))))) ```
39,087,749
Of course I know a method to do this: ```cs /// <summary>Gets the number of bits needed to represent the number.</summary> public static int Size(int bits) { var size = 0; while(bits != 0) { bits >>= 1; size++; } return size; } ``` So the Size(15) returns 4, and Size(16) returns 5. But I guess (hope) there is a quicker way. But I couldn't think of (or Google) a nice and smooth (and fast) algorithm.
2016/08/22
[ "https://Stackoverflow.com/questions/39087749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2266405/" ]
This isn't short, but it's quick (averaged over the full range of ints) ``` internal static readonly byte[] msbPos256 = new byte[] { 255, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; public static int SignificantBits(this int value) { return HighBitPosition((uint)value) + 1; } public static int HighBitPosition(this ushort value) { byte hiByte = (byte)(value >> 8); if (hiByte != 0) return 8 + msbPos256[hiByte]; return (sbyte)msbPos256[(byte)value]; } public static int HighBitPosition(this uint value) { byte hiByte = (byte)(value >> 24); if (hiByte != 0) return 24 + msbPos256[hiByte]; hiByte = (byte)(value >> 16); return (hiByte != 0) ? 16 + msbPos256[hiByte] : HighBitPosition((ushort)value); } ``` Call the SignificantBits method. Something to note is that 99.6% of all possible int values will have the most significant bit within the top 8 most significant bits (out of the 32). This requires just a right shift operation, two add operations (one of which likely get optimized by the compiler to an increment), a !=0 test, and an array reference. So, for most of the possible values, it's very quick. To cover the second 8 most significant bits takes an additional right shift, and !=0 test, and that covers 99.998% of possible int values. The casts don't cost much. You could shave off the +1 operation by incrementing the msbPos256 values by one. I was more interested in the HighBitPosition function than the SignficantBits function when I wrote it, which is why I did it the way I did (I added SignificantBits as an afterthought). IIRC, when I was testing the various tricks, this was faster than the DeBruijn technique that I had originally used for this.
If you are looking for the the highest bit set, see [Find first set](https://en.wikipedia.org/wiki/Find_first_set). One possible implementation (does not handle zero input) is: > > > ``` > table[0..31] = {0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, > 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31} > function lg_debruijn (x) > for each y in {1, 2, 4, 8, 16}: x ← x | (x >> y) > return table[(x * 0x07C4ACDD) >> 27] > > ``` > > If you want to calculate number of 1-bits (sometimes called *population count*), look at [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight). One possibility solution would be: > > > ``` > int popcount_4(uint64_t x) { > int count; > for (count=0; x; count++) > x &= x-1; > return count; > } > > ``` > > Sometimes this functionality has even language support: > > Some C compilers provide intrinsics that provide bit counting facilities. For example, GCC (since version 3.4 in April 2004) includes a builtin function `__builtin_popcount` that will use a processor instruction if available or an efficient library implementation otherwise. LLVM-GCC has included this function since version 1.5 in June, 2005. > > >
25,191,697
My Idea is to give the User a chance to store a value (in my case an `int` how broad the `JFrame` should be, so that the next time he starts my .jar, I can make it that broad from beginning on and he hasn't got to resize it again). As it is only one single value, I would not like to have to write it into a separate file etc., so is there an elegant way, sth. like a variable more "hard code" than usual? And Yes, I used the Searchbar of my browser, but I had no Idea what to search for...
2014/08/07
[ "https://Stackoverflow.com/questions/25191697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The Preferences class does this. You should not use it for more application specific values though. The size and location of the windows and such is what it is used for. ``` Preferences prefs = Preferences.userRoot(); prefs.put("AppWindowSize", "10"); prefs.get("AppWindowSize","DefaultValueHere"); ```
Can you do it? Yes. [You can put a properties file in your classpath and then use `getResourceAsStream` to load it from a package](https://stackoverflow.com/questions/333363/loading-a-properties-file-from-java-package). Should you do it? No. Consider the case where the user makes a mistake and sets their JFrame size to 10000000. They won't be able to fix that unless they unpack your JAR, change the properties file, then repackage it. It's better to use a separate file.
948,564
How do you code special cases for objects? For example, let's say I'm coding an rpg - there are N = 5 classes. There are N^2 relationships in a matrix that would determine if character A could attack (or use ability M on) character B (ignoring other factors for now). How would I code this up in OOP without putting special cases all over the place? Another way to put it is, I have something maybe ``` ClassA CharacterA; ClassB CharacterB; if ( CharacterA can do things to CharacterB ) ``` I'm not sure what goes inside that if statement, rather it be ``` if ( CharacterA.CanDo( CharacterB ) ) ``` or a metaclass ``` if ( Board.CanDo( CharacterA, CharacterB ) ) ``` when the CanDo function should depend on ClassA and ClassB, or attributes/modifiers with ClassA/ClassB?
2009/06/04
[ "https://Stackoverflow.com/questions/948564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101823/" ]
Steve Yegge has an *awesome* blog post about the Properties pattern that you could use handle this. In fact, he wrote an RPG using it! <http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html> You might say player1 is a type1 and type1s can attack type2s and player2 is a type2, so unless there is some "override" on the specific player1, player1 can attack player2. This enables very robust and extensible behavior.
I would (assuming C++) give each class a `std::string` identifier, returned by a getter method on the class's instance, and use a `std::map< std::pair<std::string, std::string>, ... >` to encode the special cases of relationship between classes, all nice and ordered in one place. I'd also access that map exclusively through a getter function so that changing the strategy for encoding some or all of the special cases is made easy as pie. E.g.: if only a few pairs of classes out of the 25 have the "invisibility" property, the map in that case might contain only the few exceptions that do have that property (for a boolean property like this a `std::set` might actually be a preferable implementation, in C+\_). Some OO languages have multi-dispatch (Common Lisp and Dylan are the two that come to mind at the moment), but for all the (vast majority) of languages that lack it, this is a good approach (in some cases you'll find that a centralized map / dict is restrictive and refactor to a Dynamic Visitor design pattern or the like, but thanks to the "getter function" such refactorings will be pretty transparent to all the rest of your code).
19,087,710
We use Hibernate Search in our web application and following are releases which we are using: ``` hibernate-search-3.4.1.Final hibernate3.6.10.jar lucene-core-3.4.0.jar ``` Previously we had `lucene-core-3.1` but upgraded a couple of months ago because of another issue. Now I am getting following error very often. I searched the net and found [this](https://stackoverflow.com/questions/18085526/lucene-hibernate-search-lock-exception) and [this](https://hibernate.atlassian.net/browse/HSEARCH-614) and a couple of others but they don't seem to be same as mine. Here is the stack trace: ``` 2013-09-29 15:10:43,624 ERROR LogErrorHandler:82 - Exception occurred java.io.FileNotFoundException: \\sql-cluster\data\indexes\mycomp.domain.Item\_1ut.cfs (The system cannot find the file specified) Primary Failure: Entity mycomp.domain.Item Id 4761556 Work Type org.hibernate.search.backend.AddLuceneWork java.io.FileNotFoundException: \\sql-cluster\data\indexes\mycomp.domain.Item\_1ut.cfs (The system cannot find the file specified) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.<init>(RandomAccessFile.java:233) at org.apache.lucene.store.MMapDirectory.openInput(MMapDirectory.java:214) at org.apache.lucene.index.CompoundFileReader.<init>(CompoundFileReader.java:64) at org.apache.lucene.index.CompoundFileReader.<init>(CompoundFileReader.java:52) at org.apache.lucene.index.IndexWriter.getFieldInfos(IndexWriter.java:1222) at org.apache.lucene.index.IndexWriter.getCurrentFieldInfos(IndexWriter.java:1242) at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:1175) at org.hibernate.search.backend.Workspace.createNewIndexWriter(Workspace.java:202) at org.hibernate.search.backend.Workspace.getIndexWriter(Workspace.java:180) at org.hibernate.search.backend.impl.lucene.PerDPQueueProcessor.run(PerDPQueueProcessor.java:103) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) 2013-09-29 15:10:43,624 ERROR PerDPQueueProcessor:118 - Unexpected error in Lucene Backend: java.lang.NullPointerException at org.hibernate.search.backend.impl.lucene.works.AddWorkDelegate.performWork(AddWorkDelegate.java:76) at org.hibernate.search.backend.impl.lucene.PerDPQueueProcessor.run(PerDPQueueProcessor.java:106) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) 2013-09-29 15:10:43,624 ERROR LogErrorHandler:82 - Exception occurred java.lang.NullPointerException Primary Failure: Entity mycomp.domain.Item Id 4761556 Work Type org.hibernate.search.backend.AddLuceneWork java.lang.NullPointerException at org.hibernate.search.backend.impl.lucene.works.AddWorkDelegate.performWork(AddWorkDelegate.java:76) at org.hibernate.search.backend.impl.lucene.PerDPQueueProcessor.run(PerDPQueueProcessor.java:106) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:722) ``` Any help is much appreciated.
2013/09/30
[ "https://Stackoverflow.com/questions/19087710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702510/" ]
Contrary to "[Dealing with line endings](https://help.github.com/articles/dealing-with-line-endings#platform-windows)", I would recommend to [*always* set `core.autocrlf` to `false`](https://stackoverflow.com/a/17628353/6309) (on Windows or any other platform): ``` git config --global core.autocrlf false ``` You don't want git to automatically changes files on a repository-wide basis without your explicit instruction. Once you have identified specific files which requires eol management, list them in a [`.gitattributes` file](http://git-scm.com/docs/gitattributes), with [core.eol directives](https://stackoverflow.com/a/3209806/6309).
Welcome to Git. Here is one doc can help you set up your git conf file to handle this. Read it and practise you will love git. [Dealing with line endings](https://help.github.com/articles/dealing-with-line-endings)
6,709,440
i know that java programs are first compiled and a bytecode is generated which is platform independent. But my question is why is this bytecode interpreted in the next stage and not compiled even though compilation is faster than interpretation in general??
2011/07/15
[ "https://Stackoverflow.com/questions/6709440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/846744/" ]
You answered your own question. Byte code is platform independent. If the compiled code was executed then it would not work on every OS. This is what C does and it is why you have to have one version for every OS. As others have suggested, the JVM does actually compile the code using [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation). It is just not saved anywhere. Here is a nice quote to sum it up > > In a bytecode-compiled system, source code is translated to an > intermediate representation known as bytecode. Bytecode is not the > machine code for any particular computer, and may be portable among > computer architectures. The bytecode may then be interpreted by, or > run on, a virtual machine. The JIT compiler reads the bytecodes in > many sections (or in full rarely) and compiles them interactively into > machine language so the program can run faster > > >
Byte code is platform independent. Once compiled into bytecode, it could run on any system. As it says on Wikipedia, > > [`Just-in-time compilation (JIT)`](http://en.wikipedia.org/wiki/Just-in-time_compilation), also known as dynamic translation, is > a method to improve the runtime performance of computer programs. > > > I recommend you to read this article. Its gives the [`basic working of JIT compiler`](http://www.javacommerce.com/displaypage.jsp?name=jit_compiler.sql&id=18268) for Java VM. > > JIT compilers alter the role of the VM a little by directly compiling > Java bytecode into native platform code, thereby relieving the VM of > its need to manually call underlying native system services. The > purpose of JIT compilers, however, isn't to allow the VM to relax. By > compiling bytecodes into native code, execution speed can be greatly > improved because the native code can be executed directly on the > underlying platform. > > > When JIT compiler is installed, instead of the VM calling the > underlying native operating system, it calls the JIT compiler. The JIT > compiler in turn generates native code that can be passed on to the > native operating system for execution. The primary benefit of this > arrangement is that the JIT compiler is completely transparent to > everything except the VM. > > >
294,294
When I click on *Reports > Status report*, the *Install profile* field says *Snrub (snrub-"1.1)* (with exactly one double quote). Where is this value defined?
2020/06/05
[ "https://drupal.stackexchange.com/questions/294294", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/44582/" ]
please add at header: ``` Content-Type : application/hal+json ```
Did you check, maybe JSON data from the frontend doesn't cover inside of `JSON.stringify(...)` and you try to send regular data which not serialized for sending? I advice to make sure you stringify data before sending: `const data = {"some":"value"} JSON.stringify(data)`
24,611,993
I have three types of objects: **T, X and Y** * X creates object of type T on heap and this object is pointed to by private member pointer of class X * Y creates object of type X on heap but needs to manipulate heap object T created by heap object X + Y can either use a private member pointer to store copy of pointer to heap object T of heap object X + or Y can use a local pointer to store copy of pointer to heap object T of heap object X To cleanup the objects, I can think of following two methods **Method 1** * Y deletes X in its destructor * X deletes T in its destructor **Method 2** * Y deletes X in its destructor * Y deletes X.T through its member pointer in the destructor * or Y deletes X.T through local pointer inside the local function where it is used Which of the above two methods is a preferred way to delete objects ?
2014/07/07
[ "https://Stackoverflow.com/questions/24611993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238038/" ]
Method 1 sounds preferable. If type X allocates a type T member, the deletion of that T should absolutely happen in the destructor of type X. Otherwise, using Method 2, if you decide down the line to create a new type that has a member of type X, you will have to remember to delete the type T in the new constructor. This could lead to memory leaks and code that is difficult to maintain. Also, If Y needs to manipulate T, it should do so through member functions of type X since T is a private member of X. That way, Type Y does not need its own pointer to the type T object.
Every thing must work on own task. In your case, Y call X destructor and X destroy its own resources.
965,623
I am creating a website that has an intro splash page that waits for 5 seconds before automatically sending the playhead to frame 17 if nobody has clicked the enter button doing the same thing. My code for this is here: function wait() { stop(); var myInterval = setInterval(function () { \_level0.menu\_number2 = 0; gotoAndStop(17); clearInterval(myInterval); }, 5\*1000); // stop for 5 seconds } wait(); This all works fine but if I haven't waited and am in the site before 5 seconds is up I suddenly get taken back to frame 17 unintentionally after 5 seconds. Now I know I need something in my code structure to check to see if the conditions have changed during these five seconds i.e the play head has moved beyond frame 15 and if so not to do anything but I am not sure what this something is. please help.
2009/06/08
[ "https://Stackoverflow.com/questions/965623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this code: it uses something called a closure (look it up if you're interested) ``` function wait(){ stop(); var myInterval = setInterval(function(){ _level0.menu_number2 = 0; gotoAndStop(17); clearInterval(myInterval); }, 5*1000); // stop for 5 seconds return function(){ clearInterval(myInterval); }; } var abortFunction = wait(); // Calls wait(), interval starts ticking abortFunction(); // Aborts the interval ``` You could also stick a global variable somewhere and check for it, but that just pollutes the global namespace.
You could always just clearInterval(myInterval) if they click the skip button. Or wrap it in a function unnecessarily: function stopwait(){ clearInterval(myInterval); }; To check the frame numbers you could use: if(\_root.\_currentFrame < 17)
7,122,544
Is there a better way to do this? ``` value = 10 train = [] storage = 12 another_var = 'apple' def first_function(value, train, storage, another_var) second_function(train, storage) third_function(train, storage, another_var) forth_function(value, another_var) end def third_function(train, storage, another_var) puts 'x' end def second_function(train, storage) puts 'x' end def forth_function(value, another_var) puts 'x' end ``` Is this the proper way to do this? Taking the values along for the ride? I'm working my way through LRTHW and I'm trying to build a game. The problem I am running into is that I have a for loop that represents turns and that acts as the game driver. Inside of that for loop it calls functions that then call more functions. Unless I load all the variables into the first function and then pass them down the chain it breaks. It's sort of neat that it blocks you from accessing variables outside of the very narrow scope, but is there a way I can override this?
2011/08/19
[ "https://Stackoverflow.com/questions/7122544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417449/" ]
``` const date = new Date; let hours = date.getHours(); let status = (hours < 12)? "Morning" : ((hours <= 18 && hours >= 12 ) ? "Afternoon" : "Night"); console.log(status); ```
``` <SCRIPT LANGUAGE="JavaScript"> currentTime=new Date(); //getHour() function will retrieve the hour from current time if(currentTime.getHours()<12) document.write("<b>Good Morning!! </b>"); else if(currentTime.getHours()<17) document.write("<b>Good Afternoon!! </b>"); else document.write("<b>Good Evening!! </b>"); </SCRIPT> ```
4,682,180
Some PHP code I look at is littered with "<?php" and "?>" tags depending on whether it's outputting HTML or not. Is there any performance benefit to this rather than using echo to write the HTML? It makes the code extremely hard to read when the code's constantly switching between code and HTML via the "<?php" tag. Note that I'm not just talking about the occasional switchover. The code I'm currently looking at (the mantis-bt source code) is giving me a headache with the number of times it's switching. Very very hard to read. I wonder if there's a reason for them doing it like this?
2011/01/13
[ "https://Stackoverflow.com/questions/4682180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227086/" ]
No reason whatsoever apart from its beginners scripting, there just trying to get the results to the page without any architectural thinking or planning into the system into the long run. What you should be doing is splitting your design up away from your logical php code, and the design compilation should be done at the end of the scripts runtime. if you redesign the application I would certainly advise you to start with a framework because the framework will force bad habits away by its design. Start with codeigniter and create a simple blog, understand how to connect/insert/select/update with the database, learn how to handle sessions, learn the Controllers and the principles of creating one. After you have had a decent play about with it start looking at the poorly coded applicatioon from a distance not looking at the code or the design but yet what exactly is it doing, is it fetching results from the database, does it have a user system etc etc. then start implementing the base layer of the application such as the above, once you have the database designed you can then start building the models to fetch from the database at the point within your application, start creating the basic view files taking **samples** from the pooorly coded application and recoding them within the new application, keeping in mind the structure and cleanliness of the coding. Hope this helps you start migrating because I certainly do not advise you continue to work with an application such as that. --- @mitch Event thought you second piece of code is cleaner its still combining your view with the rest of your application where it should be like so: ``` <html> <?php $this->load("segments/head"); ?> <body> <?php echo $this->wrap("span",$this->link("Some Linke",$this->var("homepage"))) ?> </body> </html> ``` a dedicated set of methods for the view to prevent it interacting with the main logic, this would be wrapped within an object to prevent the scope and only the object should be able to access the main logic.
I don't have statistical data to back this up, but it's my understanding that it's more efficient to "turn off" php to output HTML rather than to use echo""; The reason being that when you run your html through echo tags, you're having PHP parse it out to display, while just putting it in the doc itself will let the browser display it WITHOUT having to have PHP parse it. When I did ColdFusion development, I remember hearing the same case made for tags.
13,074,662
Hi I am trying to create a custom button. The button has basically two modes, pressed and not pressed. I have created an xml file named addtransaction which holds the two button images, the code is as follows ``` <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/add_transaction_after" android:state_pressed="true"></item> <item android:drawable="@drawable/add_transaction_before" android:state_focused="false"></item> </selector> ``` The problem I am facing is that, when the button corresponding to which the xml file is created is assigned the background. The following message appears **Failed to parse file/Users/Rudi/Desktop/ABC/res/drawable/addtransaction.xml** I am able to provide customisation to other buttons, but only this xml file is showing errors. Can some one tell me what I am doing wrong? And as an edit, here is the code for the xml file which holds my buttons ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" android:layout_gravity="center" android:orientation="horizontal" android:weightSum="10" > <LinearLayout android:id="@+id/mainLayout" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center" android:layout_weight="6" android:background="@drawable/background" android:gravity="center" android:orientation="vertical" > <ImageButton android:id="@+id/addAccount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/account" android:gravity="center" /> <ImageButton android:id="@+id/addTransaction" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/addtransaction" android:gravity="center" /> <ImageButton android:id="@+id/viewAccount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/viewaccount" android:gravity="center" /> <ImageButton android:id="@+id/recentTransaction" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/viewtransaction" android:gravity="center" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="4" > </LinearLayout> </LinearLayout> ``` here are the errors which log cat displays. ``` 10-26 20:26:02.836: E/ActivityThread(4454): **Failed to inflate 10-26 20:26:02.836: E/ActivityThread(4454): android.view.InflateException: Binary XML file line #28: Error inflating class <unknown>** 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.createView(LayoutInflater.java:613) 10-26 20:26:02.836: E/ActivityThread(4454): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 10-26 20:26:02.836: E/ActivityThread(4454): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.Activity.setContentView(Activity.java:1867) 10-26 20:26:02.836: E/ActivityThread(4454): at com.code.accountmanager.AccountManagerActivity.onCreate(AccountManagerActivity.java:41) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.Activity.performCreate(Activity.java:5008) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2141) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2212) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.ActivityThread.access$600(ActivityThread.java:144) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 10-26 20:26:02.836: E/ActivityThread(4454): at android.os.Handler.dispatchMessage(Handler.java:99) 10-26 20:26:02.836: E/ActivityThread(4454): at android.os.Looper.loop(Looper.java:137) 10-26 20:26:02.836: E/ActivityThread(4454): at android.app.ActivityThread.main(ActivityThread.java:4965) 10-26 20:26:02.836: E/ActivityThread(4454): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 20:26:02.836: E/ActivityThread(4454): at java.lang.reflect.Method.invoke(Method.java:511) 10-26 20:26:02.836: E/ActivityThread(4454): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 10-26 20:26:02.836: E/ActivityThread(4454): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558) 10-26 20:26:02.836: E/ActivityThread(4454): at dalvik.system.NativeStart.main(Native Method) 10-26 20:26:02.836: E/ActivityThread(4454): Caused by: java.lang.reflect.InvocationTargetException 10-26 20:26:02.836: E/ActivityThread(4454): at java.lang.reflect.Constructor.constructNative(Native Method) 10-26 20:26:02.836: E/ActivityThread(4454): at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.LayoutInflater.createView(LayoutInflater.java:587) 10-26 20:26:02.836: E/ActivityThread(4454): ... 25 more 10-26 20:26:02.836: E/ActivityThread(4454): **Caused by: android.content.res.Resources$NotFoundException: File res/drawable/transaction.xml from drawable resource ID #0x7f02000f** 10-26 20:26:02.836: E/ActivityThread(4454): at android.content.res.Resources.loadDrawable(Resources.java:1947) 10-26 20:26:02.836: E/ActivityThread(4454): at android.content.res.TypedArray.getDrawable(TypedArray.java:601) 10-26 20:26:02.836: E/ActivityThread(4454): at android.view.View.<init>(View.java:3336) 10-26 20:26:02.836: E/ActivityThread(4454): at android.widget.ImageView.<init>(ImageView.java:114) 10-26 20:26:02.836: E/ActivityThread(4454): at android.widget.ImageButton.<init>(ImageButton.java:87) 10-26 20:26:02.836: E/ActivityThread(4454): at android.widget.ImageButton.<init>(ImageButton.java:83) 10-26 20:26:02.836: E/ActivityThread(4454): ... 28 more 10-26 20:26:02.836: E/ActivityThread(4454): **Caused by: java.lang.NullPointerException 10-26 20:26:02.836: E/ActivityThread(4454): at android.graphics.drawable.DrawableContainer$DrawableContainerState.addChild(DrawableContainer.java:524)** 10-26 20:26:02.836: E/ActivityThread(4454): at android.graphics.drawable.StateListDrawable$StateListState.addStateSet(StateListDrawable.java:278) 10-26 20:26:02.836: E/ActivityThread(4454): at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:186) 10-26 20:26:02.836: E/ActivityThread(4454): at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881) 10-26 20:26:02.836: E/ActivityThread(4454): at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818) 10-26 20:26:02.836: E/ActivityThread(4454): at android.content.res.Resources.loadDrawable(Resources.java:1944) 10-26 20:26:02.836: E/ActivityThread(4454): ... 33 more ```
2012/10/25
[ "https://Stackoverflow.com/questions/13074662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753882/" ]
Try adding: ``` <item android:drawable="@drawable/some_drawable" /> ``` If this doesn't help, try these steps: 1. Remove the library declaration of the project. 2. Open the layout causing the error (the one which using the selector) in graphical layout. 3. Clean the project (Project -> Clean) 4. Close and reopen eclipse. (the layout should be ok now) 5. You can set the project as library again. [Here's original answer.](https://stackoverflow.com/a/8485552/1581147)
You say your drawable xml is named `addtransaction.xml` - in your layout file you reference it as `@drawable/trans`- So change that line to `android:background="@drawable/addtransaction"` and you should be done.
64,869,036
So i have the following JSON object: ``` var myObj = { Name: "Paul", Address: "27 Light Avenue" } ``` and I want to convert its keys to lowercase such that i would get: ``` var newObj = { name: "Paul", address: "27 Light Avenue" } ``` I tried the following: ``` var newObj = mapLower(myObj, function(field) { return field.toLowerCase(); }) function mapLower(obj, mapFunc) { return Object.keys(obj).reduce(function(result,key) { result[key] = mapFunc(obj[key]) return result; }, {}) } ``` But I'm getting an error saying "Uncaught TypeError: field.toLowerCase is not a function".
2020/11/17
[ "https://Stackoverflow.com/questions/64869036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7661005/" ]
```js var myObj = { Name: "Paul", Address: "27 Light Avenue" } Object.keys(myObj).map(key => { if(key.toLowerCase() != key){ myObj[key.toLowerCase()] = myObj[key]; delete myObj[key]; } }); console.log(myObj); ```
I can't reproduce your error, but if you want to lower the key than you should do: ```js var myObj = { Name: "Paul", Address: "27 Light Avenue" } function mapLower(obj, mapFunc) { return Object.keys(obj).reduce(function(result, key) { result[mapFunc(key)] = obj[key] return result; }, {}) } var newObj = mapLower(myObj, function(field) { return field.toLowerCase(); }) console.log(newObj) ``` will result with `{ name: 'Paul', address: '27 Light Avenue' }`
10,691,781
I have developed an app which shows the time in a full screeen. The hours minutes and seconds are displayed in the middle of the screen. So my objective is, when I long click any of the textviews be able to scrool it through all the screen, and place it where I want... I tried to find a proper code to apply to my app, and I found a code which makes text to image an then move that image. But the problem is, texts are updating each a second, so I think creating images each second is not a good idea... Anyone knows a method to be able to move textviews through all the screen??? This is one of my textviews ``` private TextView txtHour; txtHour = (TextView)findViewById(R.id.TxtHour); txtHour.setOnLongClickListener(new OnLongClickListener{ .... ``` I dont know what to add to this.... :( Please HELP! EDIT: According to first answer, should my code look like this? ``` txtHour.setOnLongClickListener(new OnLongClickListener() { public void onLongClick(View v){ public void drag(MotionEvent event, View v) { RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) v.getLayoutParams(); switch(event.getAction()) { case MotionEvent.ACTION_MOVE: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_UP: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_DOWN: { v.setLayoutParams(params); break; } } }}); ``` EDIT 2: finnaly this is result code, is this ok? ``` package com.iamaner.T2Speech; //imports public class MAINActivity extends Activity{ private TextView txtHour; private TextView txtMinutes; private TextView txtSeconds; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtHour = (TextView)findViewById(R.id.TxtHour); txtMinutes = (TextView)findViewById(R.id.TxtMinute); txtSeconds = (TextView)findViewById(R.id.TxtSeconds); txtHour.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub drag(event, v); return false; }}); } public void drag(MotionEvent event, View v) { FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) v.getLayoutParams(); switch(event.getAction()) { case MotionEvent.ACTION_MOVE: {params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break;} case MotionEvent.ACTION_UP: {params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break;} case MotionEvent.ACTION_DOWN: {v.setLayoutParams(params); break;} }} } ``` And this framelayout ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/your_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/TxtHour" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15mm" android:textColor="#000000"/> <TextView android:id="@+id/TxtPoints1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/separator" android:textSize="15mm" android:textColor="#000000" android:layout_gravity="center" android:gravity="center"/> <TextView android:id="@+id/TxtMinute" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15mm" android:textColor="#000000" android:layout_gravity="center" android:gravity="center" /> <TextView android:id="@+id/TxtPoints2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/separator" android:textSize="15mm" android:textColor="#000000" android:layout_gravity="center" android:gravity="center"/> <TextView android:id="@+id/TxtSeconds" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15mm" android:textColor="#000000" android:layout_gravity="bottom|right" /> </FrameLayout> ```
2012/05/21
[ "https://Stackoverflow.com/questions/10691781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354096/" ]
Add this to your onCreate: Better use FrameLayout itself. ``` txtHour.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub drag(event, v); return false; } }); ``` And this to your Activity Class ouutside any methods. ``` public void drag(MotionEvent event, View v) { RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) v.getLayoutParams(); switch(event.getAction()) { case MotionEvent.ACTION_MOVE: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_UP: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_DOWN: { v.setLayoutParams(params); break; } } ```
``` public void drag(MotionEvent event, View v) { FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) v.getLayoutParams(); switch(event.getAction()) { case MotionEvent.ACTION_MOVE: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_UP: { params.topMargin = (int)event.getRawY() - (v.getHeight()); params.leftMargin = (int)event.getRawX() - (v.getWidth()/2); v.setLayoutParams(params); break; } case MotionEvent.ACTION_DOWN: { v.setLayoutParams(params); break; } } } ``` Copy this method to ur class and call it inside your textview's ontouch(). Here i assume u use Framelayout. If not change the layout parameters accordingly.
16,246,920
I'm not sure how to create a ConstantInt in LLVM- I know the number I would like to create, but I'm unsure how I can make a ConstantInt representing that number; I can't seem to find the constructor I need in the documentation. I'm thinking it has to be along the lines of ``` ConstantInt consVal = new ConstantInt(something here). ``` I know I want it to be an int type, and I know my value... I just want to create a number!
2013/04/27
[ "https://Stackoverflow.com/questions/16246920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077708/" ]
To make an a 32 bit integer: ``` llvm::ConstantInt::get(context, llvm::APInt(/*nbits*/32, value, /*bool*/is_signed)); ```
To create a `32-bit` integer constant: ``` llvm::Type *i32_type = llvm::IntegerType::getInt32Ty(llvm_context); llvm::Constant *i32_val = llvm::ConstantInt::get(i32_type, -1/*value*/, true); ```
17,251,177
Hi guys how do you produce a gridview where first row contains text and second row contains a combobox? i tried the code below but it renders the combobox control into a simple text saying the total item of the combobox. ``` // create columns DataColumn column1 = new DataColumn(); column1.Caption = "Attribute"; column1.ColumnName = "Attribute"; column1.DataType = typeof(string); DataColumn column2 = new DataColumn(); column2.Caption = "Value"; column2.ColumnName = "Value"; column2.DataType = typeof(object); DataTable dt = new DataTable(); dt.Columns.Add(column1); dt.Columns.Add(column2); // populate field DataRow row1 = dt.NewRow(); row1.ItemArray = new object[] { "Id", "1" }; DataRow row2 = dt.NewRow(); row2.ItemArray = new object[] { "Name", "Vincent" }; ComboBox cbox = new ComboBox(); cbox.DropDownStyle = ComboBoxStyle.DropDownList; cbox.Items.AddRange(new object[]{1,2,3,4,5}); DataRow row3 = dt.NewRow(); row3.ItemArray = new object[] { "Num of Siblings", cbox}; DataRow row4 =dt.NewRow(); row4.ItemArray = new object[] { "Age", "21" }; dt.Rows.Add(row1); dt.Rows.Add(row2); dt.Rows.Add(row3); dt.Rows.Add(row4); // populate to datagridview dataGridView1.DataSource = dt; dataGridView1.Refresh(); ``` are there any other way? i can also separate the combobox from the datagridview control like when the cell (supposed to be the combobox) is clicked, it will popup a dialogbox with combobox in it (2nd form) but this will make the user fill uncombfortable. the user require me to have this kind of functionality and it should be in datagridview (fields got it from xml (dynamic fields)). the content of dropdown is just a sample, it will be given different values like when entering gender it will have male and female items instead. Thanks in advance.
2013/06/22
[ "https://Stackoverflow.com/questions/17251177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2381378/" ]
* To pass the callback, use just `getPos` instead of calling the function right away. * Use proper syntax to declare properties in `PositionObj`. ``` PositionObj = { lat: null, lon: null, } ```
The callback should tell you that the request to get position information is asynchronous. This means that `getInfo()` does NOT set the values instantly, and therefore the following line cannot access the "new" values. Anything that relies on the result of an asynchronous function MUST be within the callback itself.
41,208,105
I know that MSVC compiler in x64 mode does not support inline assembly snippets of code, and in order to use assembly code you have to define your function in some external my\_asm\_funcs.asm file like that: ``` my_asm_func PROC mov rax, rcx ret my_asm_func ENDP ``` And then in your .c or .h file you define a header for the function like that: ``` int my_asm_func(int x); ``` Although that solution answers many concerns, but I am still interested in making that assembly code function to be inline, in other words - after compilation I don't want any "calls" to **my\_asm\_func**, I just want this piece of assembly to be glued into my final compiled code. I tried declaring the function with *inline* and *\_\_forceinline* keywords, but nothing seems to be helping. Is there still any way to do what I want?
2016/12/18
[ "https://Stackoverflow.com/questions/41208105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483597/" ]
**No, there is no way to do what you want.** Microsoft's compiler doesn't support inline assembly for x86-64 targets, as you said. This forces you to define your assembly functions in an external code module (\*.asm), assemble them with MASM, and link the result together with your separately-compiled C/C++ code. The required separation of steps means that the C/C++ compiler cannot inline your assembly functions because they are not visible to it at the time of compilation. Even with link-time code generation (LTCG) enabled, your assembly module(s) will not get inlined because the linker simply doesn't support this. There is absolutely no way to get assembly functions written in a separate module inlined directly into C or C++ code. There is no way that the `inline` or `__forceinline` keywords could do anything. In fact, there's no way that you could use them without a compiler error (or at least a warning). These annotations have to go on the function's *definition* (which, for an inline function, is the same as its declaration), but you can't put it on the function's definition, since that's defined in a separate \*.asm file. These aren't MASM keywords, so trying to add them to the definition would necessarily result in an error. And putting them on the forward declaration of the assembly function in the C header is going to be similarly unsuccessful, since there's no code there to inline—just a prototype. **This is why Microsoft recommends using *intrinsics*.** You can use these directly in your C or C++ code, and the compiler will emit the corresponding assembly code automatically. Not only does this accomplish the desired inlining, but intrinsics even allow the optimizer to function, further improving the results. No, intrinsics do not lead to perfect code, and there aren't intrinsics for everything, but it's the best you can do with Microsoft's compiler. Your only other alternative is to sit down and play with various permutations of C/C++ code until you get the compiler to generate the desired object code. This can be very powerful in cases where intrinsics are not available for the instructions that you wish to be generated, but it does take a lot of time spent fidgeting, and you'll have to revisit it to make sure it continues to do what you want when you upgrade compiler versions.
Since the title mentions Visual Studio and not MSVC, I recommend installing Clang via the Visual Studio Installer. It can be used just like MSVC without needing to configure custom build tasks or anything and it supports inline assembly with Intel syntax and variables as operands. Just select "LLVM (clang-cl)" in `Platform Toolset` from the `General` section of the property pages in your project and you're good to go.
71,718,167
I am getting the error > > ImportError: cannot import name 'escape' from 'jinja2' > > > When trying to run code using the following *requirements.txt*: ``` chart_studio==1.1.0 dash==2.1.0 dash_bootstrap_components==1.0.3 dash_core_components==2.0.0 dash_html_components==2.0.0 dash_renderer==1.9.1 dash_table==5.0.0 Flask==1.1.2 matplotlib==3.4.3 numpy==1.20.3 pandas==1.3.4 plotly==5.5.0 PyYAML==6.0 scikit_learn==1.0.2 scipy==1.7.1 seaborn==0.11.2 statsmodels==0.12.2 urllib3==1.26.7 ``` Tried ```sh pip install jinja2 ``` But the requirement is already satisfied. Running this code on a windows system.
2022/04/02
[ "https://Stackoverflow.com/questions/71718167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18391313/" ]
Jinja is a dependency of Flask and Flask V1.X.X uses the `escape` module from Jinja, however recently support for the `escape` module was [dropped in newer versions of Jinja](https://jinja.palletsprojects.com/en/3.1.x/changes/#version-3-1-0). To fix this issue, simply update to the newer version of Flask V2.X.X in your *requirements.txt* where Flask no longer uses the `escape` module from Jinja. ``` Flask==2.1.0 ``` Also, do note that Flask V1.X.X is no longer supported by the team. If you want to continue to use this older version, [this Github issue may help.](https://github.com/pallets/flask/issues/4494)
> > ImportError: cannot import name 'escape' from 'jinja2' > > > This happened to me using Voila with jupyter notebook and solved using method below: 1. going to this directory `C:\Users\admin\anaconda3\Lib\site-packages\nbconvert\filters\ansi.py` 2. adding this line to the first of file `from markupsafe import escape` 3. Also change this line of code `text = jinja2.utils.escape(text)` to `text = escape(text)`
43,179,497
In Selenium-java-3.0.1, I can use WebDriverWait.until for explicit waits: ``` new WebDriverWait(myChromeDriver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); ``` Above code was running well in Selenium-java-3.0.1, until we upgraded to Selenium-java-3.2 where class WebDriverWait disappear from client-combined-3.3.0-nodeps.jar all together. What is the corresponding method call in Selenium 3.2/3.3? Thanks in advance. Stack trace is as below: ``` java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object; at au.com.testpro.rft2selenium.objects.TestObject.waitForLoad(Unknown Source) at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source) at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source) at test.ScriptSuperClass_JZ.findTestObject(ScriptSuperClass_JZ.java:65) at test.refData_Verify.execute(refData_Verify.java:102) at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.execute(Unknown Source) at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.executeCsv(Unknown Source) at test.refData_Verify.test(refData_Verify.java:486) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) ```
2017/04/03
[ "https://Stackoverflow.com/questions/43179497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3395053/" ]
You probably have old files and dublicate files that are conflicting. Change version package guava. Upgrade to guava-21.0.jar and this problem resoved. <https://github.com/SeleniumHQ/selenium/issues/3880> For me removing old selenium.jar files and pointing to latest folder did the job.
If you are using pom.xml and getting the same error again.Just go to C/user/yoursystemuser/.m2/repo/com/google/guava/guavaVersions. Delete all the previous versions of guava and keep latest. Below is the link to the dependency for guava.You might have to check your selenium version as well. <https://mvnrepository.com/artifact/com.google.guava/guava/23.0>
22,563,248
I need your help, there is an Fatal Error in my code. I don't know how to solve this problem... please help me out :) my code ``` public class MainActivity extends Activity { // button to show progress dialog Button btnShowProgress; // Progress Dialog private ProgressDialog pDialog; ImageView my_image; // Progress dialog type (0 - for Horizontal progress bar) public static final int progress_bar_type = 0; // File url to download private static String file_url = "https://example.pdf"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // show progress bar button btnShowProgress = (Button) findViewById(R.id.btnProgressBar); // Image view to show image after downloading my_image = (ImageView) findViewById(R.id.my_image); /** * Show Progress bar click event * */ btnShowProgress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // starting new Async Task new DownloadFileFromURL().execute(file_url); } }); } /** * Showing Dialog * */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case progress_bar_type: // we set this to 0 pDialog = new ProgressDialog(this); pDialog.setMessage("Downloading file. Please wait..."); pDialog.setIndeterminate(false); pDialog.setMax(100); pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(true); pDialog.show(); return pDialog; default: return null; } } /** * Background Async Task to download file * */ class DownloadFileFromURL extends AsyncTask<String, String, String> { private SSLContext context; /** * Before starting background thread * Show Progress Bar Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); showDialog(progress_bar_type); } /** * Downloading file in background thread * */ @Override protected String doInBackground(String... f_url) { int count; try { ``` This line is the error in: URL url = new URL(f\_url[0]); ``` HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // Load the truststore that includes self-signed cert as a "trusted" entry. KeyStore truststore; truststore = KeyStore.getInstance("BKS"); InputStream in = getActivity().getResources().openRawResource(R.raw.mykeystore); truststore.load(in, "mysecret".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); // Create custom SSL context that incorporates that truststore SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.connect(); // this will be useful so that you can show a tipical 0-100% progress bar int lenghtOfFile = connection.getContentLength(); // download the file InputStream input = new BufferedInputStream(connection.getInputStream(), 8192); // Output stream OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called publishProgress(""+(int)((total*100)/lenghtOfFile)); // writing data to file output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } private ContextWrapper getActivity() { // TODO Auto-generated method stub return null; } /** * Updating progress bar * */ protected void onProgressUpdate(String... progress) { // setting progress percentage pDialog.setProgress(Integer.parseInt(progress[0])); } /** * After completing background task * Dismiss the progress dialog * **/ @Override protected void onPostExecute(String file_url) { // dismiss the dialog after the file was downloaded dismissDialog(progress_bar_type); // Displaying downloaded image into image view // Reading image path from sdcard String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf"; // setting downloaded into image view my_image.setImageDrawable(Drawable.createFromPath(imagePath)); } } } ``` and this is my Logcat : ``` 03-21 16:36:26.747: E/AndroidRuntime(5751): FATAL EXCEPTION: AsyncTask #1 03-21 16:36:26.747: E/AndroidRuntime(5751): Process: com.example.test2, PID: 5751 03-21 16:36:26.747: E/AndroidRuntime(5751): java.lang.RuntimeException: An error occured while executing doInBackground() 03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$3.done(AsyncTask.java:300) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:242) 03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.lang.Thread.run(Thread.java:841) 03-21 16:36:26.747: E/AndroidRuntime(5751): Caused by: java.lang.NullPointerException: println needs a message 03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.println_native(Native Method) 03-21 16:36:26.747: E/AndroidRuntime(5751): at android.util.Log.e(Log.java:232) 03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:194) 03-21 16:36:26.747: E/AndroidRuntime(5751): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1) 03-21 16:36:26.747: E/AndroidRuntime(5751): at android.os.AsyncTask$2.call(AsyncTask.java:288) 03-21 16:36:26.747: E/AndroidRuntime(5751): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 03-21 16:36:26.747: E/AndroidRuntime(5751): ... 4 more ``` Stacktrace output `03-21 18:39:45.957: W/System.err(2061): java.lang.NullPointerException 03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:147) 03-21 18:39:45.967: W/System.err(2061): at com.example.test1.MainActivity$DownloadFileFromURL.doInBackground(MainActivity.java:1) 03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$2.call(AsyncTask.java:288) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 03-21 18:39:45.967: W/System.err(2061): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 03-21 18:39:45.967: W/System.err(2061): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 03-21 18:39:45.967: W/System.err(2061): at java.lang.Thread.run(Thread.java:841)`
2014/03/21
[ "https://Stackoverflow.com/questions/22563248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434011/" ]
You obviously have no need for the selected element, therefore i suggest instead creating your plugin on `$` directly rather than `$.fn` so that you don't waste time selecting elements that you'll never use. Pass in the context and selector through the options object parameter as an object. ``` $.myPlugin = function (options) { $(options.context).on("click", options.selector, function(){ alert("Hello World!"); }); } $.myPlugin({ context: "#container", selector: ".targetel" }); ``` An alternative would be: ``` $.fn.myPlugin = function (selector) { return this.on("click", selector, function(){ alert("Hello World!"); }); } $("#container").myPlugin(".targetel"); ```
Try this (edit) ``` (function($){ $.fn.myPlugin = function(options) { settings = { container : null }; var options = $.extend({}, settings, options); // Help!! I need another selector here! return $(options.container).on("click", function(){ alert('success!'); }); }; })(jQuery); $('html').myPlugin({container:"body"}) ``` jsfiddle <http://jsfiddle.net/guest271314/vpu33/>
54,902,621
I have a basic question. It is possible to send two parameter form POST method in Angular and Java Spring. One parameter is JSON object second is an image. I have a simple example in Angular to explain what I want: ``` addHero(file: File,category: CategoryModel): Observable<any> { const formdata: FormData = new FormData(); formdata.append('file', file); return this.http.post<File>(this.cateogryUrl, {formdata,category} ) .pipe( // catchError(this.handleError('addHero', file)) ); ``` }
2019/02/27
[ "https://Stackoverflow.com/questions/54902621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11056703/" ]
You can always convert it to BASE64. Then it's a simple string which you can simply pass it within the JSON (or a different one). EDIT This is what i do in my case any time a user upload a file. Isimply transform the file chosen to a BASE64 string. There are some really nice resources out there about this. ``` onFileChanged(event) { const file = event.target.files[0]; if (file.type.split('/')[0] !== 'image') { this.validFile = false; } this.imageUploadModel.ImageType = file.type.split('/')[1]; const myReader: FileReader = new FileReader(); myReader.onloadend = (e) => { this.imageUploadModel.Base64String = myReader.result.toString(); }; myReader.readAsDataURL(file); } ``` This is my model ``` export class ImageUploadModel { Title: string; Description: string; ImageType: string; Base64String: string; } ``` And i stringify it so i can send it on the body of the request: ``` const body = JSON.stringify(this.imageUploadModel); ```
It depends on your backend. If it takes image as a multipartfile, you can't send json data with it. But you can append other values which is desired to the form data. If it takes image as a base64 file, you can use json object to send data.
56,154,957
I just did a fresh install of Windows 10 Pro version 1903 build 18362.116 and Visual Studio Code. Now the integrated terminal only launches externally. Pressing `Ctrl` + `~` results in this. [![vscode non-integrated terminal](https://i.stack.imgur.com/ia6WX.png)](https://i.stack.imgur.com/ia6WX.png) What am I missing? How do I get it to open integrated again? EDIT ==== After working with VSCode team it is a verified bug. [See the Github issue here](https://github.com/microsoft/vscode/issues/73790). I posted the workaround as an answer here.
2019/05/15
[ "https://Stackoverflow.com/questions/56154957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25197/" ]
OK, worked through this one [in VSCode repo issues](https://github.com/microsoft/vscode/issues/73790). For now, until it's fixed, turn off ConPTY integration in the User Settings. [![vscode conpty setting](https://i.stack.imgur.com/25xrV.png)](https://i.stack.imgur.com/25xrV.png)
The issue now says use legacy console. To change the setting open a cmd prompt. Right click the title to bring up properties. ![cmd properties](https://i.stack.imgur.com/EDTRl.png) Then Uncheck 'Use legacy console' ![Use legacy console](https://i.stack.imgur.com/pu3Zw.png)
47,880,571
I am trying to calculate in appended rows values. But, calculation scripts not working. Is there any confliction between jquery-slim and jquery? I am using bootstrap 4 and laravel framework for this project. I tried various jquery scripts for this calculation. But, did not work any. Would someone help me to complete the calcuation please. ```js var item_row = '{{ $item_row }}'; function addItem() { html = '<tr id="item-row-' + item_row + '">'; html += '<td class="text-center" style="vertical-align: middle;">'; html += '<button type="button" onclick="$(\'#item-row-' + item_row + '\').remove()" title="Delete" class="btn btn-xs btn-danger"><i class="fa fa-trash"></i></button>'; html += '</td>'; html += '<td>'; html += '<select class="form-control select2" name="item[' + item_row + '][item_id]" id="item-item_id-' + item_row + '">'; html += '<option selected="selected" value="">Select</option>'; html += '<option value="item1">item1</option>'; html += '<option value="item2">item2</option>'; html += '<option value="item3">item3</option>'; html += '<option value="item4">item4</option>'; html += '<input name="item[' + item_row + '][item_id]" type="hidden" id="item-id-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][unit_price]" type="text" id="item-unit_price-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][purchase_price]" type="text" id="item-purchase_price-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][tax_rate]" type="text" id="item-tax_rate-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][discount_amount]" type="text" id="item-discount_amount-' + item_row + '">'; html += ' </td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][sale_price]" type="text" id="item-sale_price-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][quantity]" type="text" id="item-quantity-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][return_quantity]" type="text" id="item-return_quantity-' + item_row + '">'; html += '</td>'; html += '<td>'; html += '<input class="form-control text-right" required="required" name="item[' + item_row + '][total_price]" type="text" id="item-total_price-' + item_row + '">'; html += '</td>'; html += '</tr>'; $('#items tbody #addItem').before(html); item_row++; } function update_amounts() { var sum = 0.0; $('#items > tbody > tr').each(function() { var qty = $(this).find('.quantity').val(); var price = $(this).find('.sale_price').val(); var amount = (qty * price) sum += amount; $(this).find('.sub_total').text('' + amount); }); //just update the total to sum $('.grand_total').text(sum); } $('.quantity').change(function() { update_amounts(); }); ``` ```html <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" /> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table class="table table-bordered table-responsive" id="items"> <thead> <tr style="background-color: #f9f9f9;"> <th width="5%" class="text-center">Actions</th> <th width="10%" class="text-left">Item</th> <th width="8%" class="text-left">Unit Price</th> <th width="11%" class="text-left">Purchase Price</th> <th width="8%" class="text-left">Tax Rate</th> <th width="5%" class="text-right">Discount(%)</th> <th width="10%" class="text-right">Sale Price</th> <th width="5%" class="text-right">Quantity</th> <th width="13%" class="text-right">Return Quantity</th> <th width="10%" class="text-right">Total Price</th> </tr> </thead> <tbody> <?php $item_row = 0; ?> <tr id="item-row-{{ $item_row }}"> <td class="text-center" style="vertical-align: middle;"> <button type="button" onclick="$(\'#item-row-' + item_row + '\').remove();" title="Delete" class="btn btn-xs btn-danger"><i class="fa fa-trash"></i></button> </td> <td> <select class="form-control select2 typeahead" required="required" name="item[{{ $item_row }}][item_id]" id="item-item_id-{{ $item_row }}"> <option>Select</option> <option value="item1">item1</option> <option value="item2">item2</option> <option value="item3">item3</option> <option value="item4">item4</option> </select> <input name="item[{{ $item_row }}][item_id]" type="hidden" id="item-id-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][unit_price]" type="text" id="item-unit_price-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][purchase_price]" type="text" id="item-purchase_price-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][tax_rate]" type="text" id="item-tax_rate-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][discount_amount]" type="text" id="item-discount_amount-{{ $item_row }}"> </td> <td> <input class="form-control text-right sale_price" required="required" name="item[{{ $item_row }}][sale_price]" type="text" id="item-sale_price-{{ $item_row }}"> </td> <td> <input class="form-control text-right quantity" required="required" name="item[{{ $item_row }}][quantity]" type="text" id="item-quantity-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][return_quantity]" type="text" id="item-return_quantity-{{ $item_row }}"> </td> <td> <input class="form-control text-right" required="required" name="item[{{ $item_row }}][total_price]" type="text" id="item-total_price-{{ $item_row }}"> </td> </tr> <?php $item_row++; ?> <tr id="addItem"> <td class="text-center"><button type="button" onclick="addItem();" title="Add" class="btn btn-xs btn-primary" data-original-title="Add"><i class="fa fa-plus"></i></button></td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Sub Total</strong></td> <td> <input type="text" name="sub_total" id="sub_total" class="form-control text-right sub_total"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Tax Amount</strong></td> <td> <input type="text" name="tax_amount" id="tax_amount" class="form-control text-right"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Discount Amount</strong></td> <td> <input type="text" name="discount_amount" id="discount_amount" class="form-control text-right"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Grand Total</strong></td> <td> <input type="text" name="grand_total" id="grand_total" class="form-control text-right grand_total"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Cash Received</strong></td> <td> <input type="text" name="cash_received" id="cash_received" class="form-control text-right"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right align-middle"><strong>Cash Refund</strong></td> <td> <input type="text" name="cash_refund" id="cash_refund" class="form-control text-right"> </td> </tr> <tr> <td colspan="8"></td> <td class="text-right"><a href="" class="btn btn-warning">Clear</a></td> <td><button type="submit" class="btn btn-primary">Save</button></td> </tr> </tbody> </table> ```
2017/12/19
[ "https://Stackoverflow.com/questions/47880571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7014431/" ]
You can use Pandas: ``` import pandas as pd l = [ ["Pakistan", 23], ["Pakistan", 127], ["India", 3], ["India", 71], ["Australia", 31], ["India", 22], ["Pakistan", 81] ] pd.DataFrame(l).groupby([0]).mean().idxmax().values[0] ``` Output: ``` 'Pakistan' ```
Another version (with stdlib only): ``` from __future__ import division import collections input= [ ["Pakistan", 23], ["Pakistan", 127], ["India", 3], ["India", 71], ["Australia", 31], ["India", 22], ["Pakistan", 81] ] t = collections.defaultdict(list) for c,n in input: t[c].append(n) max(t, key=lambda c: sum(t[c]) / len(t[c])) 'Pakistan' ```
53,533
Is there anything that will natively allow read/write on an ext2/3 partition within Snowie? Just don't want to get a Linux box to mount, and then access via samba. Although I could perhaps through VMware Fusion … and then share it back… Anyway to do this natively?
2009/10/10
[ "https://superuser.com/questions/53533", "https://superuser.com", "https://superuser.com/users/12555/" ]
I find the easiest and most reliable way to access linux ext3 partitions on my mac is to run Ubuntu in a vmware virtual machine on the mac. Once running you can connect Ubuntu to the ext3 drive via usb, and this way you can get complete reliability reading and writing to ext3 file systems. It's fast because the disk is directly connected to the mac, unlike on a network. And you can use it to copy files very quickly to/from the mac host by using shared directories or any number of other ways.
fuse-ext2 works but is very slow (I get some 7 MB/s reading and 1 MB/s writing via USB 2.0). If you have the choice, better use Apple's HFS+ on the external drive, which is much faster (I get some 30 MB/s both reading and writing, both on Mac and Linux). HFS+ is supported by Linux mostly out-of-the-box. To get write access even to a journaled partition on Ubuntu, install support via `sudo apt-get install hfsprogs` and when the drive is mounted (e.g., automatically), re-mount it writable using `sudo mount -o remount,force,rw /mount/point` BTW, recently I suffered from a Mac OS crash apparently due to fuse-ext2 <https://sourceforge.net/projects/fuse-ext2/forums/forum/787602/topic/6549364>
28,396,012
In `C` I have this `enum`: ``` enum { STAR_NONE = 1 << 0, // 1 STAR_ONE = 1 << 1, // 2 STAR_TWO = 1 << 2, // 4 STAR_THREE = 1 << 3 // 8 }; ``` Why is `1 << 3` equal to 8 and not 6?
2015/02/08
[ "https://Stackoverflow.com/questions/28396012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Shifting a number to the left is equivalent to multiplying that number by 2n where `n` is the distance you shifted that number. To see how is that true lets take an example, suppose we have the number `5` so we shift it `2` places to the left, `5` in binary is `00000101` i.e. > > 0×27 + 0×26 + 0×25 + 0×24 + 0×23 + 1×22 + 0×21 + 1×20 = 1×22 + 1×20 = 4 + 1 = 5 > > > now, `5 << 2` would be `00010100` i.e. > > 0×27 + 0×26 + 0×25 + 1×24 + 0×23 + 1×22 + 0×21 + 0×20 = 1×24 + 1×22 = 16 + 4 = 20 > > > But we can write *1×24 + 1×22* as > > 1×24 + 1×22 = (1×22 + 1×20)×22 = 5×4 → 20 > > > and from this, it is possible to conclude that `5 << 2` is equivalent to 5×22, it would be possible to demonstrate that in general > > k << m = k×2m > > > So in your case `1 << 3` is equivalent to 23 = 8, since `1 << 3` → `b00000001 << 3` → `b00001000` → 23 -> 8 If you instead did this `3 << 1` then `3 << 1` → `b00000011 << 1` → `b00000110` → 22 + 21 → 4 + 2 → 6
Think in binary. You are actually doing this. 0001 shifted 3 times to the left = 1000 = 8
4,037,993
The login form works fine, but any other form I submit (things like editing or creating data) I get a CSRF attack detected error. I have tried to clear symfony and browser cache, deleted cookies, tried multiple browsers and multiple computers. What can cause this? When I turn off the CSRF protection it works fine.
2010/10/27
[ "https://Stackoverflow.com/questions/4037993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459950/" ]
It's tough to answer this with the information provided. Here are two possibilities: * Are you sure the CSRF token is actually being submitted? * Is the same form processing both values? CSRF tokens in Symfony are generated from three things: the CSRF secret (set in app.yml), the session\_id, and the form class. Is one of these three things changing?
To check this, you should try running Fiddler while performing the POST and check the payload for %5B\_csrf\_token%5D={whateveryourtokenis}.
4,334,520
Why is the `load` event not fired in IE for iFrames? Please take a look at [this example](http://jsfiddle.net/Claudius/GTmKv/7/). Work perfectly as expected in FF and Chrome, but IE fails.
2010/12/02
[ "https://Stackoverflow.com/questions/4334520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246277/" ]
IE might have already loaded the content (and fired the event) before you add the handler. I found that when I statically specified the iframe src attr, and added $(x).load event handlers via jquery, firefox (3.6.28) triggered my handlers but IE (8.0.6001.18702) didn't. I ended up adjusting my test program so that it set the iframe src via javascript after adding the $(x).load handler. My $(x).load handler was called at the same points in IE and Firefox (but note a handler added via iframe onload attribute behaved differently between IE and FF) . Here is what I ended up with: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <script type="text/javascript" src="jquery-ui/js/jquery-1.6.2.min.js"></script> <script language="javascript"> function show_body(name, $iframe) { $('.log').append(name+': '+$iframe.contents().find('body').html()+'<br/>'); } function actuallyLoaded(name, x) { $('.log').append(name+' actually loaded<br/>'); } $(document).ready(function(){ $('.i1').load(function(){show_body('i1', $('.i1'));}); $('.i1').attr('src', 'eb_mce_iframe_content.html'); var $x=$('.i1').clone().removeClass('i1'); $('body').append($x); $x.load(function(){show_body('x', $x);}); $x.attr('src', 'eb_mce_iframe_content.html'); }); </script> </head> <body> <iframe class="i1" onload="actuallyLoaded($(this).attr('class')+'/'+$(this).attr('src'), this);"> </iframe> <div class="log"> </div> </body> </html> ``` ... and here was the Firefox "log": i1/eb\_mce\_iframe\_content.html actually loaded i1: Fred the fox. /eb\_mce\_iframe\_content.html actually loaded x: Fred the fox.
Seis's answer is the correct one, and can be improved to use non-global/anonymous functions. ``` window.dummy_for_ie7 = function() { } var iframe = $('<iframe onload="dummy_for_ie7" />')[0]; iframe.attachEvent('onload', real_event_handler) ``` To my surprise, this works. Note: iframe.onload = func() would NOT work, even after that hack. You **MUST** use attachEvent. Go figure. Note: naturally, this code *verbatim* will not work in standard-compliant UAs.
338,359
[Git for Windows](http://code.google.com/p/msysgit/) doesn't seem to support the extra context menu entries for "Git GUI Here" (or "Git Bash Here") when running on 64-bit systems. Is there some other way I can get an entry for "Git GUI" to show up in the context menu so that it will open the commit interface with the current folder selected? ### Edit I saw the installer option and made sure it was checked, even reinstalled a few times. Also removed TortoiseGit and restarted the computer, but nothing seems to help. From what I could find online I got the impression you have to mess around with building and modifying msysgit yourself to get the context entries to work on 64-bit systems, which I'm not keen on doing.
2011/09/21
[ "https://superuser.com/questions/338359", "https://superuser.com", "https://superuser.com/users/51132/" ]
You can just type: `regsvr32 "%PROGRAMFILES%\git\git-cheetah\git_shell_ext64.dll"` in a console window (or use Win+R).
I had the same problem. After installing msysgit not in the normal program directory, everything works fine.
58,071
[In Trump's lawsuit in Arizona](https://lawandcrime.com/2020-election/trump-campaign-lawyer-admits-to-judge-our-search-for-evidence-of-fraud-produced-obvious-lies-and-spam/): > > A Trump campaign attorney conceded in court on Thursday morning that he tried to enter hundreds of dodgy form-filed affidavits into evidence, even though their own investigation found that a subset of the sworn statements that they received were filled with lies and “spam.” > > > “This is concerning,” [said] Judge Daniel Kiley, ... > > > > > ... The Trump campaign said it excluded the submissions of those who swore to lies, but they included the ones they could not prove were lying into evidence. > > > Judge Kiley replied that this did not show the remaining affidavits are trustworthy. > > > “That just shows you cannot disprove what’s asserted,” Kiley noted. > > > Does a lawyer ordinarily need to take steps to determine that the contents of an affidavit are actually true before submitting it (rather than merely excluding ones determined to be false)? If not, what is the reasoning behind the judge requiring it here? Trump's lawyer may have collected the text of the affidavits via an online form, but he then printed them and had them signed under penalty of perjury by the affiants, which to my non-lawyer sensibilities makes them no different than any other affidavits.
2020/11/14
[ "https://law.stackexchange.com/questions/58071", "https://law.stackexchange.com", "https://law.stackexchange.com/users/14414/" ]
To witness an affidavit? ------------------------ No. However, ... ------------ An affidavit is testimony-in-chief of a witness. Either: * that testimony is going to be tested under cross-examination. So, the lawyer that presents it better be pretty sure that their witness will not look like a liar. Or * for reasons of judicial efficiency the evidence will not be tested. If so, the judge or jury will decide how much weight to give that evidence. A jury does not have to give reasons for who they believe and who they don’t; a judge does. As to your question ... ----------------------- The judge wants to know because these affidavits will not be tested because a decision has to be made very quickly; before the Arizona has to certify their votes. Therefore the judge has to use other methods to decide how much weight to give these affidavits. Correct answer: not a lot.
> > Does a lawyer ordinarily need to take steps to determine that the > contents of an affidavit are actually true before submitting it > (rather than merely excluding ones determined to be false)? > > > Depends on the role of the lawyer. There can be two: 1. Lawyer who simply takes the affidavit from the person giving/swearing it. Whoever has got this affidavit can then use it in court for any purpose. 2. Lawyer who presents the affidavit before court. This does not need to be the same lawyer who took the affidavit (does not need to be a lawyer at all actually). So, for a lawyer in the 1st role the answer is no. For a lawyer in the 2nd role it is by all means a good idea to be actually sure/believe that the contents are true. Otherwise, if a litigant does not fully believe evidence in his favor, how can he come any close to convincing the judge?
735,821
This problem is designated for those who have the basic knowledge of floor brackets I know the answer will be 6. But tell me how.
2014/04/01
[ "https://math.stackexchange.com/questions/735821", "https://math.stackexchange.com", "https://math.stackexchange.com/users/132522/" ]
It is clear that $\dfrac{13x + 4}{3}$ must be an integer so $x$ must have the form of $2 + 3k$. Substitute this into the equation and now we must solve: $$\left\lfloor\frac{48+75k}{4}\right\rfloor = \left\lfloor 12 + \frac{75k}{4}\right\rfloor = 12 + \left\lfloor \frac{75k}{4}\right\rfloor = 13k + 10$$ $$ \left\lfloor \frac{75k}{4}\right\rfloor = 13k - 2$$ Find an approximate solution by solving $\frac{75k}{4} = 13k - 2$ and reaching $k = -\frac{8}{23}$. We will now look for solutions on intervals around this point. $$ \left.\left\lfloor \frac{75k}{4}\right\rfloor\right|\_{k = -8/23} = -7$$ Let $13k -2 = -8,$ $k = -\dfrac{6}{13}.$ Let $13k -2 = -7,$ $k = -\dfrac{5}{13}.$ Let $13k -2 = -6,$ $k = -\dfrac{4}{13}.$ Let $13k -2 = -5,$ $k = -\dfrac{3}{13}.$ From these possible values of $k$ we find that $x = \dfrac{8}{13}, \dfrac{11}{13}, \dfrac{14}{13}, \dfrac{17}{13}$. Plugging in to the original equation to verify we find two extraneous solutions and that $\boxed{x = \dfrac{14}{13}, \dfrac{17}{13}}$. This method will not work well in all cases. Because $\frac{75}{4} = 18.75 \not\approx 13$ I assumed that there are a maximum of four solutions. In a case where we must solve $ \lfloor \frac{75k}{4}\rfloor = 19k - 2$ there are five solutions. In $ \lfloor \frac{75k}{4}\rfloor = 18.75k - 2$ there will be infinitely many.
$\left[{p}\right]=\left[\frac{\mathrm{25}{x}−\mathrm{2}}{\mathrm{4}}\right]=\frac{\mathrm{13}{x}+\mathrm{4}}{\mathrm{3}}={n}\in{Z} \\ $ ${x}=\frac{\mathrm{3}{n}−\mathrm{4}}{\mathrm{13}}\Rightarrow\frac{\mathrm{25}{x}−\mathrm{2}}{\mathrm{4}}=\frac{\mathrm{75}{n}−\mathrm{74}}{\mathrm{52}} \\ $ $\left\{{p}\right\}=\frac{\mathrm{75}{n}−\mathrm{74}}{\mathrm{52}}−{n}=\frac{\mathrm{23}{n}−\mathrm{74}}{\mathrm{52}} \\ $ ${n}\in\left\{\mathrm{4},\mathrm{5}\right\}\Rightarrow{x}\in\left\{\frac{\mathrm{8}}{\mathrm{13}},\frac{\mathrm{11}}{\mathrm{13}}\right\} \\ $ Yes, it's not 6
227,879
I am trying to use `bibunits` package. If I compile the TeX file using the following sequence of commands, it works properly. ``` pdflatex document bibtex bu1 pdflatex document pdflatex document ``` However, if I compile it using TeXstudio 2.8.8, TeXstudio fails to recognize bibtex entries inside the bibunit. Here is a minimal example. ``` \documentclass{article} \usepackage{bibunits} \usepackage{filecontents} \begin{filecontents}{mybib.bib} @ARTICLE{Meyer2000, AUTHOR="Bernd Meyer", TITLE="A constraint-based framework for diagrammatic reasoning", JOURNAL="Applied Artificial Intelligence", VOLUME= "14", ISSUE = "4", PAGES= "327--344", YEAR=2000 } @ARTICLE{Codishetal2000, AUTHOR="M. Codish and K. Marriott and C.K. Taboch", TITLE="Improving program analyses by structure untupling", JOURNAL="Journal of Logic Programming", VOLUME= ""43", ISSUE = "3", PAGES= "251--263", YEAR=2000 } \end{filecontents} \begin{document} \begin{bibunit}[plain] References to the \TeX book \cite{Meyer2000} and to Lamport’s \LaTeX\ book, which appears only in the references\nocite{Codishetal2000}. \putbib[mybib] \end{bibunit} \end{document} ```
2015/02/13
[ "https://tex.stackexchange.com/questions/227879", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/50211/" ]
Old question, but exactly my problem. I don't know much about TeXstudio, but I put together a hack to get it to work. There must be a better way. Somebody please post it. 1. Go to Options->Configure TeXstudio... 2. Select Commands from the options on the left 3. Scroll to BibTeX 4. Update the BibTeX command as described below The default command should be "bibtex.exe %", which apparently runs bibtex on the main filename (without the extension). I added a list of executions of bibtex on bu# where # is a number from 1 to 9. So the BibTeX command now looks like: ``` bibtex.exe % | bibtex.exe bu1 | bibtex.exe bu2 | bibtex.exe bu3 | bibtex.exe bu4 | bibtex.exe bu5 | bibtex.exe bu6 | bibtex.exe bu7 | bibtex.exe bu8 | bibtex.exe bu9 ``` FYI, I am running TeXstudio 2.8.4 on Windows 7 Like I said, a hack. But it seems to work. --- **Edit**: I'm guessing TeXstudio does conditional "recompiles" of the bibliography based on whether it thinks there has been a change. I'm also guessing that it doesn't detect changes well with bibunits. Therefore, I've had to do (at least) three TeXstudio steps when using this hack. First, recompile main tex file. Second, recompile bib file (f11). Third, recompile main tex file again.
You may want to use **[latexmk](https://www.ctan.org/pkg/latexmk/)**. It fully automates the process of compilation. ``` latexmk -pdflatex -synctex=1 document.tex ``` will do the job. You can tell TeXstudio to use **latexmk**. Just change the settings for PdfLaTeX command from ``` pdflatex -synctex=1 -interaction=nonstopmode %.tex ``` to ``` latexmk -pdflatex -synctex=1 -interaction=nonstopmode %. ```
39,532,144
i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem. **Testmatrix.java** ``` public class TestMatrix{ int rows; int cols; double data[][] = new double[4][4]; public TestMatrix() { super(); rows=1; cols=1; for(int i=0; i<=rows;i++) { for(int j=0; j<=cols;j++) { data[i][j] = 0.0; } } } public void print(){ for (int i = 0; i <data.length ; i++) { for (int j = 0; j <data[0].length ; j++) { System.out.print(data[i][j]+" "); } System.out.println(); } } ``` Here is the main class **Main.java** ``` public class Main { public static void main(String[] args){ TestMatrix m1 = new TestMatrix(); m1.print(); } } ``` Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's) Thanks in advance \*\*
2016/09/16
[ "https://Stackoverflow.com/questions/39532144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5288543/" ]
Either declare matrix to 2\*2 as said by Chris or change ``` for (int i = 0; i < data.length ; i++) { for (int j = 0; j < data.length ; j++) { ``` to ``` for (int i = 0; i <= rows ; i++) { for (int j = 0; j <= cols ; j++) { ``` If you want any size of matrix upto 4\*4 use second solution.
Your class should be like this: ``` public class Test { int rows; int cols; double data[][] = new double[2][2]; public void print() { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length; j++) { System.out.print(" "+data[i][j]+" "); } System.out.println(); } } public static void main(String[] args) { Test m1 = new Test(); m1.print(); } } ``` and this part you can delete. You do not need it. This is not an initialization. ``` public void matrix() { rows = 1; cols = 1; for (int i = 0; i <= rows; i++) { for (int j = 0; j <= cols; j++) { data[i][j] = 0.0; } } } ```
5,827,590
I would like to style the following: **forms.py:** ``` from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea) ``` **contact\_form.html:** ``` <form action="" method="post"> <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> ``` For example, how do I set a **class** or **ID** for the `subject`, `email`, `message` to provide an external style sheet to?
2011/04/29
[ "https://Stackoverflow.com/questions/5827590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651174/" ]
Write your form like: ``` class MyForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name") message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message") ``` In your HTML field do something like: ``` {% for field in form %} <div class="row"> <label for="{{ field.name}}">{{ field.label}}</label>{{ field }} </div> {% endfor %} ``` Then in your CSS write something like: ``` .name{ /* you already have this class so create it's style form here */ } .message{ /* you already have this class so create it's style form here */ } label[for='message']{ /* style for label */ } ``` Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.
There is a very easy to install and great tool made for Django that I use for styling and it can be used for every frontend framework like Bootstrap, Materialize, Foundation, etc. It is called widget-tweaks Documentation: [Widget Tweaks](https://pypi.python.org/pypi/django-widget-tweaks) 1. You can use it with Django's generic views 2. Or with your own forms: from django import forms ``` class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea) ``` Instead of using default: ``` {{ form.as_p }} or {{ form.as_ul }} ``` You can edit it your own way using the render\_field attribute that gives you a more html-like way of styling it like this example: template.html ``` {% load widget_tweaks %} <div class="container"> <div class="col-md-4"> {% render_field form.subject class+="form-control myCSSclass" placeholder="Enter your subject here" %} </div> <div class="col-md-4"> {% render_field form.email type="email" class+="myCSSclassX myCSSclass2" %} </div> <div class="col-md-4"> {% render_field form.message class+="myCSSclass" rows="4" cols="6" placeholder=form.message.label %} </div> </div> ``` This library gives you the opportunity to have well separated yout front end from your backend
79,098
Is there a program/resource that allows you to track graphics files—for instance an Illustrator or Photoshop file—and will list all InDesign or Illustrator files where that asset is used? Bridge doesn't seem to do that.
2016/10/22
[ "https://graphicdesign.stackexchange.com/questions/79098", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/78629/" ]
As far as I'm aware, no file has any no clue where it may or may not be used moving forwards. Customarily assets can only be collected from the collective file, not the the individual pieces that make up the collection. I've never heard of any asset collection that can somehow magically know where the asset was used just by looking at the asset. The link between files is created in the main file via a references to the included asset(s). There's no software I know that then embeds some sort of subscribe link in the original asset file(s) so they know where they are used.
I've read that NeoFinder can 'look inside' documents in a search such as a PDF. Maybe it'll see the list of links inside, for example, an InDesign file. I asked the question at the NeoFinder site and will update you when I hear back!
4,485,399
I would like to know how to bump the last digit in a version number using bash. e.g. ``` VERSION=1.9.0.9 NEXT_VERSION=1.9.0.10 ``` EDIT: The version number will only contain natural numbers. Can the solution be generic to handle any number of parts in a version number. e.g. ``` 1.2 1.2.3 1.2.3.4 1.2.3.4.5 ```
2010/12/19
[ "https://Stackoverflow.com/questions/4485399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83416/" ]
**TL;DR:** ``` VERSION=1.9.0.9 echo $VERSION | awk -F. '/[0-9]+\./{$NF++;print}' OFS=. # will print 1.9.0.10 ``` For a detailed explanation, read on. --- Let's start with the basic [answer](https://stackoverflow.com/a/4485581/15168) by [froogz3301](https://stackoverflow.com/users/83416/froogz3301): ``` VERSIONS=" 1.2.3.4.4 1.2.3.4.5.6.7.7 1.9.9 1.9.0.9 " for VERSION in $VERSIONS; do echo $VERSION | awk -F. '{$NF = $NF + 1;} 1' | sed 's/ /./g' done ``` How can we improve on this? Here are a bunch of ideas extracted from the copious set of comments. The trailing '1' in the program is crucial to its operation, but it is not the most explicit way of doing things. The odd '1' at the end is a boolean value that is true, and therefore matches every line and triggers the default action (since there is no action inside braces after it) which is to print $0, the line read, as amended by the previous command. Hence, why not this `awk` command, which obviates the `sed` command? ``` awk -F. '{$NF+=1; OFS="."; print $0}' ``` Of course, we could refine things further — in several stages. You could use the bash '<<<' string redirection operator to avoid the pipe: ``` awk -F. '...' <<< $VERSION ``` The next observation would be that given a series of lines, a single execution of awk could handle them all: ``` echo "$VERSIONS" | awk -F. '/[0-9]+\./{$NF+=1;OFS=".";print}' ``` without the for loop. The double quotes around "$VERSION" preserve the newlines in the string. The pipe is still unnecessary, leading to: ``` awk -F. '/[0-9]+\./{$NF+=1;OFS=".";print}' <<< "$VERSIONS" ``` The regex ignores the blank lines in `$VERSION` by only processing lines that contain a digit followed by a dot. Of course, setting OFS in each line is a tad clumsy, and '`+=1`' can be abbreviated '`++`', so you could use: ``` awk -F. '/[0-9]+\./{$NF++;print}' OFS=. <<< "$VERSIONS" ``` (or you could include '`BEGIN{OFS="."}`' in the program, but that is rather verbose. The '`<<<`' notation is only supported by Bash and not by Korn, Bourne or other POSIX shells (except as a non-standard extension parallelling the Bash notation). The AWK program is going to be supported by any version of `awk` you are likely to be able to lay hands on (but the variable assignment on the command line was not supported by old UNIX 7th Edition AWK).
I have come up with this. ``` VERSIONS=" 1.2.3.4.4 1.2.3.4.5.6.7.7 1.9.9 1.9.0.9 " for VERSION in $VERSIONS; do echo $VERSION | awk -F. '{$NF = $NF + 1;} 1' | sed 's/ /./g' done ```
3,003,986
There are many ways to express a plane of $R^3$. I am focusing on two of them. The first is the cartesian equation $Ax + By + Cz + D = 0$. The second is to give two direction vectors $u$ and $v$ and a point $P$ of the plane. My question is: how can I obtain two **ortogonal** direction vectors $u$ and $v$ and a point $P$ from the cartesian equation $Ax + By + Cz + D = 0$? How can I obtain the cartesian equation from the direction vectors and a point of the plane?
2018/11/18
[ "https://math.stackexchange.com/questions/3003986", "https://math.stackexchange.com", "https://math.stackexchange.com/users/295866/" ]
$$(a,b,c)=\vec n$$ is a vector normal to the plane. From the knowledge of the Cartesian equation, choose the vector among $(0,c,-b), (-c,0,a)$ and $(b,-a,0)$ with the largest norm (do this to avoid degeneracies). This gives you a first vector perpendicular to $\vec n$, let $\vec u$. Then set $\vec v=\vec n\times\vec u$, and you have your second vector. For the point, you can project the origin orthogonally onto the plane, i.e. find $\lambda$ such that $\lambda(a,b,c)$ fulfills the plane equation. This yields $$\lambda(a^2+b^2+c^2)+d=0.$$ --- The converse is easier. Compute $$(a,b,c)=\vec u\times\vec v$$ and expand $$a(x-x\_P)+b(y-y\_P)+c(z-z\_P)=0.$$
Going one direction: Given $Ax + By + Cz + D = 0$ $(B,-A, 0)$ is a vector in the plane $(A,B,\frac {A^2 + B^2}{C})$ is a vector in the plane orthogonal to the first. $(0,0,-\frac {D}{C})$ is a point in the plane Of course, this is just one way to find orthogonal vectors and a point in the plane. Going the other direction.... given, vectors in the plane $u,v$ and point in the plane $P$ $u\times v = N$ is normal vector in the plane. Suppose the components are $N = (N\_x,N\_y,N\_z)$ then $N\_x x + N\_y y+ N\_z z - N\cdot P = 0$ will be an equation for the plane.
24,645,432
We have created a Play application in Java and are deploying it to a dev-environment virtual machine using [Atlassian Bamboo's](https://www.atlassian.com/software/bamboo) SSH task: `cd path/to/application/directory && start "" play run`. This goes to the proper location, launches a new console, and starts play: the server is started successfully and we can access the site with no issues. The problem is that the deployment task in Bamboo never stops because it is still monitoring the console where `play run` was called -- in the Bamboo status, we are seeing things like `Deploying for 7,565 minutes`. We thought adding the `start ""` would fix that issue, but in Bamboo it is the same as just doing the `play run`. Also, when we need to redeploy, we must first stop the deployment in process, and manually relaunch it. **Two questions:** 1. How can we start the server from Bamboo in such a way that the deployment plan finishes? 2. How can we stop/kill the previous server from Bamboo at the beginning of the next deployment?
2014/07/09
[ "https://Stackoverflow.com/questions/24645432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/935476/" ]
From [javadocs](http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) : Since java 5 **Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.** The java compiler applies autoboxing usually when - * Passed as a parameter to a method that expects an object of the corresponding wrapper class. * Assigned to a variable of the corresponding wrapper class.
This feature has been added in Java 5. **text** gets converted automatically into Integer by compiler. So basically its a syntactic sugar that can shorten your code (otherwise you would do conversions back and forth by yourself). Of course it has its price and if this happens a lot (I mean really a lot, big loops, frequent invocations and so forth), it can become a performance issue, so when using it, just remember the it happens under the hood and you'll be fine. ``` Integer.valueOf(text) ``` is called under the hood The feature is called autoboxing btw Hope this helps
32,641
> > KJV John 15:19  If ye were of the world, the world would love his own: > but because ye are not of the world, but I have chosen you out of the > world, therefore the world hateth you.  > > > Westcott and Hort / [NA27 variants] εἰ ἐκ τοῦ κόσμου ἦτε, ὁ κόσμος ἂν > τὸ ἴδιον ἐφίλει· ὅτι δὲ ἐκ τοῦ κόσμου οὐκ ἐστέ, ἀλλ' ἐγὼ ἐξελεξάμην > ὑμᾶς ἐκ τοῦ κόσμου, διὰ τοῦτο μισεῖ ὑμᾶς ὁ κόσμος. > > >
2018/04/12
[ "https://hermeneutics.stackexchange.com/questions/32641", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/20832/" ]
No, there was no separation of the Godhead at any time during the crucifixion. I believe there has been a great misunderstanding about Christ’s quoting of Psalm 22 on the cross. Jesus quoted Psalm 22:1: > > “My God, My God, why has thou forsaken Me.” > > > Based on this quote, many people have developed all kinds of theories of separation of the persons of the Trinity. This is based on an incomplete understanding of the context. All one has to do is to continue reading in Psalm 22 to find out there was no separation and that the Father had NOT forsaken Christ. > > 22I will declare thy name unto my brethren: in the midst of the > congregation will I praise thee. 23 Ye that fear the Lord, praise him; > all ye the seed of Jacob, glorify him; and fear him, all ye the seed > of Israel. 24 For he hath not despised nor abhorred the affliction of > the afflicted; neither hath he hid his face from him; but when he > cried unto him, he heard. > > > The entire context of Psalm 22 shows that God has NOT despised nor abhorred the affliction of the afflicted and had NOT hid His face from Him and heard Him when He called. Obviously, Christ would have understood the complete context of the Psalm and was most likely recounting this to Himself when He was on the cross. We can certainly understand that Christ (in His humanity) would have most definitely **felt** that God had forsaken Him. However, He would have also understood the true character of His Father who would not abandon Him. Hence, the reassurance of quoting the Psalm in His time of need. As far as your reference to Hebrews 9; I am not sure what you were asking. Per the KJV: > > 13 For if the blood of bulls and of goats, and the ashes of an heifer > sprinkling the unclean, sanctifieth to the purifying of the flesh: 14 > how much more shall the blood of Christ, who through the eternal > Spirit offered himself without spot to God, purge your conscience from > dead works to serve the living God? > > > These verses communicate the superiority of Christ’s sacrifice over the OT temple sacrifices. The OT sacrifices could not purge sin only the sacrifice of Christ could do that. There is no indication of separation in either verse.
To answer your question, it is absolutely necessary to treat theological and Christological issue: a) what is the reality of God, His Spirit and His Logos-Son and b) how Jesus, the Logos-Son incarnate in history, is related to the Holy Spirit after the Incarnation? Below I shall address those issues and try eventually to find the solution to your question also. The New Testament, and the Bible in general, does not have a very strict terminology with regard of "soul" and "spirit" and sometimes they are used interchangeably as standing for the created reasonable soul of human being, through presence of which he moves, desires and, which is even more important, thinks. However, the New Testament also speaks of the uncreated Spirit of God through whom one can receive the "new birth" (John 3:3). Humans, *qua* created and limited, have the presence of the Spirit in a dynamically apportioned way, for it is impossible for finite beings to possess the infinite divine Spirit in His fullness, for only God can claim this. Now, Spirit possesses all what belongs to God, for He "knows even the depths of God" (1 Cor. 2:10), and in this way the Spirit is equal to God, for epistemological equality in the invisible and purely spiritual realm amounts to ontological equality; and by the same token also the Son is equal to the Father and the Spirit, for the Spirit receives everything from the Son, who has everything of the Father (John 16:15). This fullness of the Spirit and the Son with all infinite riches of God in actual infinity is not temporal and processual/gradational, but eternal and instantaneous, and this common fullness with the same infinite reality of the Three - the Father, the Spirit and the Son - has been there even before the world was created, in all eternity, and such a volitional act as creation of the universe can in not even a tiny bit change anything in the changeless trinitarian relationship of love in the Godhead, for God is eternal changeless love of divine Persons, and that is the meaning of the verse "God is love" (1 John 4:8). In fact, a Mono-Personal Absolute cannot be the God of love, for before creation of the world He would love only Himself, and be thus the Absolute lonely Egoist; but the Christian God, the eternal Father loved eternally His co-eternal Son even before He created the world through Him (John 17:24). This said, we can firmly hold in mind's gaze: **Trinitarian Persons are indivisible**. To give just an analogy: can you disentangle water from wetness? Not, of course. Infinitely more so, you cannot disentangle the Persons of the Trinity from each other, although neither are they mixed, as to lose the Personal distinctions, for the Father is not the Son and the Son is not the Holy Spirit, even if the reality of the Three is one and identical. Now, Christology: who is Christ? He is the Logos-Son Incarnate, that is to say, Logos-Son having adopted the human nature, or human created body invested with intelligent created soul. Thus, Logos, who always is with the Father and the Spirit inseparably, has adopted the human ensouled body, which is another wording for "human nature". At the death on the Calvary Jesus gave His human created soul to the "hands of the Father", as the dying man does, but this human created soul does not perish on the hands of God, for how can anything die received by the vivifying "hand" of the Father; of course this "hand" is not a physical hand but a metaphor for His Spirit (in fact, the Spirit of God is equated with the "finger of God" in the parallel passages of Matthew 12:28, Luke 11:20), and this is the meaning of 1 Peter 3:18, that His body died, but His soul was vivified by Spirit, that is to say, by the vivifying "hand of the Father", and by the Logos-Son also, who, as God, has authority and power to vivify, for Logos, qua God, could not die, for it is ontologically impossible for God's eternal Logos to die; but we justly say, that Logos in a certain sense, suffered and died on the Cross, for Logos' human body became, by adoption, by His volition, eternal aspect of His Personality, so that after the Incarnation we can think of the invisible divine Person of Logos only together with His human nature and human body, and since His body really died, we somehow say that "God's Logos died", "God's co-eternal Son died". But of course, when we say this, we imply that His body died, that is to say, the Logos' created soul was separated from His created body; as, for instance, when Paul passionately desires for death, he in fact desires that his soul is separated from the physical body and joining eternally Christ (Phil 1:23) (for it is impossible to suppose that he longs for total annihilation in this manner, for annihilation and complete "switching off" of consciousness before the general resurrection simply cannot be more desirable for Paul than being with his beloved Christian community on earth, but being, after physical death, with Christ with a greater intensity of graceful interaction - that is truly more desirable even than being with the beloved brethren-Christians on earth). Thus, neither Father, nor Holy Spirit never ever have left the Logos, either before the Incarnation, or after the Incarnation (when the Incarnate Logos, the Logos who became also son of a man, was called Jesus Christ and eternally so henceforth), or on the Calvary, when He in His human nature was undergoing unspeakable sufferings and eventually also underwent death - the separation of His, Uncreated Logos' created soul from His, Uncreated Logos' created body. Apologizes for the length of the answer, but it is difficult to make shorter such a breathtakingly difficult issues.
25,071,766
You are given a string like: ``` input_string = """ HIYourName=this is not true HIYourName=Have a good day HIYourName=nope HIYourName=Bye!""" ``` Find the most common sub-string in the file. Here the answer is "HiYourName=". Note, the challenging part is that HiYourName= is not a "word" itself in the string i.e. it is not delimited by spaced around it. So, just to clarify, this is not most common word problem.
2014/08/01
[ "https://Stackoverflow.com/questions/25071766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3897793/" ]
Here's a simple brute-force solution: ``` from collections import Counter s = " HIYourName=this is not true HIYourName=Have a good day HIYourName=nope HIYourName=Bye!" for n in range(1, len(s)): substr_counter = Counter(s[i: i+n] for i in range(len(s) - n)) phrase, count = substr_counter.most_common(1)[0] if count == 1: # early out for trivial cases break print 'Size: %3d: Occurrences: %3d Phrase: %r' % (n, count, phrase) ``` The output for your sample string is: ``` Size: 1: Occurrences: 10 Phrase: ' ' Size: 2: Occurrences: 4 Phrase: 'Na' Size: 3: Occurrences: 4 Phrase: 'Nam' Size: 4: Occurrences: 4 Phrase: 'ourN' Size: 5: Occurrences: 4 Phrase: 'HIYou' Size: 6: Occurrences: 4 Phrase: 'IYourN' Size: 7: Occurrences: 4 Phrase: 'urName=' Size: 8: Occurrences: 4 Phrase: ' HIYourN' Size: 9: Occurrences: 4 Phrase: 'HIYourNam' Size: 10: Occurrences: 4 Phrase: ' HIYourNam' Size: 11: Occurrences: 4 Phrase: ' HIYourName' Size: 12: Occurrences: 4 Phrase: ' HIYourName=' Size: 13: Occurrences: 2 Phrase: 'e HIYourName=' ```
Another brute force without imports: ``` s = """ HIYourName=this is not true HIYourName=Have a good day HIYourName=nope HIYourName=Bye!""" def conseq_sequences(li): seq = [] maxi = max(s.split(),key=len) # max possible string cannot span across spaces in the string for i in range(2, len(maxi)+ 1): # get all substrings from 2 to max possible length seq += ["".join(x) for x in (zip(*(li[i:] for i in range(i)))) if " " not in x] return max([x for x in seq if seq.count(x) > 1],key=len) # get longest len string that appears more than once print conseq_sequences(s) HIYourName= ```
13,226,986
I need to verify a Text present in the page through WebDriver. I like to see the result as boolean (true or false). Can any one help on this by giving the WebDriver code?
2012/11/05
[ "https://Stackoverflow.com/questions/13226986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1793816/" ]
Driver.getPageSource() is a bad way to verify text present. Suppose you say, `driver.getPageSource().contains("input");` That doesn't verify "input" is present on the screen, only that "input" is present in the html, like an input tag. I usually verify text on an element by using xpath: ``` boolean textFound = false; try { driver.findElement(By.xpath("//*[contains(text(),'someText')]")); textFound = true; } catch (Exception e) { textFound = false; } ``` If you want an exact text match, just remove the contains function: ``` driver.findElement(By.xpath("//*[text()='someText'])); ```
If you want check only displayed objects(**C#**): ``` public bool TextPresent(string text, int expectedNumberOfOccurrences) { var elements = Driver.FindElements(By.XPath(".//*[text()[contains(.,'" + text + "')]]")); var dispayedElements = 0; foreach (var webElement in elements) { if (webElement.Displayed) { dispayedElements++; } } var allExpectedElementsDisplayed = dispayedElements == expectedNumberOfOccurrences; return allExpectedElementsDisplayed; } ```
8,017,705
When I try to start RMAN I get this error: ``` SQL> rman target=/ SP2-0734: unknown command beginning "rman targe..." - rest of line ignored. SQL> ``` What am I missing?
2011/11/05
[ "https://Stackoverflow.com/questions/8017705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008100/" ]
You don't run RMAN from SQL\*Plus - you run it from the command line. [Have a look here](http://download.oracle.com/docs/cd/B19306_01/backup.102/b14193/toc.htm#i771020).
You must run the RMAN from command line interface not from the sql plus. The following are the command options. 1). RMAN target / catalog username/password@schema 2.) RMAN connect target /
31,774,643
Here is my `match` table ``` +----------------------------+ |Match_id |team1_id|team2_id | ------------------------------ | 1 | 1 | 2 | +----------------------------+ ``` Teams have severals played mapped by team\_player ``` +------------------+ |team_id |player_id| -------------------- | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 | 4 | | 2 | 5 | | 2 | 6 | +------------------+ ``` And then the `players` table ``` +----------------------+ |player_id |player_name| -----------------------| | 1 | p1 | | 2 | p2 | | 3 | p3 | | 4 | p4 | | 5 | p5 | | 6 | p6 | +----------------------+ ``` I try to get players name by team. Here is my query : ``` SELECT tp1.`player_id` as id1, tp2.`player_id` as id2, p1.`player_name` as pseudo1, p2.`player_name` as pseudo2 FROM (`match` m LEFT JOIN `team_player` tp1 ON m.`team1_id` = tp1.`team_id` LEFT JOIN `team_player` tp2 ON m.`team2_id` = tp2.`team_id`) LEFT JOIN `players` p1 ON tp1.`player_id` = p1.`player_id` LEFT JOIN `players` p2 ON tp2.`player_id` = p2.`player_id` WHERE m.`MATCH_ID`= 49 ``` It gets me this : ``` +------------------------+ |id1 |id2|pseudo1|pseudo2| |------------------------| |1 |4 | p1 | p4 | |1 |5 | p1 | p5 | |1 |6 | p1 | p6 | |2 |4 | p2 | p4 | |2 |5 | p2 | p5 | |2 |6 | p2 | p6 | |3 |4 | p3 | p4 | |3 |5 | p3 | p5 | |3 |6 | p3 | p6 | +------------------------+ ``` Is it possible to get this : ``` +------------------------+ |id1 |id2|pseudo1|pseudo2| |------------------------| |1 |4 | p1 | p4 | |3 |5 | p2 | p5 | |1 |6 | p3 | p6 | +------------------------+ ``` Thanks ;)
2015/08/02
[ "https://Stackoverflow.com/questions/31774643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095267/" ]
Once the `Color` enum is initialized, `RANDOM` will be one specific color - it may be different from execution to execution, but in a single run, it will stay fixed. What you want is to generate a new Color every time you use `RANDOM`. (At least that's how I understood it) One way to do this is using a constant-specific enum body: ``` public enum Color { //... RANDOM(0) { @Override public int getRGB() { return Utils.randomColor(); } }; //... } ``` --- This has its own problems. For example, you probably want to generate multiple random colors, each of which remains constant. Otherwise, each time you use the color, you get a new one. To avoid this, the only way is really not to use an enum at all, at least not exclusively. Basically, the solution would be to do what `java.awt.Color` already does: a simple class that you can create arbitrary instances of, and `public static final` constants that enumerate some predefined colors.
The other answers will work, but in Java 8 there's an even nicer way to do it. Have each enum be initialized not with its color, but an [`IntSupplier<Color>`](https://docs.oracle.com/javase/8/docs/api/java/util/function/IntSupplier.html). ``` public class Property { ... Property(IntSupplier rgbSupplier) { this.rgbSupplier = rgbSupplier; } Property(int rgb) { // convenience constructor this(() -> rgb); // delegate to constructor above } public int getRGB() { return rgbSupplier.getAsInt(); } ... } ``` For most of your colors, the construction is the same; but for the random one, you supply a method reference: ``` ... PINK(new java.awt.Color(255, 40, 166).getRGB()), RANDOM(Utils::randomColor), ... ``` In English, what this is doing is constructing each enum not with a specific value, but with an `IntSupplier` that says "get me the value." The "standard" types are each constructed with an `IntSupplier` that always returns the provided value (`() -> rgb`), but the random one is constructed with an `IntSupplier` that invokes `Utils.randomColor()`.
8,240,419
I want some kind of utility more like Call Stack which gives me list of all the methods/properies that are executing in the current run, something that works on realtime will be good. Actually i am refactoring my code and wants to keep an eye on things that are not usable or things that should be avoided. I am using FxCop but that is not powerful enough to serve the purpose. Kindly help Thanks
2011/11/23
[ "https://Stackoverflow.com/questions/8240419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2720334/" ]
Sounds like you are looking for a .NET profiler. There are several commercial offerings: * RedGate - [ANTS performance profiler](http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/) * jetBrains - [dotTrace](http://www.jetbrains.com/profiler/) Also, see the answer to this SO question - [What Are Some Good .NET Profilers?](https://stackoverflow.com/questions/3927/what-are-some-good-net-profilers)
When I'm refactoring code I use the Obsolete-attribute a lot. ``` <Obsolete("Please use the better and faster MyNewSub() instead. This method still work, see info in MyNewSub on how to migrate.")> _ Public Sub MyOldSub() ' code. End Sub ``` This way I get warnings for every function that calls this method. And every user in the project will see that the function should be avoided when coding further. (You can also set the attribute to generate an error instead of a warning) Maybe not an direct answer on your question, but it is a good tool when refactoring code.
1,446,120
I am going over C and have a question regarding `const` usage with pointers. I understand the following code: ``` const char *someArray ``` This is defining a pointer that points to types of char and the `const` modifier means that the values stored in `someArray` cannot be changed. However, what does the following mean? ``` char * const array ``` Is this an alternate way of specifying a parameter that is a char pointer to an array named "array" that is `const` and cannot be modified? Lastly, what does this combination mean: ``` const char * const s2 ``` For reference, these are taken from the Deitel C programming book in Chapter 7 and all of these are used as parameters passed to functions.
2009/09/18
[ "https://Stackoverflow.com/questions/1446120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135306/" ]
From [what is the difference between const int\*, const int \* const, int const \*](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-int-const): > > Read it backwards... > > > > ``` > int* - pointer to int > int const * - pointer to const int > int * const - const pointer to int > int const * const - const pointer to const int > > ``` > >
Repeating what other users wrote, but I want to provide context. Take these two definitions: ``` void f1(char *ptr) { /* f1 can change the contents of the array named ptr; * and it can change what ptr points to */ } void f2(char * const ptr) { /* f2 can change the contents of the array named ptr; * but it cannot change what ptr points to */ } ``` Making the pointer itself `const`, like in the f2 example, is ~~absolutely~~ almost pointless. Every parameter passed to a function is passed by value. If the function changes that value, it only changes its local copy and has no effect on the calling code. ``` /* ... calling code ... */ f1(buf); f2(buf); ``` In either case, `buf` is unchanged after the function call. --- Consider the strcpy() function ``` char *strcpy(char *dest, const char *src); ``` One possible implementation is ``` char *strcpy(char *dest, const char *src) { char *bk = dest; while (*src != '\0') { *dest++ = *src++; } *dest = *src; return bk; } ``` This implementation changes both `dest` and `src` inside the function only. Making either of the pointers (or both) `const` would gain nothing for the strcpy() function or to the calling code.
382,726
I was reading the first law of thermodynamics when it struck me. We haven't been taught differentiation but still, we find it in our chemistry books. Why is small work done always taken as $dW=F \cdot dx$ and not $dW=x \cdot dF$?
2018/01/28
[ "https://physics.stackexchange.com/questions/382726", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/182968/" ]
The answer to your question depends on how we define work. ***Definition***, *A force is said to do work if, when acting, there is a displacement of the point of application in the direction of the force.* In layman language, to do work you need displacement, not just force. In the equation, $dW=x.dF$, we are considering a change in force at a constant position from a reference point (origin). As per our definition, no work is being done because there is no displacement. To understand it better, assume there is a heavy block and you are applying a variable force to it. No matter how hard you push, you won't be able to give it some speed. The work-energy theorem says that if a force does some effective work, there is a change in kinetic energy of the body. But in our case, there is no change in kinetic energy which implies no work is done by you. This is a pretty good way to get a hang of what work is. On the other hand, in the equation $dW=F.dx$, we are considering an infinitesimal displacement for a constant force. Work is being done here as we have a force and a displacement. If we have a variable force, we will have to break our procedure of calculating work into infinitesimal displacements for which force can be assumed constant. $$W=\int\vec{F}.\vec{dx}=\int\vec{|F|}\vec{|dx|}\cos\theta$$
$F(x,t)$ can always be expressed as a function of position (and time); however, it is generally *wrong* to write position as a function of force (as well as, $x(F)$ will fail to describe how nature works.) To see why: considering an object being acted by a constant force, such a function is always *multi-valued*, it is so *ill-defined* that the input is always same, while the output is always different. Hence this $x(F)$ fails to predict the motion of the object at any given moment. Now, let's see how it is wrong with physics: suppose we manage to find the *area* below the $\int x(F,t)dF$. Hence we know the "work done". However, the area below an object under constant force is *zero*, as it is a vertical straight line, but it is plainly *wrong*! The object is accelerating; therefore, something must keep inputing energy to the object! The work done can't be zero! All in all, mathematically, "$x\,dF$" is ill-defined. Physically, it describes the physics so wrong.
48,147,071
I would like to **compare different CRM products** [SAP Hybris (C4C) vs. Salesforce] in my work. I've not yet started because currently I have a very basic problem in understanding the difference between SAP Hybris and SAP Hybris C4C (Cloud for Customer). SAP Hybris is divided into Commerce, Marketing, Revenue, Sales, Service. Unfortunately, I do not quite understand what is exactly summarized under SAP Hybris C4C. Has anyone a exact definition? Furthermore, I am not sure what is better comparable: * Salesforce Vs. SAP Hybris or * Salesforce Vs. SAP Hybris C4C I appreciate every hint.
2018/01/08
[ "https://Stackoverflow.com/questions/48147071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
in `mat-step` use `[stepControl]="formName"` and in `.ts` do validation of the form. Using only `linear` won't help. I was doing wrong. I did not use `[stepControl]`
Using @Hypenate's answer, I just wanted to force the user to stay at the current step while the formGroup (connedted to the current step) is INVALID. So I made a css definition in styles.css: ``` .mat-element-notclickable{ pointer-events: none; cursor: not-allowed; opacity: 0.5; color: #cccccc; } ``` than in **ngOnInit** I just subscribe to the formGroup's statusChange and disable all the steps as needed: ``` ngOnInit() { this.formGroup.statusChanges.subscribe( newStatus => { if( newStatus === 'VALID') { Array.from(document.getElementsByClassName('mat-step-header')).forEach(element => { element.classList.remove('mat-element-notclickable') }); } else { Array.from(document.getElementsByClassName('mat-step-header')).forEach(element => { element.classList.add('mat-element-notclickable') }) } }) } ``` (of course, you could just use the header container, and use only one .classList.add and remove, but in other places I will need to enable/disable steps separately)
70,816,463
I have 3 different types of items, which i have interfaces of ``` interface TypeA{ name: string; } interface TypeB{ count: number; } interface TypeC{ date: Date; } ``` This items should be rendered in a list of items (in a list all items are from the same type). Depending on the type of the item, a different method is called, which will render different layouts. ``` export const ListItem: React.FC<ListItemProps> = (props) => { let item = null; switch (props.type) { case "A": item = renderTypeA(props); break; case "B": item = renderTypeB(props); break; case "C": item = renderTypeC(props); break; } return item; }; ``` The method should accept just items from the desired type. ``` const renderTypeA = (props: TypeAProps) => { {...} }; ``` The problem is that I can't get Typescript to recognize all properties of the types and also only auto-complete the respective types. I have also tried it with a union type "ListItemTypes", ``` type ListItemTypes = TypeA | TypeB | TypeC export const ListItem: React.FC<ListItemTypes> = (props) => { ... }; ``` but when I then try to include the ListItem, I always get an error that properties are missing. ``` <ListItem {...item /> <--- is telling me that properties are missing ``` Does anyone know how I can fix this problem? [Example](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wG4Aoc4AOxiSk3STgBUBPMJAQTgG9y4cGByQAuOACIuEioOooQYuAGcYUGgHMKAX0o06DJqxEAhPgKEjxEkzItoIAV1rjqjkACN6OvbXqM0ZnZOAGFzQWFOaxC7QQATFDpxABFEpB9yB2pVOCJqOPpg7jgAXjgACjAcMGVxIq4ASlKAPnDcpBhHKGo4AB5lMBRqZvregHoBoeadCkyIbPg8gqgiszLK6trjThMmktb%20QSJO7r7J4dXx8%20nybVmsnKXCkTD1qogaupe9g4tjrp6-UGFxeV2BNzulEizAAMsBVABJOggIrKUrbYoAHwxZmxRRCsyQAA9ILA4A94HDEcjxMh0DAAHQAMRCvSpMCRSBRImUrTemx%20bQANh04MBkei3EKhbIVAB3cVoAAWFXeNQZ0Kah0E5JQymYUgkogsOrFErKTxWIi4Gw%20ygastNHiIKAA1o7dfrJLZjabBOKuejLatbTUHSadc7UO6I2g9QaYr6-QG8BakPlnqFQ-aPYIo27Zbojh0AWauTNKBT2hmoJzUxVBdqq8oFGARakYCh0QBtCPa03Q6zSAA0EcEDmcMHEAEYAEyj03aBdwAC6sv%20pzZ8I5Et4DP3LfA7cSKG0cDGEIoQA)
2022/01/22
[ "https://Stackoverflow.com/questions/70816463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4789317/" ]
I checked your code, it's throwing errors because you're destructuring an array into your component. In your code ``` const renderItem = () => { const sampleData = [ { type: "A", count: 12, }, ]; // incorrectly destructuring sampleData here return <ListItem {...sampleData} />; }; ``` You should be able to achieve the expected result with this instead: ``` const renderItemA = () => { const sampleData = { type: "A" as const, // notice const assertion here name: "name" }; return <ListItem {...sampleData} />; }; ``` Because you defined `type` as literal type, you need [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) so that > > no literal types in that expression should be widened (e.g. no going from "hello" to string) > > > [Playground link](https://www.typescriptlang.org/play?ssl=55&ssc=1&pln=48&pc=1#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4Aoc4AOxiSk3STgBUBPMJAQTgG9y4cGByQAuAlzIC41FCDFwAzjCg0A5hQC%20lGnQZNWIgEJ9pwzuPxGpgtBACutcdXsgARvS07a9RmmbsnADCpoLmCvhBNnAAJih04gAi8Uhe5HbUynBE1DH0gdxwALxwABRgOGCK4gVcAJTFAHyh2Ugw9lDUcAA8imAo1I213QD0fQONWhTpEJnwOXlQBSYl5ZXVhpxGDUXN-IJE7Z0944PLo6eT5JrTGVkL%20SIhqxUQVTVPO3vShx1dvf0zk8LoCrjdKOE4AAZYDKACSdBABUUxU2hQAPmiTJiCkFpkgAB6QWBwO7wGHwxHiZDoGAAOgAYkFuhSYAikEiRIpmi91l8WgAbNpwYCI1EuAUCiiCRQAd1FaAAFmVXlU6eEGvtBKSUIpmPhJKJpNqRWKSg8liIuGs3oo6tKTXA3EQUABrB22XX66xGx2mjmoi3LG1Ve3G7XO1Du8NoL0EKK%20x2igPmpC5R7BEN2j0Rl3RwTaA5tP7%20kBTShk1rpqDskA8Vb8rWVxRyMBC5IwFCorVhESWSRwXWk2bKAA04dk8ksk6Q%20Gk4KLR3%20rNrfDp65b4Hb8RQmjgIzBtxH8zTi1rKzKjekzdb2873fD4Us1kHKLJ45NdkcMHEAEYAEzzg6vzHCysJsmKvDrnSm5tkgHa7vuh4VseVZnoizyXk0LQ3lu8E7g%20JpPvG%20CvsOcwftqcQJDISCynAHZIKUdRAT8xagSukHQbBd6IQeUxAA)
Here is a minimal example of discriminated union usage: ``` interface TypeA { type: "A"; name: string; } interface TypeB { type:"B"; count: number; } export const ListItem = (props: TypeA | TypeB) => { let item = null; switch (props.type) { case "A": item = renderTypeA(props); // TS know this must be TypeA in this block break; case "B": item = renderTypeB(props); break; } return item; }; const renderTypeA = (props: TypeA) => { props.name; // No error }; const renderTypeB = (props: TypeB) => { props.name; // Error }; // Update: const renderItem = () => { const sampleData: Array<ListItemTypes> = [ { type: "A", count: 12, // This doesn't follow your ListItemTypes shape }, ]; // ListItem requires an object, not a list of objects return sampleData.map(sd => <ListItem {...sd} />); }; ```
9,547,670
It has been estimated that a specific social network site has the following number of users per month. ``` F(n)= F(n-1)*120% + 100*n where F(0)=0 ``` this means that every month 100 new users are added because of advertisement and 20% more users are added per month due to users inviting people the the social network. Also on the first month there are no users. Anyways if we plug in numbers to this recursion we will get: ``` F(0)=0 F(1)=F(0)*1.2 + 100*1=100 F(2)=F(1)*1.2 + 100*2=320 F(3)=F(2)*1.2 + 100*3=684 F(4)=F(3)*1.2 + 100*4=1220.8 F(5)=F(4)*1.2 + 100*5=1964.96 .... ``` Anyways I have answer the first part of that question. Now I am stuck in solving that recursive relation. I need to find an equation that will solve the recurrence relation. In other words a function that if I where to pass the number 2 then it will output 320 for example without having to call itself. **The answer is actually:** ![enter image description here](https://i.stack.imgur.com/wyprJ.png) I don't understand how to get to that solution. I got that answer from [HERE](http://www.wolframalpha.com/input/?i=F%28n%29=%28F%28n-1%29*%2812/10%29%29%2b%28100*n%29%20,F%280%29=0). I will like to understand how to solve it not just get the solution.
2012/03/03
[ "https://Stackoverflow.com/questions/9547670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637142/" ]
Mathematical View ================= instead of 1.2 I'll use `a` and instead of 100 I'll use `b` (a>1,b!=0): ``` F(n) = aF(n-1) + bn ==> F(n) = a (aF(n-2) + bn) + bn = a^2 F(n-2) + ab(n-1)+bn = a^3F(n-2) + a^2 * b * (n-2)+a*b*(n-1)+b*n=... = a^n F(0) + a^(n-1) * b * (n-(n-1)) + .... + bn = 0 + a^(n-1)* nb + a^(n-2)* (n-1)b + ... + a^0 *1*b - [a^(n-1)* (n-1)b + a^(n-2) * (n-2)b + ... + 0) ``` if we write: ``` A = a^(n-1)* nb + a^(n-2)* (n-1)b + ... + a^0 *1*b B = a^(n-1)* (n-1)b + a^(n-2) * (n-2)b + ... ``` You need to find `A-B`. then ``` A = b (a^n + a^n-1 + a^n-2 + ....)' B = b/a * (a^(n-1)+....)' - a ``` and if we let `C = a^n + a^n-1 + a^n-2 + ....` we know `C = (a^(n+1) - a)/(a - 1)` and simply you can calculate C' and finally you can calculate A and B and their difference `A - B`. Algorithmic and real working view ================================= But if I want to talk in context of algorithms, I'm care about `O` and Θ and Ω , ... not about exact running time. So when I see your algorithm I say It's Θ(an) without any calculation, because if you replace bn with 1, it doesn't affect your Θ notation because your function grows exponentially so removing some constant or polynomial functions (without converting them to zero) doesn't change exponential running time, and It just removes some polynomial function from final result. So in this cases I never try solid maths. I'll use solid math in writing academic papers or exams not in real life.
``` f(n)=af(n-1)+bn =a[af(n-2)+b(n-1)+b(n-1)]=a^2f(n-2)+(a+1)b(n-1) -ab ``` in general f(n) =a^n \* x + n\*y+z now f(1)=a\*x+y+z=1 f(2)=(a^2)\* x+2y+z= f(3)=... We can sole this linear system to get x,y ,z
23,519,091
Using Silverlight 5, RIA services 1.0 and Telerik controls I have a dialog with a button that when clicked goes and runs some service code. The issue is when I double click or triple click it real fast, it keeps calling the service thus getting this error: ``` System.InvalidOperationException: System.InvalidOperationException: A SubmitChanges operation is already in progress on this DomainContext. ``` I was wondering if this is a common error and any work around for it? Here is the .NET source code that it goes to that causes it to crash: ``` public virtual SubmitOperation SubmitChanges(Action<SubmitOperation> callback, object userState) { if (this.IsSubmitting) throw new InvalidOperationException(Resource.DomainContext_SubmitAlreadyInProgress); ```
2014/05/07
[ "https://Stackoverflow.com/questions/23519091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is not an error. A submitChange operation is asynchronous so you have to detect that it is completed before doing something else. One solution could be to block the user from clicking on the button before the operation is completed. Since you are using a Telerik controls, you can use a busy indicator. ``` private void btnUserAction_Click(object sender, RoutedEventArgs e) { myBusyIndicator.IsBusy = true; // DO your stuff var submitOperation = myContext.SubmitChanges(); submitOperation.Completed += (s, e) => { // It is completed, now the user can click on the button again myBusyIndicator.IsBusy = false; } } ``` EDIT : The busy indicator should be defined in your Xaml, like this : ``` <Telerik:RadBusyIndicator x:Name="myBusyIndicator"> <Grid x:Name="LayoutRoot" > <Button Name="btnUserAction" Click="btnUserAction_Click" /> </Grid> </Telerik:RadBusyIndicator> ```
We had same problem, and had to change from sending a command to the viewmodel to having a bit of code behind for button click ... ``` /// <summary> /// Workaround for handling double-click from the Map Results button - trying to prevent running the query twice and adding duplicate layers into the Layer Control /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MapResultsButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 1) this.ViewModel.MapResultsCommand.Execute(null); } ``` As you can see, this uses a `ClickCount` property which is part of the `MouseButtonEventArgs` Once the command has reached the viewmodel we can then worry about busy indicators and other ways of disabling the button.
1,416,111
I think about starting from scratch building a small application fullfilling two technical requirements: * should be usable on iPhone * should work offline There are two obvious alternatives here to choose between * A real iPhone application with offline capabilities * A web app using HTML5 offline, Google Gears or similar Having no iPhone app development experience (I don't own an iPhone), i wonder which way would be the easiest to go? What are the learning curves for building offline HTML vs building an iPhone app?
2009/09/12
[ "https://Stackoverflow.com/questions/1416111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109305/" ]
Honestly, it depends what your app is going to do. MobileSafari supports all the HTML5 offline stuff, so you could store data in a clientside SQL database, cache the application clientside, etc... The mobile Gmail app is probably the most notable example of that, giving you full-featured access to your Gmail even when offline. You can also use geolocation through JavaScript APIs that were added in 3.0. Web Clips let your web app share the home screen with native applications too. There is more on using web apps on the iPhone on [this Stack Overflow post](https://stackoverflow.com/questions/1140105/iphone-web-apps-running-as-native-apps). Obviously, doing a Web app will be of interest to people who like dealing with HTML, CSS, and JavaScript (and possibly whatever language is running server-side). It is possible to do really neat stuff with offline Web apps, but its performance won't be as good as that of native apps, especially on pre-3GS devices. Developing a native application will require you to learn Objective-C (or C# as soon as Mono Touch is available to the masses) and pay a $99 fee to be allowed to test on-device and deploy to App Store. A lot more of the system is exposed to you through the various APIs, such as the camera, compass, multitouch, and so on. Objective-C is pretty simple to pick up if you're familiar with Java; you only really need to get used to the square bracket syntax and memory management and then it's pretty straight-forward. Then there are the hybrid systems, like [PhoneGap](http://phonegap.com/), which expose more of the device's APIs, provided the Web app runs in a special container app. It is also crossplatform, so you could also deploy the app on Android and BlackBerry if you wanted to. This still requires you to pay the App Store fee, but if you're more familiar with Web development, this gives you the best of both worlds.
I can't tell you too much about HTML apps in general, but I can tell you that [the API](http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html) for the `UIWebView` is extremely minimal, and of course there is much less you can do than in a native iPhone application.
60,724,667
I'm learning RTOS on stm32F411RE board (Cortex-M4). I use MDK uVision v5. I encounter a problem of C code **while loop**. The code in the following is exactly the same in my project and the instructor's project (on Udemy), however, after compiling both project (on my PC), the assembly code look's different. I want to ask what makes this different. Thank you. ``` void osSignalWait(int32_t *semaphore) { __disable_irq(); while(*semaphore <=0) { __disable_irq(); __enable_irq(); } *semaphore -= 0x01; __enable_irq(); } ``` In the debug view (see image), if the condition does not match, it does not go to load the real value **LDR r1,[r0, #0x00]** and then do the comparison. Instead, it compares and goes to execute the command inside the while loop. [![My code compiled debug view](https://i.stack.imgur.com/cul11.png)](https://i.stack.imgur.com/cul11.png) My code compiled below ``` 100: void osSignalWait(int32_t *semaphore) 101: { 0x08001566 4770 BX lr 102: __disable_irq(); 103: while(*semaphore <=0) 104: { 0x08001568 B672 CPSID I 101: { 102: __disable_irq(); 103: while(*semaphore <=0) 104: { 0x0800156A 6801 LDR r1,[r0,#0x00] 0x0800156C E001 B 0x08001572 105: __disable_irq(); 0x0800156E B672 CPSID I 106: __enable_irq(); 107: } 108: *semaphore -= 0x01; 0x08001570 B662 CPSIE I 0x08001572 2900 CMP r1,#0x00 0x08001574 DDFB BLE 0x0800156E 0x08001576 1E49 SUBS r1,r1,#1 109: __enable_irq(); 0x08001578 6001 STR r1,[r0,#0x00] 0x0800157A B662 CPSIE I 110: } ``` If I compile the instructor's (on Udemy) code (on my PC using his project), the assembly code look's different ( with exactly the same while loop code). It would load the real value again and do the comparison. [![Instructor's code compiled debug view](https://i.stack.imgur.com/bYtxw.jpg)](https://i.stack.imgur.com/bYtxw.jpg) Instructor's code compiled below (Compiled on my PC) ``` 100: void osSignalWait(int32_t *semaphore) 101: { 0x08000CDE 4770 BX lr 102: __disable_irq(); 0x08000CE0 B672 CPSID I 103: while(*semaphore <=0) 104: { 0x08000CE2 E001 B 0x08000CE8 105: __disable_irq(); 0x08000CE4 B672 CPSID I 106: __enable_irq(); 107: } 0x08000CE6 B662 CPSIE I 0x08000CE8 6801 LDR r1,[r0,#0x00] 0x08000CEA 2900 CMP r1,#0x00 0x08000CEC DDFA BLE 0x08000CE4 108: *semaphore -= 0x01; 0x08000CEE 6801 LDR r1,[r0,#0x00] 0x08000CF0 1E49 SUBS r1,r1,#1 0x08000CF2 6001 STR r1,[r0,#0x00] 109: __enable_irq(); 110: 111: 0x08000CF4 B662 CPSIE I 112: } ```
2020/03/17
[ "https://Stackoverflow.com/questions/60724667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7897452/" ]
Since you aren't telling the compiler `semaphore` can change during the execution of this function, your compiler has decided to optimize your code and load the value of semaphore only once and use its copy in the while loop, then only write the result in the end. As it is written now, there's no reason for the compiler to assume this could be harmful. To notify the compiler a variable *can* change outside the function, during the execution of that function, please use the `volatile` keyword, see: <https://en.cppreference.com/w/c/language/volatile> In that case, your code would become: ``` void osSignalWait(volatile int32_t *semaphore) { __disable_irq(); while(*semaphore <=0) { __disable_irq(); // Note: I think the order is wrong... __enable_irq(); } *semaphore -= 0x01; __enable_irq(); } ``` By the way, calling `__disable_irq` twice (once before the while loop, then at the start inside the loop) then `__enable_irq` seems a bit wonky, don't you mean enable (and do something) then disable within the while loop?
This very well known keil over optimisation bug. Reported many times. Having memory clobber it should read the memory every time. Here is an example how clobbers work ``` #include <stdint.h> unsigned x; volatile unsigned y; int foo() { while(x < 1000); } int bar() { while(x < 1000) asm("":::"memory"); } ``` ``` foo: ldr r3, .L5 ldr r3, [r3] cmp r3, #1000 bxcs lr .L3: b .L3 .L5: .word x bar: ldr r1, .L11 ldr r2, .L11+4 ldr r3, [r1] cmp r3, r2 bxhi lr .L9: ldr r3, [r1] cmp r3, r2 bls .L9 bx lr .L11: .word x .word 999 ```
7,916,871
I want to kill a process using inno setup.i want to check whether the window is open before i start installing the setup. can i do this by searching windows name? please help me with some sample code to kill the process
2011/10/27
[ "https://Stackoverflow.com/questions/7916871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000471/" ]
The best option is to use a mutex to see if it's still running using `AppMutex`. One way to close it is to find the window handle then just post a simple WM\_CLOSE message. There are other options like the [Files in use extension](http://www.vincenzo.net/isxkb/index.php?title=Files_in_use_extension) and [PSVince](http://www.vincenzo.net/isxkb/index.php?title=Call_psvince.dll_on_install_and_uninstall) Also see [this article](http://www.vincenzo.net/isxkb/index.php?title=Detect_if_an_application_is_running) for a bit more information.
A less complicated method would be to run a [batch file](http://www.jrsoftware.org/iskb.php?runbatchfile) which uses task kill ie: if you wanted to kill notepad before uninstalling ``` taskkill /IM notepad.exe ```
29,952
[The *Rama*, *Orach Chayim* 553](http://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%AA%D7%A7%D7%A0%D7%92), says: > > The practice is that we do not study [Torah] the day before [the ninth of *Av*](http://en.wikipedia.org/wiki/Tisha_B%27Av) from midday on, except such matters as are permitted [study material] on the ninth…. Also, one should not go on a pleasure trip on the day before the ninth of *Av*. > > > (*Mishna B'rura* comments that others condemn the practice of avoiding Torah study on the eighth, but my question is about the practice to forbid it.) Many practices are forbidden or frowned upon on the ninth: five main abstentions (eating, washing oneself, anointing oneself, marital relations, and wearing leather shoes), sitting on a chair, Torah study, greeting people with a blessing, conducting business, going on a pleasure trip. Why are Torah study and trips singled out as the two things extended to the eighth? I understand that a ban on eating is not extended: that's too difficult, even dangerous. But sitting on a chair? marital relations? greeting people? Why not? What's special about Torah study and trips?
2013/07/15
[ "https://judaism.stackexchange.com/questions/29952", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/170/" ]
These two activities continue to bring pleasure to the person even after they are done. If a person learned properly, he would continue thinking about what he had learned. So too with a trip, a person would think about his joyful experience and derive pleasure from it.
You are not the only one who was perplexed by this halacha as the MB brings several opinions (GR"A, RaSHaL) that did not accept the Rama's ruling and the Biur Halacha (BH) seems to concur with them. The MB gives a reason that Torah study gladdens the heart, While the Magen Avraham says that since it is possible to learn those topics that are permitted on Tisha B'Av therefore the Rama did not ban torah study in a time when it's permitted. (erev TB) Interesting enough Tiyul is not mentioned in the MB/BH or in the original tshuva from the MaHaril (Shu"T 44). I don't know how it got in there other to say as the BH says that people should not think once learning is forbidden they can take advantage of the time to take a pleasurable stroll.(BH) With all that said allow me to try a "baala batesha pshat" Just like Bedikat Chametz where we are concerned a person will become so engrossed in their learning that they will forget to start the bediaka on time, and there are even opinions that 30 minutes before the zman bedika it is forbidden to learn perhaps here too we were concerned that since torah learning is such an enjoyable experience that a person will become so engrossed in it and not stop when Tisha B'Av starts. Same thing with a pleasure trip. Admittedly this don't pass the MY logic test but as I mentioned since the Maharil himself offered no reason for the issur AND many achronim actually rejected this minhag then we can take some freedoms and consider possible reasons. Also since the only source of the minhag of the Maharil himself then there is no reason to be more machmer than what the MaHaril wrote. sources The Rama, Orach Chayim 553, MB and Sh"uT MaHaril 44
42,555,983
I have created a macro to copy data from one sheet and transpose and paste the data to another sheet as so: ``` Sub sbCopyRangeToAnotherSheet() 'Copy the data Sheets("Raw Data").Range("A4:A27").Copy 'Transpose and paste data to new sheet Sheets("Distinct Users").Range("D6:AA6").PasteSpecial Transpose:=True End Sub ``` I need to do this 31 times and I'm not quite sure how to do this. I assume I need to use the .offset functionality in Range, but I am not sure how to do this... for example, I need to change the initial range I've copied from ("A4:A27") to ("A28:A51") and then change the pasted range to ("D7:AA7"). I thought of creating a variable to define the starting cell, and another variable to define the ending cell of the range and then using offset to increase the offset inside of a loop. My biggest problem is... I'm not sure how to define the starting cell and ending cell for my offset! Also, I'm not sure if I can even do something like : ``` Dim lwrRange1 as Cell = "A4" Dim uprRange1 as Cell = "A27" Dim lwrRange2 as Cell = "D6" Dim uprRange2 as Cell = "AA6" Do While 1 <= 31 'Copy the data Sheets("Raw Data").Range(lwrRange1:uprRange1).Copy 'Transpose and paste data to new sheet Sheets("Distinct Users").Range(lwrRange2:uprRange2).PasteSpecial Transpose:=True lwrRange1 += 24 uprRange1 += 24 lwrRange2 += 1 uprRange2 += 1 i += 1 Loop ``` any help or insight would be greatly appreciated!
2017/03/02
[ "https://Stackoverflow.com/questions/42555983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1819427/" ]
Use Range objects : ``` Dim SrcRg As Range Dim DestRg As Range Set SrcRg = Sheets("Raw Data").Range("A4:A27") Set DestRg = Sheets("Distinct Users").Range("D6") For i = 1 To 31 'Copy the data SrcRg.Copy 'Transpose and paste data to new sheet DestRg.PasteSpecial Transpose:=True Set SrcRg = SrcRg.Offset(SrcRg.Rows.Count, 0) Set DestRg = DestRg.Offset(1, 0) Next i ```
Maybe try using a For loop like so: ``` Sub sbCopyRangeToAnotherSheet() Dim i As Integer Dim rCopy As Range, rPaste As Range Set rPaste = Sheets("Distinct Users").Range("D6:AA6") Set rCopy = Sheets("Raw Data").Range("A4:A27") For i = 0 To 30 'Copy the data rCopy.Offset(rCopy.Rows.Count * i, 0).Copy 'Transpose and paste data to new sheet rPaste.Offset(rPaste.Row + i, 0).PasteSpecial Transpose:=True Next i End Sub ```
5,288,834
I've completed some simple MVVM tutorials, but they were super simplified examples. Here is my problem: I have a model class for a person, which contains some variables (firstname, lastname) and lists (education, workplaces). These lists have their own classes. For simple variables I created one viewmodel which implements INotifyPropertyChanged interface and everything works pretty well. However I don't know how to handle the lists. Should they have seperate viewmodels? Or how can I add these to the existing ViewModel? Thanks in advance!
2011/03/13
[ "https://Stackoverflow.com/questions/5288834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/657391/" ]
If you need to more actions on elements of those collection then you can create separate ViewModels for those classes. Then in general ViewModel you can create ObservableCollection of additional ViewModels. Pseudo code: ``` public class PersonViewModel { public ObservableCollection<EducationViewModel> Education { get; set; } public ObservableCollection<WorkplaceViewModel> Workplaces { get; set; } } ```
For starters, implementing the list as an `ObservableCollection` on your ViewModel will work fine. There's an [example on MSDN](http://msdn.microsoft.com/en-us/library/ms748365.aspx) to get you started; there are tons of tutorials around too.
203,927
I created a 2010 workflow in SPD 2013 on development machine. Once it was time to go live, I took site collection back up from development and restored it on production so my workflow as well as all InfoPath 2013 forms were moved. Now I have made several changes in workflow as well as forms on development machine. What is the best way to move both workflow and forms to production?
2017/01/02
[ "https://sharepoint.stackexchange.com/questions/203927", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/15263/" ]
Access token expires in 12hrs by default in high-trust (when using `TokenHelper.cs`). Session in 20min, but in that case `SharePointContext.cs` should renew it. May be your custom logic affects this somehow. My guess - try to adjust session expiration time to one hour for example (`web.config`): ``` <configuration> <system.web> <sessionState timeout="60"></sessionState> </system.web> </configuration> ``` **UPD** Looking at the modified `SharePointContext.cs` it seems I found exact reason for your issue. Take a look at the line `1178` in `SharePointContext.cs`: ``` DateTime.UtcNow.AddMinutes(10) ``` Your *user+add-in* token lifetime is only 10 minutes (besides your *add-in only* token, line `1150` is good). Put here `TokenLifetimeMinutes` instead of `10` and I think you are good to go.
Try to increase your token cache limit and token lifetime. ``` $sts = Get-SPSecurityTokenServiceConfig $sts.CookieLifetime = New-TimeSpan -Minutes 600 $sts.WindowsTokenLifetime = New-TimeSpan -Minutes 600 $sts.MaxApplicationTokenCacheItems = 100000 $sts.MaxLogonTokenCacheItems = 100000 $sts.MaxServiceTokenCacheItems = 100000 $sts.Update() ``` Make sure that you document what these values are before you change them and [research each value](https://technet.microsoft.com/en-us/library/ff607549.aspx) to understand what they are and what changing the value means to your environment. When I changed these values, it took about a day to take hold. I assume the old values are cached but don't know how to force the cache to clear.