id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
29,225,834
Where are variables in a closure stored - stack or heap?
<p>Like the following codes:</p> <pre><code>var foo = function() { var a = 1; // closure var return function() { // closure fun console.log(a); } }; var bar = foo(); </code></pre> <p>When foo exits(or say, returns), we know that the variable a will not be destroyed and remains in memory(that's why closure works). So my problem is where does the the variable a store, stack or heap?</p>
29,226,388
1
0
null
2015-03-24 05:48:31.94 UTC
11
2021-06-15 09:57:08.71 UTC
2021-06-15 09:57:08.71 UTC
null
5,459,839
null
3,428,531
null
1
23
javascript|closures|heap-memory|stack-memory
4,221
<p>A closure is just an evolution of the concept of the stack.</p> <p>The stack is used to separate/isolate scope when functions are called. When a function returns the stack frame (activation record) is popped off the call stack thus freeing the used memory allowing the next function call to reuse that RAM for its stack frame.</p> <p>What a closure does is that instead of actually freeing that stack frame, if there's any object/variable in that stack frame that's referenced by anything else then it keeps that stack frame for future use.</p> <p>Most languages implement this by implementing the stack as a linked list or hash table instead of a flat array. That way, the stack can be re-ordered at runtime and is not constrained by physical memory layout.</p> <p>So. With this in mind, the answer is that variables in a closure are stored in the stack and heap. Depending on your point of view.</p> <p>From the point of view of the language, it's definitely the stack. Since that's what closures are in theory - a modified stack.</p> <p>From the point of view of the machine language or underlying C/assembly code, the idea of a linked-list stack is nonsense. Therefore the higher level language must be using the heap to implement its "stack".</p> <p>So the variable is in the stack but that stack is probably located in the heap.</p> <p>This of course depends on the implementation of your programming language. But the above description is valid for most javascript interpreters (certainly all the ones I've seen).</p>
31,819,375
Inject mock into Spring MockMvc WebApplicationContext
<p>I'm working to test (via JUnit4 and Spring MockMvc) a REST service adapter using Spring-boot. The adapter simply passes along requests made to it, to another REST service (using a custom <code>RestTemplate</code>) and appends additional data to the responses.</p> <p>I'd like to run <code>MockMvc</code> tests to perform controller integration tests, but want to override the <code>RestTemplate</code> in the controller with a mock to allow me to predefine the 3rd party REST response and prevent it from being hit during each test. I've been able to accomplish this by instantiating a <code>MockMvcBuilders.standAloneSetup()</code> and passing it the controller to be tested with the mock injected as listed in this <a href="https://stackoverflow.com/questions/16170572/unable-to-mock-service-class-in-spring-mvc-controller-tests">post</a> (and my setup below), however I am not able to do the same using <code>MockMvcBuilders.webAppContextSetup()</code>.</p> <p>I've been through a few other posts, none of which answer the question as to how this might be accomplished. I would like to use the actual Spring application context for the tests instead of a standalone to prevent any gaps as the application is likely to grow.</p> <p>EDIT: I am using Mockito as my mocking framework and am trying to inject one of its mocks into the context. If this isn't necessary, all the better.</p> <p>Controller:</p> <pre><code>@RestController @RequestMapping(Constants.REQUEST_MAPPING_PATH) public class Controller{ @Autowired private DataProvider dp; @Autowired private RestTemplate template; @RequestMapping(value = Constants.REQUEST_MAPPING_RESOURCE, method = RequestMethod.GET) public Response getResponse( @RequestParam(required = true) String data, @RequestParam(required = false, defaultValue = "80") String minScore ) throws Exception { Response resp = new Response(); // Set the request params from the client request Map&lt;String, String&gt; parameters = new HashMap&lt;String, String&gt;(); parameters.put(Constants.PARAM_DATA, data); parameters.put(Constants.PARAM_FORMAT, Constants.PARAMS_FORMAT.JSON); resp = template.getForObject(Constants.RESTDATAPROVIDER_URL, Response.class, parameters); if(resp.getError() == null){ resp.filterScoreLessThan(new BigDecimal(minScore)); new DataHandler(dp).populateData(resp.getData()); } return resp; } } </code></pre> <p>Test class:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringApplicationConfiguration(classes = MainSpringBootAdapter.class) @TestPropertySource("/application-junit.properties") public class WacControllerTest { private static String controllerURL = Constants.REQUEST_MAPPING_PATH + Constants.REQUEST_MAPPING_RESOURCE + compressedParams_all; private static String compressedParams_all = "?data={data}&amp;minScore={minScore}"; @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @InjectMocks private Controller Controller; @Mock private RestTemplate rt; @Value("${file}") private String file; @Spy private DataProvider dp; @Before public void setup() throws Exception { dp = new DataProvider(file); MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test public void testGetResponse() throws Exception { String[] strings = {"requestData", "100"}; Mockito.when( rt.getForObject(Mockito.&lt;String&gt; any(), Mockito.&lt;Class&lt;Object&gt;&gt; any(), Mockito.&lt;Map&lt;String, ?&gt;&gt; any())) .thenReturn(populateTestResponse()); mockMvc.perform(get(controllerURL, strings) .accept(Constants.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultHandlers.print()); Mockito.verify(rt, Mockito.times(1)).getForObject(Mockito.&lt;String&gt; any(), Mockito.&lt;Class&lt;?&gt;&gt; any(), Mockito.&lt;Map&lt;String, ?&gt;&gt; any()); } private Response populateTestResponse() { Response resp = new Response(); resp.setScore(new BigDecimal(100)); resp.setData("Some Data"); return resp; } } </code></pre>
31,826,974
3
0
null
2015-08-04 21:08:48.063 UTC
11
2020-02-12 08:23:25.28 UTC
2017-05-23 12:26:31.28 UTC
null
-1
null
4,555,594
null
1
18
java|spring-boot|mockito|integration-testing|junit4
41,645
<p>Spring's <code>MockRestServiceServer</code> is exactly what you're looking for. </p> <p>Short description from javadoc of the class:</p> <blockquote> <p>Main entry point for client-side REST testing. Used for tests that involve direct or indirect (through client code) use of the RestTemplate. Provides a way to set up fine-grained expectations on the requests that will be performed through the RestTemplate and a way to define the responses to send back removing the need for an actual running server.</p> </blockquote> <p>Try to set up your test like this:</p> <pre><code>@WebAppConfiguration @ContextConfiguration(classes = {YourSpringConfig.class}) @RunWith(SpringJUnit4ClassRunner.class) public class ExampleResourceTest { private MockMvc mockMvc; private MockRestServiceServer mockRestServiceServer; @Autowired private WebApplicationContext wac; @Autowired private RestOperations restOperations; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); mockRestServiceServer = MockRestServiceServer.createServer((RestTemplate) restOperations); } @Test public void testMyApiCall() throws Exception { // Following line verifies that our code behind /api/my/endpoint made a REST PUT // with expected parameters to remote service successfully expectRestCallSuccess(); this.mockMvc.perform(MockMvcRequestBuilders.get("/api/my/endpoint")) .andExpect(status().isOk()); } private void expectRestCallSuccess() { mockRestServiceServer.expect( requestTo("http://remote.rest.service/api/resource")) .andExpect(method(PUT)) .andRespond(withSuccess("{\"message\": \"hello\"}", APPLICATION_JSON)); } } </code></pre>
56,612,042
How to fix "mapping values are not allowed in this context " error in yaml file?
<p>I've browsed similar questions and believe i've applied all that i've been able to glean from answers.</p> <p>I have a .yml file where as far as I can tell each element is formatted identically. And yet according to <a href="http://www.yamllint.com/" rel="noreferrer">YamlLint.com</a> </p> <p><code>(&lt;unknown&gt;): mapping values are not allowed in this context at line 119 column 16</code></p> <p>In this case, line 119 is the line containing the second instance the word "transitions" below. That I can tell each element is formatted identically. Am I missing something here? </p> <pre><code> landingPage: include: false transitions: - condition:location nextState:location location: include:false transitions: - condition:excluded nextState:excluded excluded: include:false transitions: - condition:excluded nextState: excluded - condition:age nextState:age </code></pre>
56,612,181
8
0
null
2019-06-15 16:09:59.573 UTC
6
2022-05-31 21:11:19.57 UTC
null
null
null
null
4,630,594
null
1
47
web-scraping|yaml
162,759
<p>You cannot have a multiline plain scalar, such as your <code>include:false transitions</code> be the key to a mapping, that is why you get the mapping values not allowed in this context error.</p> <p>Either you forgot that you have to have a space after the value indicator (<code>:</code>), and you meant to do:</p> <pre><code> include: false transitions: </code></pre> <p>or you need to quote your multi-line scalar:</p> <pre><code> 'include:false transitions': </code></pre> <p>or you need to put that plain scalar on one line:</p> <pre><code> include:false transitions: </code></pre> <p>please note that some libraries do not allow value indicators in a plain scalar at all, even if they are not followed by space</p>
51,150,193
Angular Material editable table using FormArray
<p>I'm trying to build an inline editable table using the latest material+cdk for angular. </p> <h1>Question</h1> <blockquote> <p>How can I make mat-table use <code>[formGroupName]</code> so that the form fields can be referenced by its correct form path?</p> </blockquote> <p>This is what I got so far: <strong><a href="https://stackblitz.com/edit/angular-material-editable-table?file=src%2Fapp%2Fapp.component.ts" rel="noreferrer">Complete StackBlitz example</a></strong></p> <p><strong>Template</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;form [formGroup]="form"&gt; &lt;h1&gt;Works&lt;/h1&gt; &lt;div formArrayName="dates" *ngFor="let date of rows.controls; let i = index;"&gt; &lt;div [formGroupName]="i"&gt; &lt;input type="date" formControlName="from" placeholder="From date"&gt; &lt;input type="date" formControlName="to" placeholder="To date"&gt; &lt;/div&gt; &lt;/div&gt; &lt;h1&gt;Wont work&lt;/h1&gt; &lt;table mat-table [dataSource]="dataSource" formArrayName="dates"&gt; &lt;!-- Row definitions --&gt; &lt;tr mat-header-row *matHeaderRowDef="displayColumns"&gt;&lt;/tr&gt; &lt;tr mat-row *matRowDef="let row; let i = index; columns: displayColumns;" [formGroupName]="i"&gt;&lt;/tr&gt; &lt;!-- Column definitions --&gt; &lt;ng-container matColumnDef="from"&gt; &lt;th mat-header-cell *matHeaderCellDef&gt; From &lt;/th&gt; &lt;td mat-cell *matCellDef="let row"&gt; &lt;input type="date" formControlName="from" placeholder="From date"&gt; &lt;/td&gt; &lt;/ng-container&gt; &lt;ng-container matColumnDef="to"&gt; &lt;th mat-header-cell *matHeaderCellDef&gt; To &lt;/th&gt; &lt;td mat-cell *matCellDef="let row"&gt; &lt;input type="date" formControlName="to" placeholder="To date"&gt; &lt;/td&gt; &lt;/ng-container&gt; &lt;/table&gt; &lt;button type="button" (click)="addRow()"&gt;Add row&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>Component</strong></p> <pre class="lang-ts prettyprint-override"><code>export class AppComponent implements OnInit { data: TableData[] = [ { from: new Date(), to: new Date() } ]; dataSource = new BehaviorSubject&lt;AbstractControl[]&gt;([]); displayColumns = ['from', 'to']; rows: FormArray = this.fb.array([]); form: FormGroup = this.fb.group({ 'dates': this.rows }); constructor(private fb: FormBuilder) { } ngOnInit() { this.data.forEach((d: TableData) =&gt; this.addRow(d, false)); this.updateView(); } emptyTable() { while (this.rows.length !== 0) { this.rows.removeAt(0); } } addRow(d?: TableData, noUpdate?: boolean) { const row = this.fb.group({ 'from' : [d &amp;&amp; d.from ? d.from : null, []], 'to' : [d &amp;&amp; d.to ? d.to : null, []] }); this.rows.push(row); if (!noUpdate) { this.updateView(); } } updateView() { this.dataSource.next(this.rows.controls); } } </code></pre> <h1>Problem</h1> <p>This wont work. Console yields </p> <blockquote> <p>ERROR Error: Cannot find control with path: 'dates -> from'</p> </blockquote> <p>It seems as if the <code>[formGroupName]="i"</code> has no effect, cause the path should be <code>dates -&gt; 0 -&gt; from</code> when using a formArray.</p> <p><strong>My current workaround</strong>: For this problem, I've bypassed the internal path lookup (<code>formControlName="from"</code>) and use the form control directly: <code>[formControl]="row.get('from')"</code>, but <strong>I would like to know</strong> how I can (or at least why I cannot) use the Reactive Form preferred way. </p> <p>Any tips are welcome. Thank you.</p> <hr> <p>Since I think this is a bug, I've registered <a href="https://github.com/angular/material2/issues/12217" rel="noreferrer">an issue</a> with the angular/material2 github repo.</p>
51,348,069
5
0
null
2018-07-03 08:42:41.413 UTC
8
2021-06-16 07:55:35.203 UTC
2018-07-15 11:31:17.487 UTC
null
1,119,364
null
1,119,364
null
1
41
angular|angular-material
67,522
<p>I would use the index which we can get within <code>matCellDef</code> binding:</p> <pre><code>*matCellDef=&quot;let row; let index = index&quot; [formGroupName]=&quot;index&quot; </code></pre> <p><strong><a href="https://stackblitz.com/edit/angular-material-editable-table-fazhbc?file=src/app/app.component.html" rel="noreferrer">Forked Stackblitz</a></strong></p> <p>For solving problems with sorting and filtering take a look at this answer <a href="https://stackoverflow.com/questions/64947763/angular-material-table-sorting-with-reactive-formarray/64951005#64951005">Angular Material Table Sorting with reactive formarray</a></p>
5,687,882
What are some good methods to finding a heuristic for the A* algorithm?
<p>You have a map of square tiles where you can move in any of the 8 directions. Given that you have function called <code>cost(tile1, tile2)</code> which tells you the cost of moving from one adjacent tile to another, how do you find a heuristic function h(y, goal) that is both admissible and consistent? Can a method for finding the heuristic be generalized given this setting, or would it be vary differently depending on the <code>cost</code> function? </p>
5,687,914
3
0
null
2011-04-16 16:26:58.337 UTC
4
2011-04-16 16:40:30.76 UTC
null
null
null
null
711,327
null
1
9
algorithm|graph|heuristics|shortest-path|a-star
39,454
<p>Amit's tutorial is one of the best I've seen on A* <a href="http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S7" rel="noreferrer">(Amit's page)</a>. You should find some very useful hint about heuristics on this page .</p> <p>Here is the quote about your problem : </p> <blockquote> <p>On a square grid that allows 8 directions of movement, use Diagonal distance (L∞).</p> </blockquote>
5,630,500
How to send Push Notification to multiple devices?
<p>This is the first time I am using push notification in my App. I have gone through sample applications along with books and I got how to send push notification to a single device. But I am not getting exactly what changes should I do in my program to send push notification to multiple devices. I am using 'PushMeBaby' application for server side coding. Please, help me out.</p>
5,638,338
3
1
null
2011-04-12 04:42:41.323 UTC
14
2019-08-21 09:56:48.12 UTC
2019-08-21 09:56:48.12 UTC
null
7,844,349
null
669,245
null
1
23
iphone|push-notification|apple-push-notifications
37,588
<p>Try this example code and modify for your environment.</p> <pre><code> $apnsHost = '&lt;APNS host&gt;'; $apnsPort = &lt;port num&gt;; $apnsCert = '&lt;cert&gt;'; $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert); $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); $payload['aps'] = array('alert' =&gt; 'some notification', 'badge' =&gt; 0, 'sound' =&gt; 'none'); $payload = json_encode($payload); // Note: $device_tokens_array has list of 5 devices' tokens for($i=0; $i&lt;5; $i++) { $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload; fwrite($apns, $apnsMessage); }?&gt; </code></pre> <p>This article helps verifying drop connection and connection status: <a href="https://stackoverflow.com/questions/2583957/apple-push-notification-sending-high-volumes-of-messages">Apple Push Notification: Sending high volumes of messages</a></p> <p>Other reference links: </p> <p><a href="https://stackoverflow.com/questions/5050363/how-can-i-send-push-notification-to-multiple-devices-in-one-go-in-iphone">How can I send push notification to multiple devices in one go in iPhone?</a> and <a href="https://stackoverflow.com/questions/1642182/how-to-handle-multiple-devices-when-using-push-notification">how to handle multiple devices when using Push Notification?</a></p>
6,009,384
Exception handling in Haskell
<p>I need help to understand the usage of the three Haskell functions</p> <ul> <li>try (<code>Control.Exception.try :: Exception e =&gt; IO a -&gt; IO (Either e a)</code>)</li> <li>catch (<code>Control.Exception.catch :: Exception e =&gt; IO a -&gt; (e -&gt; IO a) -&gt; IO a</code>)</li> <li>handle (<code>Control.Exception.handle :: Exception e =&gt; (e -&gt; IO a) -&gt; IO a -&gt; IO a</code>)</li> </ul> <p>I need to know several things: </p> <ol> <li>When do I use which function?</li> <li>How do I use this function with some simple example?</li> <li>Where is the difference between catch and handle? They have nearly the same signature only with a different order.</li> </ol> <p>I will try to write down my trials and hope you can help me:</p> <p><strong>try</strong></p> <p>I have an example like: </p> <pre><code>x = 5 `div` 0 test = try (print x) :: IO (Either SomeException ()) </code></pre> <p>I have two questions:</p> <ol> <li><p>How can I set a custom error output?</p></li> <li><p>What can i do to set all errors to SomeException so I dont must write the <code>:: IO (Either SomeException())</code></p></li> </ol> <p><strong>catch/try</strong></p> <p>Can you show me a short example with a custom error output?</p>
6,009,807
3
0
null
2011-05-15 15:38:21.303 UTC
39
2015-03-10 19:41:10.703 UTC
2011-05-15 16:50:51.607 UTC
null
98,117
null
751,960
null
1
83
haskell|exception-handling
36,933
<h1>When do I use which function?</h1> <p>Here's the recommendation from the Control.Exception documentation:</p> <ul> <li>If you want to do some cleanup in the event that an exception is raised, use <code>finally</code>, <code>bracket</code> or <code>onException</code>.</li> <li>To recover after an exception and do something else, the best choice is to use one of the <code>try</code> family.</li> <li>... unless you are recovering from an asynchronous exception, in which case use <code>catch</code> or <code>catchJust</code>.</li> </ul> <h1>try :: Exception e => IO a -> IO (Either e a)</h1> <p><code>try</code> takes an <code>IO</code> action to run, and returns an <code>Either</code>. If the computation succeeded, the result is given wrapped in a <code>Right</code> constructor. (Think right as opposed to wrong). If the action threw an exception <em>of the specified type</em>, it is returned in a <code>Left</code> constructor. If the exception was <em>not</em> of the appropriate type, it continues to propagate up the stack. Specifying <code>SomeException</code> as the type will catch all exceptions, which may or may not be a good idea.</p> <p>Note that if you want to catch an exception from a pure computation, you will have to use <code>evaluate</code> to force evaluation within the <code>try</code>.</p> <pre><code>main = do result &lt;- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int) case result of Left ex -&gt; putStrLn $ "Caught exception: " ++ show ex Right val -&gt; putStrLn $ "The answer was: " ++ show val </code></pre> <h1>catch :: Exception e => IO a -> (e -> IO a) -> IO a</h1> <p><code>catch</code> is similar to <code>try</code>. It first tries to run the specified <code>IO</code> action, but if an exception is thrown the handler is given the exception to get an alternative answer.</p> <pre><code>main = catch (print $ 5 `div` 0) handler where handler :: SomeException -&gt; IO () handler ex = putStrLn $ "Caught exception: " ++ show ex </code></pre> <p><strong>However,</strong> there is one important difference. When using <code>catch</code> your handler cannot be interrupted by an asynchroneous exception (i.e. thrown from another thread via <code>throwTo</code>). Attempts to raise an asynchroneous exception will block until your handler has finished running.</p> <p>Note that there is a different <code>catch</code> in the Prelude, so you might want to do <code>import Prelude hiding (catch)</code>.</p> <h1>handle :: Exception e => (e -> IO a) -> IO a -> IO a</h1> <p><code>handle</code> is simply <code>catch</code> with the arguments in the reversed order. Which one to use depends on what makes your code more readable, or which one fits better if you want to use partial application. They are otherwise identical.</p> <h1>tryJust, catchJust and handleJust</h1> <p>Note that <code>try</code>, <code>catch</code> and <code>handle</code> will catch <em>all</em> exceptions of the specified/inferred type. <code>tryJust</code> and friends allow you to specify a selector function which filters out which exceptions you specifically want to handle. For example, all arithmetic errors are of type <code>ArithException</code>. If you only want to catch <code>DivideByZero</code>, you can do:</p> <pre><code>main = do result &lt;- tryJust selectDivByZero (evaluate $ 5 `div` 0) case result of Left what -&gt; putStrLn $ "Division by " ++ what Right val -&gt; putStrLn $ "The answer was: " ++ show val where selectDivByZero :: ArithException -&gt; Maybe String selectDivByZero DivideByZero = Just "zero" selectDivByZero _ = Nothing </code></pre> <hr> <h1>A note on purity</h1> <p>Note that this type of exception handling can only happen in impure code (i.e. the <code>IO</code> monad). If you need to handle errors in pure code, you should look into returning values using <code>Maybe</code> or <code>Either</code> instead (or some other algebraic datatype). This is often preferable as it's more explicit so you always know what can happen where. Monads like <code>Control.Monad.Error</code> makes this type of error handling easier to work with.</p> <hr> <p>See also:</p> <ul> <li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exception.html">Control.Exception</a></li> </ul>
6,008,324
Fade Effect on Link Hover?
<p>on many sites, such as <a href="http://www.clearleft.com" rel="noreferrer">http://www.clearleft.com</a>, you'll notice that when the links are hovered over, they will fade into a different color as opposed to immediately switching, the default action.</p> <p>I assume JavaScript is used to create this effect, does anyone know how?</p>
6,008,409
4
1
null
2011-05-15 12:18:35.533 UTC
51
2017-03-01 17:16:54.077 UTC
2012-12-04 23:59:55.157 UTC
null
5,640
null
734,409
null
1
137
css|hover|fade|effect
399,884
<p>Nowadays people are just using <a href="http://code.tutsplus.com/tutorials/css-fundamentals-css3-transitions--pre-10922" rel="noreferrer">CSS3 transitions</a> because it's a lot easier than <a href="https://github.com/jquery/jquery-color" rel="noreferrer">messing with JS</a>, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.</p> <p>Something like this gets the job done:</p> <pre class="lang-css prettyprint-override"><code>a { color:blue; /* First we need to help some browsers along for this to work. Just because a vendor prefix is there, doesn't mean it will work in a browser made by that vendor either, it's just for future-proofing purposes I guess. */ -o-transition:.5s; -ms-transition:.5s; -moz-transition:.5s; -webkit-transition:.5s; /* ...and now for the proper property */ transition:.5s; } a:hover { color:red; } </code></pre> <p>You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:</p> <pre class="lang-css prettyprint-override"><code>a { color:blue; background:white; -o-transition:color .2s ease-out, background 1s ease-in; -ms-transition:color .2s ease-out, background 1s ease-in; -moz-transition:color .2s ease-out, background 1s ease-in; -webkit-transition:color .2s ease-out, background 1s ease-in; /* ...and now override with proper CSS property */ transition:color .2s ease-out, background 1s ease-in; } a:hover { color:red; background:yellow; } </code></pre> <p><a href="http://jsfiddle.net/Marcel/xejsM/52/" rel="noreferrer">Demo here</a></p>
52,771,328
Plotly chart not showing in Jupyter notebook
<p>I have been trying to solve this issue for hours. I followed the steps on the <a href="https://plot.ly/python/getting-started/#start-plotting-online" rel="noreferrer">Plotly website</a> and the chart still doesn't show in the notebook.</p> <p>This is my code for the plot:</p> <pre><code>colorway = ['#f3cec9', '#e7a4b6', '#cd7eaf', '#a262a9', '#6f4d96', '#3d3b72', '#182844'] data = [ go.Scatter( x = immigration.columns, y = immigration.loc[state], name=state) for state in immigration.index] layout = go.Layout( title='Immigration', yaxis=dict(title='Immigration %'), xaxis=dict(title='Years'), colorway=colorway, font=dict(family='Courier New, monospace', size=18, color='#7f7f7f') ) fig = go.Figure(data=data, layout=layout) iplot(fig) </code></pre> <p>And this is everything I have imported into my notebook:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import init_notebook_mode, iplot init_notebook_mode(connected=True) </code></pre>
52,800,828
7
2
null
2018-10-12 02:25:43.987 UTC
18
2022-06-26 11:48:59.28 UTC
2021-02-05 14:35:16.86 UTC
null
7,109,869
null
10,168,730
null
1
71
python|jupyter-notebook|plotly|jupyter|jupyter-lab
126,341
<p>You need to change <code>init_notebook_mode</code> call and remove <code>connected=True</code>, if you want to work in offline mode.</p> <p>Such that:</p> <pre><code># Import the necessaries libraries import plotly.offline as pyo import plotly.graph_objs as go # Set notebook mode to work in offline pyo.init_notebook_mode() # Create traces trace0 = go.Scatter( x=[1, 2, 3, 4], y=[10, 15, 13, 17] ) trace1 = go.Scatter( x=[1, 2, 3, 4], y=[16, 5, 11, 9] ) # Fill out data with our traces data = [trace0, trace1] # Plot it and save as basic-line.html pyo.iplot(data, filename = 'basic-line') </code></pre> <p>Output should be shown in your jupyter notebook:</p> <p><a href="https://i.stack.imgur.com/q5GLv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q5GLv.png" alt="My example" /></a></p>
34,674,326
Node Express - Storage and retrieval of authentication tokens
<p>I have an Express application setup and need some advice on storing tokens.</p> <p>I am receiving an access token from an OAuth 2 server after authenticating a user account, which I then need to use for subsequent api requests.</p> <p>I want to hide the token value from the client and I believe one way of doing this is to save the token on the server in an encoded cookie so that when further requests are made, these can be routed through middleware and the cookie can then be used for retrieval of the token stored sever side and then used as a header value in the ongoing request to the actual api endpoint.</p> <p>Someone has actually already asked this question - <a href="https://stackoverflow.com/questions/23773408/how-to-store-an-auth-token-in-an-angular-app">How to store an auth token in an Angular app</a> This is exactly the flow I am working with in my application but the answer talks about using an Angular service and I'm not so sure I would want to do this, surely this can all be handled by Express so the client side code doesnt need to know about the token, just any errors the API server returns back.</p> <p>So summary of flow I think I need:</p> <ul> <li>User submits login credentials</li> <li>OAuth 2 server returns access token</li> <li>Token is saved somewhere in Express, keyed by an id of sorts</li> <li>A cookie is generated and sent back in response to the client. Cookie contains token value encoded perhaps? Or maybe the id of token value stored in Express middleware component?</li> <li>Client makes an api request, which Express route middleware picks up. </li> <li>Express checks for presence of cookie and either decodes the token value, or somehow retrieves from storage mechanism server side.</li> <li>Token value is then used as a header between express and final api endpoint</li> </ul> <p>There is probably middleware already out there that handles this kinda thing, I have already seen PassportJS which seems to be the kinda thing I may want to use, but I'm not so sure it handles the OAuth2 token flow on the server I am working against (password grant) and instead seems to be more suited to the redirect login OAuth flow.</p> <p>I surely need somewhere to save the token value in Express, so some form of storage (not in memory I dont think).</p> <p>I am fairly new to Express so would appreciate any suggestions\advice on how to approach this.</p> <p>Thanks</p>
34,952,384
1
2
null
2016-01-08 10:07:19.16 UTC
8
2016-01-22 17:13:37.343 UTC
2017-05-23 10:30:06.87 UTC
null
-1
null
726,965
null
1
8
angularjs|node.js|express|oauth-2.0|access-token
4,799
<p>The most secure way to do this is just as you described:</p> <ul> <li>Get an OAuth token from some third party service (Google, Facebook, whatever).</li> <li>Create a cookie using Express, and store that token in the cookie. Make sure you also set the <code>secure</code> and <code>httpOnly</code> cookie flags when you do this: this ensures the cookie CANNOT BE READ by client-side Javascript code, or over any non-SSL connection.</li> <li>Each time the user makes a request to your site, that cookie can be read by your middleware in Express, and used to make whatever API calls you need to the third party service.</li> </ul> <p>If your service also needs to make asynchronous requests to Google / Facebook / etc. when the user is NOT actively clicking around on your site, you should also store their token in your user database somewhere as well -- this way you can make requests on behalf of the user whenever you need to.</p> <p>I'm the author of <a href="https://github.com/stormpath/express-stormpath" rel="noreferrer">express-stormpath</a>, a Node auth library (similar to Passport), and this is how we do things over there to ensure maximal security!</p>
1,857,465
With sqlalchemy how to dynamically bind to database engine on a per-request basis
<p>I have a Pylons-based web application which connects via <a href="http://www.sqlalchemy.org/" rel="noreferrer">Sqlalchemy</a> (v0.5) to a Postgres database. For security, rather than follow the typical pattern of simple web apps (as seen in just about all tutorials), I'm not using a generic Postgres user (e.g. "webapp") but am requiring that users enter their own Postgres userid and password, and am using that to establish the connection. That means we get the full benefit of Postgres security.</p> <p>Complicating things still further, there are two separate databases to connect to. Although they're currently in the same Postgres cluster, they need to be able to move to separate hosts at a later date.</p> <p>We're using sqlalchemy's <a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html" rel="noreferrer">declarative</a> package, though I can't see that this has any bearing on the matter.</p> <p>Most examples of sqlalchemy show trivial approaches such as setting up the Metadata once, at application startup, with a generic database userid and password, which is used through the web application. This is usually done with Metadata.bind = create_engine(), sometimes even at module-level in the database model files.</p> <p>My question is, how can we defer establishing the connections until the user has logged in, and then (of course) re-use those connections, or re-establish them using the same credentials, for each subsequent request.</p> <p>We have this working -- we think -- but I'm not only not certain of the safety of it, I also think it looks incredibly heavy-weight for the situation.</p> <p>Inside the <code>__call__</code> method of the BaseController we retrieve the userid and password from the web session, call sqlalchemy create_engine() once for each database, then call a routine which calls Session.bind_mapper() repeatedly, once for each table that <em>may</em> be referenced on each of those connections, even though any given request usually references only one or two tables. It looks something like this:</p> <pre><code># in lib/base.py on the BaseController class def __call__(self, environ, start_response): # note: web session contains {'username': XXX, 'password': YYY} url1 = 'postgres://%(username)s:%(password)s@server1/finance' % session url2 = 'postgres://%(username)s:%(password)s@server2/staff' % session finance = create_engine(url1) staff = create_engine(url2) db_configure(staff, finance) # see below ... etc # in another file Session = scoped_session(sessionmaker()) def db_configure(staff, finance): s = Session() from db.finance import Employee, Customer, Invoice for c in [ Employee, Customer, Invoice, ]: s.bind_mapper(c, finance) from db.staff import Project, Hour for c in [ Project, Hour, ]: s.bind_mapper(c, staff) s.close() # prevents leaking connections between sessions? </code></pre> <p>So the create_engine() calls occur on every request... I can see that being needed, and the Connection Pool probably caches them and does things sensibly. </p> <p>But calling Session.bind_mapper() once for <em>each</em> table, on <em>every</em> request? Seems like there has to be a better way.</p> <p>Obviously, since a desire for strong security underlies all this, we don't want any chance that a connection established for a high-security user will inadvertently be used in a later request by a low-security user.</p>
1,858,010
2
0
null
2009-12-07 02:29:48.04 UTC
12
2010-03-22 23:34:47.08 UTC
2010-03-22 23:34:47.08 UTC
null
221,537
null
221,537
null
1
8
python|postgresql|web-applications|sqlalchemy|pylons
10,055
<p>Binding global objects (mappers, metadata) to user-specific connection is not good way. As well as using scoped session. I suggest to create new session for each request and configure it to use user-specific connections. The following sample assumes that you use separate metadata objects for each database:</p> <pre><code>binds = {} finance_engine = create_engine(url1) binds.update(dict.fromkeys(finance_metadata.sorted_tables, finance_engine)) # The following line is required when mappings to joint tables are used (e.g. # in joint table inheritance) due to bug (or misfeature) in SQLAlchemy 0.5.4. # This issue might be fixed in newer versions. binds.update(dict.fromkeys([Employee, Customer, Invoice], finance_engine)) staff_engine = create_engine(url2) binds.update(dict.fromkeys(staff_metadata.sorted_tables, staff_engine)) # See comment above. binds.update(dict.fromkeys([Project, Hour], staff_engine)) session = sessionmaker(binds=binds)() </code></pre>
1,773,680
Thread.VolatileRead Implementation
<p>I'm looking at the implementation of the <em>VolatileRead/VolatileWrite</em> methods (using Reflector), and i'm puzzled by something.</p> <p>This is the implementation for VolatileRead:</p> <pre><code>[MethodImpl(MethodImplOptions.NoInlining)] public static int VolatileRead(ref int address) { int num = address; MemoryBarrier(); return num; } </code></pre> <p>How come the memory barrier is placed after reading the value of "address"? dosen't it supposed to be the opposite? (place before reading the value, so any pending writes to "address" will be completed by the time we make the actual read. The same thing goes to VolatileWrite, where the memory barrier is place <em>before</em> the assignment of the value. Why is that? Also, why does these methods have the <em>NoInlining</em> attribute? what could happen if they were inlined?</p>
1,773,696
2
1
null
2009-11-20 22:43:17.463 UTC
10
2017-04-07 13:50:53.483 UTC
null
null
null
unknown
null
null
1
28
c#|multithreading|memory-model
4,360
<p>I thought that until recently. Volatile reads aren't what you think they are - they're not about guaranteeing that they get the most recent value; they're about making sure that no read which is later in the program code is moved to before <em>this</em> read. That's what the spec guarantees - and likewise for volatile writes, it guarantees that no earlier write is moved to <em>after</em> the volatile one.</p> <p>You're <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94808&amp;wa=wsignin1.0" rel="noreferrer">not alone</a> in suspecting this code, but <a href="http://joeduffyblog.com/2008/06/13/volatile-reads-and-writes-and-timeliness/" rel="noreferrer">Joe Duffy explains it better than I can</a> :)</p> <p>My answer to this is to give up on lock-free coding other than by using things like PFX which are designed to insulate me from it. The memory model is just too hard for me - I'll leave it to the experts, and stick with things that I <em>know</em> are safe.</p> <p>One day I'll update my threading article to reflect this, but I think I need to be able to discuss it more sensibly first...</p> <p>(I don't know about the no-inlining part, btw. I suspect that inlining could introduce some other optimizations which aren't meant to happen around volatile reads/writes, but I could easily be wrong...)</p>
63,875,411
Type 'State<List<User>?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate
<p>I'm trying to get a value from LiveData with observeAsState in jetpack compose, but I get a weird error</p> <blockquote> <p>Type 'State&lt;List?&gt;' has no method 'getValue(Nothing?, KProperty&lt;*&gt;)' and thus it cannot serve as a delegate</p> </blockquote> <h2>Code</h2> <pre><code>@Composable fun UserScreen(userViewModel:UserViewModel){ val items: List&lt;User&gt; by userViewModel.fetchUserList.observeAsState() UserList(userList = items) } </code></pre> <p><a href="https://i.stack.imgur.com/xhSRG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xhSRG.png" alt="enter image description here" /></a></p> <h2>ViewModel</h2> <pre><code>class UserViewModel: ViewModel() { private val dataSource = UserDataSource() val fetchUserList = liveData { emit(dataSource.dummyUserList) } } </code></pre>
63,877,349
9
1
null
2020-09-13 20:45:58.42 UTC
20
2022-08-19 16:03:12.37 UTC
null
null
null
null
10,870,164
null
1
120
android|kotlin|android-jetpack|android-jetpack-compose
24,653
<p>If you get a compiler error that observeAsState or getValue are not defined make sure you have the following imports:</p> <pre><code>import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState </code></pre> <p>This information is from Step #4 in the &quot;<a href="https://developer.android.com/codelabs/jetpack-compose-state" rel="noreferrer">Using State in Jetpack Compose</a>&quot; codelab.</p>
53,405,483
Material Design TextInputEditText Border Color When Not Activated
<p>I'm placing a <code>TextInputEditText</code> widget onto a white background. When the fragment first loads, the widget does not have focus. The border around the widget is white (or almost white), so it is invisible on a white background. Here is a screenshot of that widget, drawn on a black background for contrast:</p> <p><img src="https://i.stack.imgur.com/ZfWOA.png" alt=""></p> <p>As soon as I tap on the widget, the border becomes that of my primary color, which is exactly what I want. Here is a similar screenshot after the widget is activated.</p> <p><img src="https://i.stack.imgur.com/7NtY6.png" alt=""></p> <p>I'm trying to control these colors through a style, and I've tried everything that I can think of, but I cannot figure out how to adjust that color. Here is my style (feel free to laugh at the various attempts):</p> <pre><code>&lt;style name="MyTextInputLayout" parent="Base.Widget.MaterialComponents.TextInputLayout"&gt; &lt;item name="android:colorBackground"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:textColorHint"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="android:paddingStart"&gt;16dp&lt;/item&gt; &lt;item name="android:paddingEnd"&gt;16dp&lt;/item&gt; &lt;item name="android:colorControlActivated"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorControlNormal"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorControlHighlight"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:backgroundTint"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorAccent"&gt;@android:color/black&lt;/item&gt; &lt;/style&gt; &lt;style name="MyTextInputEditText" parent="ThemeOverlay.MaterialComponents.TextInputEditText"&gt; &lt;item name="android:textColor"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorBackground"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorControlActivated"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorControlNormal"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorControlHighlight"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:backgroundTint"&gt;@android:color/black&lt;/item&gt; &lt;item name="android:colorAccent"&gt;@android:color/black&lt;/item&gt; &lt;/style&gt; </code></pre> <p>And finally, the xml of the layout in case it is helpful:</p> <pre><code>&lt;com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginBottom="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" style="@style/MyTextInputLayout"&gt; &lt;com.google.android.material.textfield.TextInputEditText android:id="@+id/reg_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/username" style="@style/MyTextInputEditText"/&gt; &lt;/com.google.android.material.textfield.TextInputLayout&gt; </code></pre> <p>How can I change this border color when the widget is not active (i.e. does not have focus)?</p>
53,406,146
5
3
null
2018-11-21 04:54:59.827 UTC
9
2021-05-21 09:29:37.423 UTC
2018-11-21 05:01:46.17 UTC
null
9,134,576
null
1,024,973
null
1
17
android|material-design
17,440
<p>I solved this in two main steps:</p> <ol> <li><p>First problem I had was that the parent style for my <code>TextInputLayout</code> style needed to be changed to <code>Widget.MaterialComponents.TextInputLayout.OutlinedBox</code>.</p></li> <li><p>Once I figured that out, I traced through the Android xml for that style and got to a file called mtrl_box_stroke_color.xml. This is a selector where the three colors for the standard TextInputLayout border are declared. That file looks like this:</p> <p> </p></li> </ol> <p>So I copied that and created my own file in the res/color folder that I called edit_text_box_border.xml. I modified the three colors to suit my purposes, ultimately coming up with this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:color="?attr/colorPrimary" android:state_focused="true"/&gt; &lt;item android:alpha="0.87" android:color="@color/colorPrimary" android:state_hovered="true"/&gt; &lt;item android:alpha="0.12" android:color="@color/colorPrimary" android:state_enabled="false"/&gt; &lt;item android:alpha="0.38" android:color="@color/colorPrimary"/&gt; &lt;/selector&gt; </code></pre> <p>Then, back in my style, I had to get rid of my many color attempts and add an item for boxStrokeColor that pointed to this file. Here are both styles:</p> <pre><code>&lt;style name="MyTextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox"&gt; &lt;item name="android:textColorHint"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="android:paddingStart"&gt;16dp&lt;/item&gt; &lt;item name="android:paddingEnd"&gt;16dp&lt;/item&gt; &lt;item name="boxStrokeColor"&gt;@color/edit_text_box_border&lt;/item&gt; &lt;/style&gt; &lt;style name="MyTextInputEditText" parent="ThemeOverlay.MaterialComponents.TextInputEditText.OutlinedBox.Dense"&gt; &lt;item name="android:textColor"&gt;@android:color/black&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Now, when I run the app, I start out with this:</p> <p><a href="https://i.stack.imgur.com/fsrYy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fsrYy.png" alt="enter image description here"></a></p> <p>Which then turns into this when I tap on it:</p> <p><a href="https://i.stack.imgur.com/2htka.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2htka.png" alt="enter image description here"></a></p> <p>That's what I was going for, so problem solved. Hope this helps someone.</p>
68,780,819
When I try to pull or push in GitHub, I am getting an error message: "Please use a personal access token instead."
<p>I am using the version control as GitHub through SourceTree, but it is getting failed from 13th August, the below is the error I am getting from GitHub.</p> <blockquote> <p>remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead. remote: Please see <a href="https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/" rel="noreferrer">https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/</a> for more information.</p> </blockquote> <p>Anybody know what was the problem, or how can I use the personal access token?</p>
68,784,631
7
1
null
2021-08-14 06:17:31.893 UTC
17
2022-08-17 07:22:47.553 UTC
2021-09-11 08:41:47.29 UTC
null
446,477
null
8,399,124
null
1
22
github|version-control|atlassian-sourcetree
30,660
<p>Since the OP is using SourceTree, do the following:</p> <ol> <li>Generate your <a href="https://github.com/settings/tokens" rel="noreferrer">Personal access tokens</a> in Github account setting.</li> <li>Double click a repository in SourceTree, click <code>Setting</code> icon in the top right of the popup window.</li> <li>Click <code>Remotes</code> in the menu tab. You will see the remote URL of this repository, which should be like this <code>https://github.com/username/repo.git</code>.</li> <li>Click <code>Edit</code> and change it to <code>https://&lt;your_token&gt;@github.com/username/repo.git</code>.</li> </ol> <p>DONE.</p>
6,259,647
MySQL match() against() - order by relevance and column?
<p>Okay, so I'm trying to make a full text search in multiple columns, something simple like this:</p> <pre><code>SELECT * FROM pages WHERE MATCH(head, body) AGAINST('some words' IN BOOLEAN MODE) </code></pre> <p>Now i want to order by relevance, (how many of the words are found?) which I have been able to do with something like this:</p> <pre><code>SELECT * , MATCH (head, body) AGAINST ('some words' IN BOOLEAN MODE) AS relevance FROM pages WHERE MATCH (head, body) AGAINST ('some words' IN BOOLEAN MODE) ORDER BY relevance </code></pre> <p>Now here comes the part where I get lost, I want to prioritize the relevance in the <code>head</code> column.</p> <p>I guess I could make two relevance columns, one for <code>head</code> and one for <code>body</code>, but at that point I'd be doing somewhat the same search in the table three times, and for what i'm making this function, performance is important, since the query will both be joined and matched against other tables.</p> <p><strong>So, my main question is</strong>, is there a faster way to search for relevance and prioritize certain columns? (And as a bonus possibly even making relevance count number of times the words occur in the columns?)</p> <p>Any suggestions or advice would be great.</p> <p><strong>Note:</strong> I will be running this on a LAMP-server. (WAMP in local testing)</p>
6,305,108
5
2
null
2011-06-07 00:56:01.823 UTC
53
2021-08-18 21:25:49.727 UTC
null
null
null
null
676,713
null
1
84
mysql|full-text-search
139,104
<p>This <em>might</em> give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:</p> <pre><code>SELECT pages.*, MATCH (head, body) AGAINST ('some words') AS relevance, MATCH (head) AGAINST ('some words') AS title_relevance FROM pages WHERE MATCH (head, body) AGAINST ('some words') ORDER BY title_relevance DESC, relevance DESC -- alternatively: ORDER BY title_relevance + relevance DESC </code></pre> <p>An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is <a href="http://www.postgresql.org/docs/9.0/static/textsearch-controls.html" rel="noreferrer">Postgres</a>. It allows to set the weight of operators and to play around with the ranking.</p>
6,210,390
How to set selectedIndex of select element using display text?
<p>How to set selectedIndex of select element using display text as reference?</p> <p>Example:</p> <pre><code>&lt;input id="AnimalToFind" type="text" /&gt; &lt;select id="Animals"&gt; &lt;option value="0"&gt;Chicken&lt;/option&gt; &lt;option value="1"&gt;Crocodile&lt;/option&gt; &lt;option value="2"&gt;Monkey&lt;/option&gt; &lt;/select&gt; &lt;input type="button" onclick="SelectAnimal()" /&gt; &lt;script type="text/javascript"&gt; function SelectAnimal() { //Set selected option of Animals based on AnimalToFind value... } &lt;/script&gt; </code></pre> <p>Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...</p>
6,210,445
7
1
null
2011-06-02 04:31:29.313 UTC
13
2018-07-19 17:34:35.473 UTC
2017-07-13 07:43:29.637 UTC
null
107,625
null
724,689
null
1
46
javascript|selectedindex
237,403
<p>Try this:</p> <pre><code>function SelectAnimal() { var sel = document.getElementById('Animals'); var val = document.getElementById('AnimalToFind').value; for(var i = 0, j = sel.options.length; i &lt; j; ++i) { if(sel.options[i].innerHTML === val) { sel.selectedIndex = i; break; } } } </code></pre>
6,169,121
How to write a BOOL predicate in Core Data?
<p>I have an attribute of type <code>BOOL</code> and I want to perform a search for all managed objects where this attribute is <code>YES</code>.</p> <p>For string attributes it is straightforward. I create a predicate like this:</p> <pre><code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName = %@", userName]; </code></pre> <p>But how do I do this, if I have a bool attribute called <em>selected</em> and I want to make a predicate for this? Could I just do something like this?</p> <pre><code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = %@", yesNumber]; </code></pre> <p>Or do I need other format specifiers and just pass <code>YES</code>?</p>
6,169,191
7
0
null
2011-05-29 17:08:19.237 UTC
16
2021-07-11 12:30:47.63 UTC
2013-08-23 16:50:35.263 UTC
null
488,876
null
472,300
null
1
99
iphone|ios|ipad|core-data|predicate
47,781
<p>From <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html#//apple_ref/doc/uid/TP40001793-SW2" rel="noreferrer">Predicate Programming Guide</a>:</p> <p>You specify and test for equality of Boolean values as illustrated in the following examples:</p> <pre><code>NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber numberWithBool:aBool]]; NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"]; </code></pre> <p>You can also check out the <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-SW1" rel="noreferrer">Predicate Format String Syntax</a>.</p>
6,003,374
What is CMake equivalent of 'configure --prefix=DIR && make all install '?
<p>I do <code>cmake . &amp;&amp; make all install</code>. This works, but installs to <code>/usr/local</code>.</p> <p>I need to install to a different prefix (for example, to <code>/usr</code>).</p> <p>What is the <code>cmake</code> and <code>make</code> command line to install to <code>/usr</code> instead of <code>/usr/local</code>?</p>
6,003,937
8
6
null
2011-05-14 16:59:50.267 UTC
136
2022-08-04 21:40:20.58 UTC
2018-10-22 20:27:14.923 UTC
null
63,550
null
564,524
null
1
439
cmake
240,618
<p>You can pass in any CMake variable on the command line, or edit cached variables using ccmake/cmake-gui. On the command line,</p> <pre>cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr . && make all install</pre> <p>Would configure the project, build all targets and install to the /usr prefix. The type (PATH) is not strictly necessary, but would cause the Qt based cmake-gui to present the directory chooser dialog.</p> <p><em>Some minor additions as comments make it clear that providing a simple equivalence is not enough for some. Best practice would be to use an external build directory, i.e. not the source directly. Also to use more generic CMake syntax abstracting the generator.</em></p> <pre>mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr .. && cmake --build . --target install --config Release</pre> <p>You can see it gets quite a bit longer, and isn't directly equivalent anymore, but is closer to best practices in a fairly concise form... The --config is only used by multi-configuration generators (i.e. MSVC), ignored by others.</p>
6,094,329
Tomcat 7 and JSTL
<p>I wrote a web application with Eclipse Tomcat and it works on my local Tomcat 7, when I tried to publish it online on a Tomcat 7, I had the following error:</p> <blockquote> <p>SEVERE: Servlet.service() for servlet [obliquid.servlet.Index] in context with path [/cp] threw exception [The absolute uri: <code>http://java.sun.com/jsp/jstl/core</code> cannot be resolved in either web.xml or the jar files deployed with this application] </p> </blockquote> <p>Tomcat 7 has "Spec versions: Servlet 3.0, JSP 2.2, EL 2.2", so JSTL is not included?</p> <p>When I tried to upload standard.jar and jstl.jar I had the following error:</p> <blockquote> <p>org.apache.jasper.JasperException: /jsp/index.jsp (line: 3, column: 62) Unable to read TLD "META-INF/c.tld" from JAR file "jndi:/localhost/cp/WEB-INF/lib/standard.jar": org.apache.jasper.JasperException: Failed to load or instantiate TagLibraryValidator class: org.apache.taglibs.standard.tlv.JstlCoreTLV</p> </blockquote> <p>I did some googling, but I couldn't sort it out, some said it could be caused by conflicting versions of the jars. Maybe I should not include those jars and use a different JSTL url? Mine is for JSTL 1.1 I think, is there a new URL for JSTL 1.2?</p> <p>What should I do to solve the problem and make this application run?</p>
6,094,605
9
3
null
2011-05-23 07:52:08.07 UTC
28
2015-12-16 19:18:25.99 UTC
2012-05-03 02:29:36.65 UTC
null
3
null
445,543
null
1
47
java|tomcat|jstl|tomcat7
99,066
<p>Tomcat has never included JSTL.</p> <p>You should put the jstl and standard jars in <code>WEB-INF/lib</code> (you've done that), and make sure you have the permissions to read them (chmod)</p> <p>Your URI is correct and it should work (works here)</p>
6,162,188
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
<p>I'm trying to find out when a user left a specified page. There is no problem finding out when he used a link inside the page to navigate away but I kind of need to mark up something like when he closed the window or typed another URL and pressed enter. The second one is not so important but the first one is. So here is the question:</p> <p>How can I see when a user closed my page (capture window.close event), and then... doesn't really matter (I need to send an AJAX request, but if I can get it to run an alert, I can do the rest).</p>
6,162,238
9
0
null
2011-05-28 14:19:34.37 UTC
25
2022-02-23 22:27:19.38 UTC
2019-05-06 14:33:47.737 UTC
null
4,370,109
null
569,872
null
1
56
javascript|browser|window|dom-events
66,703
<p>There are <code>unload</code> and <code>beforeunload</code> javascript events, but these are not reliable for an Ajax request (it is not guaranteed that a request initiated in one of these events will reach the server).</p> <p>Therefore, doing this is highly <strong>not</strong> recommended, and you should look for an alternative.</p> <p>If you definitely need this, consider a "ping"-style solution. Send a request every minute basically telling the server "I'm still here". Then, if the server doesn't receive such a request for more than two minutes (you have to take into account latencies etc.), you consider the client offline.</p> <hr> <p>Another solution would be to use <code>unload</code> or <code>beforeunload</code> to do a Sjax request (Synchronous JavaScript And XML), but this is completely not recommended. Doing this will basically freeze the user's browser until the request is complete, which they will not like (even if the request takes little time).</p>
5,956,610
How to select first 10 words of a sentence?
<p>How do I, from an output, only select the first 10 words?</p>
5,956,635
12
1
null
2011-05-10 21:20:30.973 UTC
15
2017-05-10 19:24:50.763 UTC
2015-08-04 02:11:56.4 UTC
null
599,911
null
441,049
null
1
50
php|string|substring|trim
90,578
<pre><code>implode(' ', array_slice(explode(' ', $sentence), 0, 10)); </code></pre> <p>To add support for other word breaks like commas and dashes, <code>preg_match</code> gives a quick way and doesn't require splitting the string:</p> <pre><code>function get_words($sentence, $count = 10) { preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches); return $matches[0]; } </code></pre> <p>As Pebbl mentions, PHP doesn't handle UTF-8 or Unicode all that well, so if that is a concern then you can replace <code>\w</code> for <code>[^\s,\.;\?\!]</code> and <code>\W</code> for <code>[\s,\.;\?\!]</code>.</p>
27,644,586
How to set up Travis CI with multiple languages
<p>My project uses both nodejs and java</p> <p>I tried starting off with a node_js build then installing java (since this is an npm module)</p> <p>but the scripts to install java failed, plus I don't think there's a need to install it when there is a build with java that already exists.</p> <p>should I start off with a java build then install node?</p> <p>I'm trying this</p> <pre class="lang-yml prettyprint-override"><code>language: java - oraclejdk8 language: node_js node_js: - "0.10" </code></pre> <p>which ignores the first 2 lines it seems and builds a node_js build which has java 7 and my project uses java 8</p> <p>I tried this <a href="https://stackoverflow.com/questions/27036259/how-to-write-travis-yml-if-my-project-deps-on-python-and-nodejs">answer</a> for python</p> <p>using </p> <pre class="lang-yml prettyprint-override"><code>language: node_js node_js: - "0.10" java: oraclejdk8 </code></pre> <p>but that didn't work</p> <p>How can I add java 8?</p>
27,655,871
6
1
null
2014-12-25 05:56:44.817 UTC
34
2021-03-11 22:14:49.117 UTC
2018-05-11 04:35:39.23 UTC
null
2,035,869
null
907,744
null
1
106
travis-ci
28,536
<p>I used this <code>.yml</code>:</p> <pre><code>language: java jdk: - oraclejdk8 node_js: "0.10" install: "npm install" script: "npm test" </code></pre>
27,455,581
Tuple.Create() vs new Tuple
<p>Consider the following expressions:</p> <pre><code>new Tuple&lt;int,int&gt;(1,2); Tuple.Create(1,2); </code></pre> <p>Is there any difference between these two methods of Tuple creation? From my reading it seems to be more a convenient shorthand than anything like object creation in C++ (heap vs stack).</p>
45,307,205
5
1
null
2014-12-13 04:35:23.85 UTC
8
2020-06-23 13:06:20.44 UTC
2018-06-15 14:23:14.14 UTC
null
284,795
null
1,710,566
null
1
51
c#|tuples
51,069
<p>Well, this questions is old... but nevertheless I think I may contribute constructively. From the accepted answer:</p> <blockquote> <p>I suppose one benefit is that, since you don't have to specify the type with Tuple.Create, you can store anonymous types for which you otherwise wouldn't be able to say what the type is</p> </blockquote> <p>The consequence is true: you can store anonymous types for which ... </p> <p>But the first part: </p> <blockquote> <p>since you don't have to specify the type with Tuple.Create</p> </blockquote> <p>is not always true. Consider the following scenario:</p> <pre><code>interface IAnimal { } class Dog : IAnimal { } </code></pre> <p>The following will not compile:</p> <pre><code>Tuple&lt;IAnimal&gt; myWeirdTuple; myWeirdTuple = Tuple.Create(new Dog()); </code></pre> <p>You will have to specify the type parameter in the Create method like this:</p> <pre><code>myWeirdTuple = Tuple.Create&lt;IAnimal&gt;(new Dog()); </code></pre> <p>which is as verbose as calling <strong><code>new Tuple&lt;IAnimal&gt;(new Dog())</code></strong> IMO</p>
44,590,393
ES6 Modules: Undefined onclick function after import
<p>I am testing ES6 Modules and want to let the user access some imported functions using <code>onclick</code>:</p> <p>test.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Module Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="click me" onclick="hello();"/&gt; &lt;script type="module"&gt;import {hello} from "./test.js";&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>test.js:</p> <pre><code>export function hello() {console.log("hello");} </code></pre> <p>When I click the button, the developer console says: <em>ReferenceError: hello is not defined</em>. How can I import functions from modules so that they are available as onclick functions?</p> <p>I am using Firefox 54.0 with <code>dom.moduleScripts.enabled</code> set to <code>true</code>.</p>
44,591,205
4
2
null
2017-06-16 13:24:07.813 UTC
21
2022-07-25 20:28:52.893 UTC
null
null
null
null
398,963
null
1
72
javascript|ecmascript-6|es6-modules
29,430
<p>Module creates a scope to avoid name collisions. </p> <p>Either expose your function to <code>window</code> object</p> <pre><code>import {hello} from './test.js' window.hello = hello </code></pre> <p>Or use <code>addEventListener</code> to bind handler. <a href="http://plnkr.co/edit/LpygpPM2xmcMvc8fDhTl?p=preview" rel="noreferrer">Demo</a></p> <pre><code>&lt;button type="button" id="hello"&gt;Click Me&lt;/button&gt; &lt;script type="module"&gt; import {hello} from './test.js' document.querySelector('#hello').addEventListener('click', hello) &lt;/script&gt; </code></pre>
51,505,291
Timeline bar graph using python and matplotlib
<p>I am looking to draw a timeline bar graph using <strong>matplotlib</strong> that will show the things a person did in one day. I am adding the code below's output and an expected output that I am looking for. Any library can be used, in my case the closest I could get to was using <strong>matplotlib</strong>. Any help would be greatly appreciated.</p> <pre><code>import datetime as dt import pandas as pd import matplotlib.pyplot as plt import numpy as np data = [ (dt.datetime(2018, 7, 17, 0, 15), dt.datetime(2018, 7, 17, 0, 30), 'sleep'), (dt.datetime(2018, 7, 17, 0, 30), dt.datetime(2018, 7, 17, 0, 45), 'eat'), (dt.datetime(2018, 7, 17, 0, 45), dt.datetime(2018, 7, 17, 1, 0), 'work'), (dt.datetime(2018, 7, 17, 1, 0), dt.datetime(2018, 7, 17, 1, 30), 'sleep'), (dt.datetime(2018, 7, 17, 1, 15), dt.datetime(2018, 7, 17, 1, 30), 'eat'), (dt.datetime(2018, 7, 17, 1, 30), dt.datetime(2018, 7, 17, 1, 45), 'work') ] rng=[] for i in range(len(data)): rng.append((data[i][0]).strftime('%H:%M')) index={} activity = [] for i in range(len(data)): index[(data[i][2])]=[] activity.append(data[i][2]) for i in range(len(index)): for j in range(len(activity)): if activity[j]==index.keys()[i]: index[index.keys()[i]].append(15) else: index[index.keys()[i]].append(0) data = list(index.values()) df = pd.DataFrame(data,index=list(index.keys())) df.plot.barh(stacked=True, sharex=False) plt.show() </code></pre> <p><strong>My Output</strong>:</p> <p>Using matplotlib this is what I was getting</p> <p><img src="https://i.stack.imgur.com/tJpES.png" alt="Using matplotlib this is what I was getting" /></p> <p><strong>Expected Output</strong>:</p> <p>I got this using google charts' Timeline graph but I need this using python and the data used for generating both graphs is not exactly the same, I hope you get the point <img src="https://i.stack.imgur.com/RhqZQ.png" alt="I got this using google charts Timeline graph but I need this using python and the data used for generating both graphs is not exactly the same, I hope you get the point" /></p>
51,506,028
2
2
null
2018-07-24 18:24:37.92 UTC
17
2022-03-30 17:16:41.91 UTC
2022-03-30 17:16:41.91 UTC
null
1,021,819
null
7,492,381
null
1
16
python-2.7|pandas|numpy|matplotlib
26,939
<p>You may create a <a href="https://matplotlib.org/api/collections_api.html#matplotlib.collections.PolyCollection" rel="noreferrer"><code>PolyCollection</code></a> of "bars". For this you would need to convert your dates to numbers (<a href="https://matplotlib.org/api/dates_api.html#matplotlib.dates.date2num" rel="noreferrer"><code>matplotlib.dates.date2num</code></a>).</p> <pre><code>import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.collections import PolyCollection data = [ (dt.datetime(2018, 7, 17, 0, 15), dt.datetime(2018, 7, 17, 0, 30), 'sleep'), (dt.datetime(2018, 7, 17, 0, 30), dt.datetime(2018, 7, 17, 0, 45), 'eat'), (dt.datetime(2018, 7, 17, 0, 45), dt.datetime(2018, 7, 17, 1, 0), 'work'), (dt.datetime(2018, 7, 17, 1, 0), dt.datetime(2018, 7, 17, 1, 30), 'sleep'), (dt.datetime(2018, 7, 17, 1, 15), dt.datetime(2018, 7, 17, 1, 30), 'eat'), (dt.datetime(2018, 7, 17, 1, 30), dt.datetime(2018, 7, 17, 1, 45), 'work') ] cats = {"sleep" : 1, "eat" : 2, "work" : 3} colormapping = {"sleep" : "C0", "eat" : "C1", "work" : "C2"} verts = [] colors = [] for d in data: v = [(mdates.date2num(d[0]), cats[d[2]]-.4), (mdates.date2num(d[0]), cats[d[2]]+.4), (mdates.date2num(d[1]), cats[d[2]]+.4), (mdates.date2num(d[1]), cats[d[2]]-.4), (mdates.date2num(d[0]), cats[d[2]]-.4)] verts.append(v) colors.append(colormapping[d[2]]) bars = PolyCollection(verts, facecolors=colors) fig, ax = plt.subplots() ax.add_collection(bars) ax.autoscale() loc = mdates.MinuteLocator(byminute=[0,15,30,45]) ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(loc)) ax.set_yticks([1,2,3]) ax.set_yticklabels(["sleep", "eat", "work"]) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/9AWCU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9AWCU.png" alt="enter image description here"></a></p> <p>Note that such plots can equally be generated with a <a href="https://matplotlib.org/gallery/lines_bars_and_markers/broken_barh.html" rel="noreferrer">Broken Bar plot (<code>broken_barh</code>)</a>, however, the (unsorted) data used here, make it a bit easier using a PolyCollection.</p> <p>And now you would need to explain to me how you can sleep and eat at the same time - something I can never quite get at, as hard as I try.</p>
33,433,274
anaconda - graphviz - can't import after installation
<p>Just installed a package through anaconda (<code>conda install graphviz</code>), but ipython wouldn't find it.</p> <p>I can see a graphviz folder in <code>C:\Users\username\Anaconda\pkgs</code></p> <p>But there's nothing in: <code>C:\Users\username\Anaconda\Lib\site-packages</code></p> <p><a href="https://i.stack.imgur.com/JlMH9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JlMH9.png" alt="still wouldn&#39;t work"></a></p>
33,433,735
14
2
null
2015-10-30 10:01:23.163 UTC
30
2022-05-26 10:17:40.68 UTC
2020-02-22 04:03:32.23 UTC
null
11,180,198
null
736,211
null
1
124
anaconda|conda|graphviz
132,256
<p>The <code>graphviz</code> conda package is <em>no</em> Python package. It simply puts the graphviz files into your virtual env's <code>Library/</code> directory. Look e.g. for <code>dot.exe</code> in the <code>Library/bin/</code> directory.</p> <p><del>To install the <code>graphviz</code> <strong>Python package</strong>, you can use <code>pip</code>: <code>conda install pip</code> and <code>pip install graphviz</code>.</del></p> <p><del>Always prefer conda packages if they are available over pip packages. Search for the package you need (<code>conda search pkgxy</code>) and then install it (<code>conda install pkgxy</code>). If it is not available, you can always build your own conda packages or you can try anaconda.org for user-built packages.</del></p> <p><del><strong>Update Nov 25, 2018</strong>: There exists now a <a href="https://anaconda.org/anaconda/python-graphviz" rel="nofollow noreferrer"><code>python-graphviz</code> package at Anaconda.org</a> which contains the Python interface for the <code>graphviz</code> tool. Simply install it with <code>conda install python-graphviz</code>.<br /> (Thanks to <a href="https://stackoverflow.com/users/1763367/wedran">wedran</a> and <a href="https://stackoverflow.com/users/5576273/g-kaklam">g-kaklam</a> for posting this solution and to <a href="https://stackoverflow.com/users/125507/endolith">endolith</a> for notifying me).</del></p> <p><strong>Update May 26, 2022</strong>: According to <a href="https://pygraphviz.github.io/documentation/stable/install.html" rel="nofollow noreferrer">the pygraphviz website</a>, the <code>conda-forge</code> channel should be used: <code>conda install -c conda-forge pygraphviz</code> (thanks to <a href="https://stackoverflow.com/users/6509519/ian-thompson">ian-thompson</a>)</p>
9,305,753
Ruby on Rails link_to With put Method
<p>I'm new to Rails, and I'm trying to use the link_to helper to create a link that issues a PUT request instead of a GET request. Specifically, I'm trying to create a link that activates a user's account in my app from the admin's panel. I'm using Rails 3.0.5.</p> <p>My routes.rb file has:</p> <pre><code>match '/admin/users/:id/activate' =&gt; 'admin#activate_user', :action =&gt; :activate_user, :via =&gt; :put </code></pre> <p>My view has:</p> <pre><code>link_to 'Activate', :action =&gt; :activate_user, :id =&gt; user.id, :method =&gt; :put </code></pre> <p>However this generates the URL (for example) <code>/admin/users/7/activate?method=put</code> with the source code <code>&lt;a href="/admin/users/7/activate?method=put"&gt;Activate&lt;/a&gt;</code>.</p> <p>I'd like to generate, instead, <code>&lt;a href = "/admin/users/7/activate" data-method="put"&gt;Activate&lt;/a&gt;</code></p> <p>I realize I could use button_to, but I've been wrestling with this issue for a while and I'm confused why I'm seeing this behavior, when other tutorials say that what I'm doing should be valid. How can I go about creating a link_to helper with the behavior I want?</p>
9,305,982
3
0
null
2012-02-16 04:54:25.997 UTC
2
2020-12-28 19:19:51.997 UTC
2012-04-21 15:59:55.057 UTC
null
379,420
null
379,420
null
1
28
ruby-on-rails|link-to
29,321
<p><strong>Updated</strong> - The <code>link_to</code> helper will do a GET unless a method is specified.</p> <p>Its better specifying the exact request type, instead of <code>match</code> in your routes file. How about replacing <code>match</code> by <code>put</code> in routes as :</p> <pre><code>put '/admin/users/:id/activate' =&gt; 'admins#activate_user', :as =&gt; 'activate_user' link_to 'Activate', activate_user_path(user.id), method: :put </code></pre> <p>The <code>activate_user</code> method should reside in <code>admins</code> controller. The <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to" rel="noreferrer">docs</a> has more info on <code>link_to</code> helper.</p>
9,212,574
Calling Activity methods from Fragment
<p>I use a fragment only inside one specific parent activity. Now I wonder if there are any drawbacks if I call methods in the parent activity directly from the included fragment like this:</p> <blockquote> <p>getActivity().someMethodInParentActivitiy()</p> </blockquote> <p>A more common solution would be to define a formal listener interface in the fragment to call back to the parent activity and then make the activity implement that interface. </p> <p>Are there any reasons (e.g. <em>reliability</em> or <em>speed</em>) why I should use the second more complex solution instead of direct method calls from the fragment to the activity?</p>
9,212,753
3
0
null
2012-02-09 14:24:09.893 UTC
5
2013-07-18 13:16:38.63 UTC
2012-02-09 14:33:14.607 UTC
null
1,051,679
null
1,051,679
null
1
29
android|android-fragments
28,773
<p>Don't look at the performance at the begining. Remember "premature optimization is the root of all evil". The second approach is better because your fragment could be used in different activities. The first approach introduces more dependencies in your code, the fragment is dependent to the activity type. You're loosing ability to test, reuse, small complex. It may seem to be simpler right now, but in the future you'll see ;-)</p>
9,273,204
Can you add buttons to navigation bars through storyboard?
<p>At the moment, I've been adding navigation buttons like follows:</p> <pre><code>self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:self.editButtonItem.style target:self action:@selector(doneButtonPressed)]; </code></pre> <p>It seems a bit silly to not add them through storyboard, but I can't find a way to do so. Is there one that I'm missing?</p>
9,273,559
2
0
null
2012-02-14 07:29:03.007 UTC
14
2015-06-16 01:41:31.937 UTC
null
null
null
null
1,103,045
null
1
57
ios
41,819
<p>You can just drag out a Bar Button Item and drop it on the right end of the view controller's navigation bar:</p> <p><img src="https://i.stack.imgur.com/XYRAt.gif" alt="enter image description here"></p>
9,417,121
Is there any way of passing additional data via custom events?
<p>I need to pass data between two autonomic user scripts - ideally without touching the <code>unsafeWindow</code> object - and I thought using custom events would be the way to go. I thought of something like this (let us disregard the MSIE model for the purpose of the example):</p> <pre><code>addEventListener("customEvent", function(e) { alert(e.data); }); var custom = document.createEvent("HTMLEvents"); custom.initEvent("customEvent", true, true); custom.data = "Some data..."; dispatchEvent(custom); </code></pre> <p>This works nicely in the standard Javascript environment and within one user script, but when the event is fired by the user script and caught outside of it or inside another user script, the <code>data</code> property is <code>undefined</code> in Chromium. I suppose I could just save the passed data in the <code>sessionStorage</code>, but it is far from seamless. Any other elegant solutions? Perfection need and can be achieved, I can feel it.</p>
9,418,326
3
0
null
2012-02-23 16:32:47.64 UTC
11
2020-11-30 13:41:37.643 UTC
2019-11-09 16:58:52.83 UTC
null
4,370,109
null
657,401
null
1
88
javascript|dom|google-chrome-extension|dom-events|userscripts
67,164
<p>Yes, you can use a <code>MessageEvent</code> or a <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent" rel="noreferrer"><code>CustomEvent</code></a>.</p> <p>Example usage:</p> <pre><code>//Listen for the event window.addEventListener("MyEventType", function(evt) { alert(evt.detail); }, false); //Dispatch an event var evt = new CustomEvent("MyEventType", {detail: "Any Object Here"}); window.dispatchEvent(evt); </code></pre>
9,044,472
How to correct indentation in IntelliJ
<p>How can indentation be automatically (not manually) corrected in IntelliJ?</p> <p>In Eclipse, it's possible to just highlight the code that needs indenting, right-click, and select <code>Source</code> > <code>Correct indentation</code>.</p> <p>Is there any method for doing the same thing in IntelliJ?</p>
9,044,517
7
0
null
2012-01-28 10:14:15.04 UTC
25
2021-07-05 04:43:44.143 UTC
2018-08-01 18:47:29.71 UTC
null
9,238,547
null
764,446
null
1
168
intellij-idea|indentation
252,095
<p><code>Code</code> → <code>Reformat Code...</code> (default <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd>) for the whole file or <code>Code</code> → <code>Auto-Indent Lines</code> (default <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>I</kbd>) for the current line or selection.</p> <p>You can customise the settings for how code is auto-formatted under <code>File</code> → <code>Settings</code> → <code>Editor</code> → <code>Code Style</code>.</p> <hr> <p>To ensure comments are also indented to the same level as the code, you can simply do as follows:</p> <p><a href="https://i.stack.imgur.com/m52kZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/m52kZ.jpg" alt="UI screenshot"></a> <sub>(example for JavaScript)</sub></p>
52,443,706
Angular HttpClient missing response headers
<p>I am trying to get into angular lately. I have a paginated request.</p> <pre class="lang-js prettyprint-override"><code>const myParams = new HttpParams().set('page', page.toString()).set('size', size.toString()); this.http.get&lt;HttpResponse&lt;User[]&gt;&gt;('https://localhost:8443/user/', { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), params: myParams, observe: 'response' }).suscribe((response: HttpResponse&lt;User[]&gt;) =&gt; this.data = response.body); </code></pre> <p>The total count of elements in the DB is transfered to the Client in the <code>X-Total-Count</code> header. i tried to read it like that:</p> <pre class="lang-js prettyprint-override"><code>.suscribe((response: HttpResponse&lt;User[]&gt;) =&gt; { this.data = response.body; this.totalCount = response.headers.get('X-Total-Count'); }); </code></pre> <p>But this does not work. It turns out that response.headers only includes a subset of the real http-response-headers.</p> <p>this is what the headers object looks like</p> <pre class="lang-js prettyprint-override"><code>&quot;headers&quot;: { &quot;normalizedNames&quot;: {}, &quot;lazyUpdate&quot;: null } </code></pre> <p>I am sure that X-Total-Count has been sent. Firefox devtools show it. Could you please tell me how to include it into the response?</p> <p><a href="https://i.stack.imgur.com/laUM7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/laUM7.png" alt="enter image description here" /></a></p> <p><strong>UPDATE</strong></p> <p>This question differs from the one that has been identified as a duplicate in the following way: I have not been asking about how to inspect the full httpResponse. I figured that out on my own. I have been asking about why the <code>headers</code> attribute of the Response is not complete.</p>
52,444,472
5
2
null
2018-09-21 12:23:49.473 UTC
3
2020-12-21 18:35:17.553 UTC
2020-08-24 11:02:00.773 UTC
null
1,428,676
null
6,284,627
null
1
42
angular|angular6|angular-httpclient
17,753
<p>CORS requests only expose 6 safelisted headers : <code>Cache-Control</code> <code>Content-Language</code> <code>Content-Type</code> <code>Expires</code> <code>Last-Modified</code> &amp; <code>Pragma</code>.</p> <p>In order to access custom headers with a CORS request, the server has to explicitly whitelist them. This can be done by sending the response header: <code>Access-Control-Expose-Headers</code> </p> <p>For example: <code>Access-Control-Expose-Headers: X-Total-Count, X-Paging-PageSize</code></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers" rel="noreferrer">MDN Source</a></p>
33,996,749
What is the difference between print and print() in python 2.7
<p>I am newbie on Python.</p> <p>I run the following code on python 2.7 and I see different result when I use print or print(). What is the difference between these two functions? I read other questions e.g., <a href="https://stackoverflow.com/questions/21581241/what-is-the-difference-between-prints-in-python">this question</a>, but I didn't find my answer.</p> <pre><code>class Rectangle: def __init__(self, w, h): self.width = w self.height = h def __str__(self): return "(The width is: {0}, and the height is: {1})".format(self.width, self.height) box = Rectangle(100, 200) print ("box: ", box) print "box: ", box </code></pre> <p>The result is:</p> <pre><code>('box: ', &lt;__main__.Rectangle instance at 0x0293BDC8&gt;) box: (The width is: 100, and the height is: 200) </code></pre>
33,996,938
5
1
null
2015-11-30 10:45:04.287 UTC
7
2019-10-24 10:49:20.93 UTC
2017-05-23 12:30:55.41 UTC
null
-1
null
2,910,740
null
1
13
python|python-2.7
70,748
<p>In Python 2.7 (and before), <code>print</code> is a <em>statement</em> that takes a number of arguments. It prints the arguments with a space in between.</p> <p>So if you do</p> <pre><code>print "box:", box </code></pre> <p>It first prints the string "box:", then a space, then whatever <code>box</code> prints as (the result of its <code>__str__</code> function).</p> <p>If you do</p> <pre><code>print ("box:", box) </code></pre> <p>You have given <em>one</em> argument, a tuple consisting of two elements ("box:" and the object <code>box</code>).</p> <p>Tuples print as their representation (mostly used for debugging), so it calls the <code>__repr__</code> of its elements rather than their <code>__str__</code> (which should give a user-friendly message).</p> <p>That's the difference you see: <code>(The width is: 100, and the height is: 200)</code> is the result of your box's <code>__str__</code>, but <code>&lt;__main__.Rectangle instance at 0x0293BDC8&gt;</code> is its <code>__repr__</code>.</p> <p>In Python 3 and higher, <code>print()</code> is a normal function as any other (so <code>print(2, 3)</code> prints <code>"2 3"</code> and <code>print 2, 3</code> is a syntax error). If you want to have that in Python 2.7, put</p> <pre><code>from __future__ import print_function </code></pre> <p>at the top of your source file, to make it slightly more ready for the present.</p>
10,607,361
Android send SMS automatically on button click
<p>I am trying to automatically send SMS message to a certain number when the user presses a button on the screen.</p> <p>This is my code:</p> <pre><code>Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:xxxxxxxxxxx")); smsIntent.putExtra("sms_body", "Hello"); startActivity(smsIntent); </code></pre> <p>xxxxxxx = phone number</p> <p>I have the following permissions: </p> <pre><code>&lt;uses-permission android:name="android.permission.SEND_SMS"&gt;&lt;/uses-permission&gt; &lt;uses-permission android:name="android.permission.RECEIVE_SMS"&gt;&lt;/uses-permission&gt; </code></pre> <p>When I press the button it takes me to another screen where I can edit my text and press Send. I just want it to do this process automatically without taking me to another screen. As I've already defined my message, I just want to send it to a particular number. </p> <p>And also I am not sure if I put the corrent phone number in the second line of code. Do I have to put my country code in there first or can I just put my mobile phone number and it will work?</p> <p>Thank you</p>
10,607,412
5
1
null
2012-05-15 19:18:02.953 UTC
12
2019-01-06 19:51:03.57 UTC
null
null
null
null
1,370,038
null
1
10
java|android|android-intent|sms|send
51,112
<p>Try this code:</p> <pre><code> String messageToSend = "this is a message"; String number = "2121234567"; SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null); </code></pre> <p>With regards to the number, you need to enter the number as if you were calling it from the phone or sending an sms message in the normal manner.</p>
10,479,353
gradient descent seems to fail
<p>I implemented a gradient descent algorithm to minimize a cost function in order to gain a hypothesis for determining whether an image has a good quality. I did that in Octave. The idea is somehow based on the algorithm from the <a href="https://class.coursera.org/ml/lecture/" rel="nofollow noreferrer">machine learning class</a> by Andrew Ng</p> <p>Therefore I have 880 values "y" that contains values from 0.5 to ~12. And I have 880 values from 50 to 300 in "X" that should predict the image's quality.</p> <p>Sadly the algorithm seems to fail, after some iterations the value for theta is so small, that theta0 and theta1 become "NaN". And my linear regression curve has strange values...</p> <p>here is the code for the gradient descent algorithm: (<code>theta = zeros(2, 1);</code>, alpha= 0.01, iterations=1500)</p> <pre><code>function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) m = length(y); % number of training examples J_history = zeros(num_iters, 1); for iter = 1:num_iters tmp_j1=0; for i=1:m, tmp_j1 = tmp_j1+ ((theta (1,1) + theta (2,1)*X(i,2)) - y(i)); end tmp_j2=0; for i=1:m, tmp_j2 = tmp_j2+ (((theta (1,1) + theta (2,1)*X(i,2)) - y(i)) *X(i,2)); end tmp1= theta(1,1) - (alpha * ((1/m) * tmp_j1)) tmp2= theta(2,1) - (alpha * ((1/m) * tmp_j2)) theta(1,1)=tmp1 theta(2,1)=tmp2 % ============================================================ % Save the cost J in every iteration J_history(iter) = computeCost(X, y, theta); end end </code></pre> <p>And here is the computation for the costfunction:</p> <pre><code>function J = computeCost(X, y, theta) % m = length(y); % number of training examples J = 0; tmp=0; for i=1:m, tmp = tmp+ (theta (1,1) + theta (2,1)*X(i,2) - y(i))^2; %differenzberechnung end J= (1/(2*m)) * tmp end </code></pre>
10,486,437
9
1
null
2012-05-07 09:02:28.693 UTC
24
2018-10-12 16:46:40.86 UTC
2018-05-18 09:52:40.103 UTC
null
3,139,595
null
231,177
null
1
27
machine-learning|octave|gradient-descent
26,522
<p>I think that your <code>computeCost</code> function is wrong. I attended NG's class last year and I have the following implementation (vectorized):</p> <pre><code>m = length(y); J = 0; predictions = X * theta; sqrErrors = (predictions-y).^2; J = 1/(2*m) * sum(sqrErrors); </code></pre> <p>The rest of the implementation seems fine to me, although you could also vectorize them.</p> <pre><code>theta_1 = theta(1) - alpha * (1/m) * sum((X*theta-y).*X(:,1)); theta_2 = theta(2) - alpha * (1/m) * sum((X*theta-y).*X(:,2)); </code></pre> <p>Afterwards you are setting the temporary thetas (here called theta_1 and theta_2) correctly back to the "real" theta.</p> <p>Generally it is more useful to vectorize instead of loops, it is less annoying to read and to debug.</p>
22,860,582
Java generics: wildcard<?> vs type parameter<E>?
<p>I am refreshing my knowledge on Java generics. So I turned to the excellent tutorial from Oracle ... and started to put together a presentation for my coworkers. I came across the section on wildcards in the <a href="http://docs.oracle.com/javase/tutorial/java/generics/unboundedWildcards.html" rel="noreferrer">tutorial</a> that says:</p> <blockquote> <p>Consider the following method, printList:</p> <pre><code>public static void printList(List&lt;Object&gt; list) { ... </code></pre> <p>The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print <code>List&lt;Integer&gt;</code>, <code>List&lt;String&gt;</code>, <code>List&lt;Double&gt;</code>, and so on, because they are not subtypes of <code>List&lt;Object&gt;</code>. To write a generic printList method, use <code>List&lt;?&gt;</code>:</p> <pre><code>public static void printList(List&lt;?&gt; list) { </code></pre> </blockquote> <p>I understand that <code>List&lt;Object&gt;</code> will not work; but I changed the code to</p> <pre><code>static &lt;E&gt; void printObjects(List&lt;E&gt; list) { for (E e : list) { System.out.println(e.toString()); } } ... List&lt;Object&gt; objects = Arrays.&lt;Object&gt;asList("1", "two"); printObjects(objects); List&lt;Integer&gt; integers = Arrays.asList(3, 4); printObjects(integers); </code></pre> <p>And guess what; using <code>List&lt;E&gt;</code> I can print different types of Lists without any problem. </p> <p>Long story short: at least the tutorial indicates that one <strong>needs</strong> the wildcard to solve this problem; but as shown, it can be solved this way too. So, what am I missing?!</p> <p>(side note: tested with Java7; so maybe this was a problem with Java5, Java6; but on the other hand, Oracle seems to do a good job regarding updates of their tutorials)</p>
22,860,765
3
1
null
2014-04-04 10:44:28.053 UTC
16
2016-11-30 17:59:52.64 UTC
2014-04-04 10:51:31.167 UTC
null
1,531,124
null
1,531,124
null
1
48
java|generics
14,938
<p>Your approach of using a generic method is strictly more powerful than a version with wildcards, so yes, your approach is possible, too. However, the tutorial does <em>not</em> state that using a wildcard is the only possible solution, so the tutorial is also correct.</p> <p>What you gain with the wildcard in comparison to the generic method: You have to write less and the interface is "cleaner" since a non generic method is easier to grasp.</p> <p>Why the generic method is more powerful than the wildcard method: You give the parameter a name which you can reference. For example, consider a method that removes the first element of a list and adds it to the back of the list. With generic parameters, we can do the following:</p> <pre><code>static &lt;T&gt; boolean rotateOneElement(List&lt;T&gt; l){ return l.add(l.remove(0)); } </code></pre> <p>with a wildcard, this is not possible since <code>l.remove(0)</code> would return <code>capture-1-of-?</code>, but <code>l.add</code> would require <code>capture-2-of-?</code>. I.e., the compiler is not able to deduce that the result of <code>remove</code> is the same type that <code>add</code> expects. This is contrary to the first example where the compiler can deduce that both is the same type <code>T</code>. This code would not compile:</p> <pre><code>static boolean rotateOneElement(List&lt;?&gt; l){ return l.add(l.remove(0)); //ERROR! } </code></pre> <p>So, what can you do if you want to have a rotateOneElement method with a wildcard, since it is easier to use than the generic solution? The answer is simple: Let the wildcard method call the generic one, then it works:</p> <pre><code>// Private implementation private static &lt;T&gt; boolean rotateOneElementImpl(List&lt;T&gt; l){ return l.add(l.remove(0)); } //Public interface static void rotateOneElement(List&lt;?&gt; l){ rotateOneElementImpl(l); } </code></pre> <p>The standard library uses this trick in a number of places. One of them is, IIRC, Collections.java</p>
18,859,063
Supervisor socket error issue
<pre><code>$ supervisorctl reread error: &lt;class 'socket.error'&gt;, [Errno 111] Connection refused: file: /usr/lib64/python2.6/socket.py line: 567 </code></pre> <p>I'm trying to configure supervisor on my production system, but am hitting this error. The supervisor log file is empty.</p> <p>When I just type <code>supervisorctl</code>, it complains:</p> <pre><code>http://localhost:9001 refused connection </code></pre> <p>Nothing is currently listening on port 9001, AFACT: <code>lsof | grep TCP</code> returns nothing.</p>
18,860,418
7
1
null
2013-09-17 20:12:41.49 UTC
32
2020-01-14 14:09:21.81 UTC
2019-08-09 23:28:42.477 UTC
null
100,297
null
868,404
null
1
105
supervisord
93,446
<p>You have to start supervisord before you can use supervisorctl. In my case:</p> <pre><code>sudo supervisord -c /etc/supervisor/supervisord.conf sudo supervisorctl -c /etc/supervisor/supervisord.conf </code></pre>
19,004,783
Reading JSON POST using PHP
<p>I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don't format this question correctly.</p> <p>I have a really simple web service that I have created that needs to take post values and return a JSON encoded array. That all worked fine until I was told I would need to post the form data with a content-type of application/json. Since then I cannot return any values from the web service and it is definitely something to do with how I am filtering their post values.</p> <p>Basically in my local setup I have created a test page that does the following -</p> <pre><code>$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data)) ); curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call $result = curl_exec($curl); //see the results $json=json_decode($result,true); curl_close($curl); print_r($json); </code></pre> <p>On the webservice I have this (I have stripped out some of the functions) -</p> <pre><code>&lt;?php header('Content-type: application/json'); /* connect to the db */ $link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB'); mysql_select_db('webservice',$link) or die('Cannot select the DB'); if(isset($_POST['action']) &amp;&amp; $_POST['action'] == 'login') { $statusCode = array('statusCode'=&gt;1, 'statusDescription'=&gt;'Login Process - Fail'); $posts[] = array('status'=&gt;$statusCode); header('Content-type: application/json'); echo json_encode($posts); /* disconnect from the db */ } @mysql_close($link); ?&gt; </code></pre> <p>Basically I know that it is due to the $_POST values not being set but I can't find what I need to put instead of the $_POST. I tried json_decode($_POST), file_get_contents("php://input") and a number of other ways but I was shooting in the dark a bit.</p> <p>Any help would be greatly appreciated.</p> <p>Thanks, Steve</p> <p>Thanks Michael for the help, that was a definite step forward I now have at least got a repsonse when I echo the post....even if it is null </p> <p>updated CURL -</p> <pre><code> $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); </code></pre> <p>updated php on the page that the data is posted to -</p> <pre><code>$inputJSON = file_get_contents('php://input'); $input= json_decode( $inputJSON, TRUE ); //convert JSON into array print_r(json_encode($input)); </code></pre> <p>As I say at least I see a response now wheras prior it was returning a blank page</p>
19,007,851
3
1
null
2013-09-25 12:21:57.693 UTC
20
2017-12-07 08:16:31.713 UTC
2013-09-25 17:31:08.14 UTC
null
1,209,098
null
1,209,098
null
1
60
php|json|post
175,240
<p>You have empty <code>$_POST</code>. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.</p> <p>You need something like that:</p> <pre><code>$json = file_get_contents('php://input'); $obj = json_decode($json); </code></pre> <p>Also you have wrong code for testing JSON-communication...</p> <p><code>CURLOPT_POSTFIELDS</code> tells <code>curl</code> to encode your parameters as <code>application/x-www-form-urlencoded</code>. You need JSON-string here.</p> <p><strong>UPDATE</strong></p> <p>Your php code for test page should be like that:</p> <pre><code>$data_string = json_encode($data); $ch = curl_init('http://webservice.local/'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $result = curl_exec($ch); $result = json_decode($result); var_dump($result); </code></pre> <p>Also on your web-service page you should remove one of the lines <code>header('Content-type: application/json');</code>. It must be called only once.</p>
3,274,354
How to find out mount/partition a directory or file is on? (Linux Server)
<p>Is there a Linux command to easily find out which partition/mount a directory or file is on? </p> <p>(This is probably a RTM question, and I feel guilty for asking it, but somehow, I can't find a good answer on google just yet..)</p>
3,274,362
1
6
null
2010-07-18 04:48:02.757 UTC
53
2017-05-08 15:56:14.997 UTC
2017-05-08 15:56:14.997 UTC
null
1,415,724
null
357,189
null
1
175
linux|file|directory|mount|disk-partitioning
103,439
<pre><code>df -P file/goes/here | tail -1 | cut -d' ' -f 1 </code></pre>
1,408,571
RESTful Authorization
<p>I'm building a community-based site in Rails for the members of a real-world organization. I'm trying to adhere to the best practices of RESTful design, and most of it is more or less by-the-book. The issue that's making my brain run in neat RESTful circles is that of authorization. <em>Authentication</em> is an easy, long-solved problem with widely-accepted RESTful solutions, but RESTful authorization seems to be a bit of a black art. I'm trying to find the approach that will provide the most general and flexible framework for controlling access to resources while being as simple as possible, all while conforming to a RESTful architecture. (Also, a pony.)</p> <p>Considerations:</p> <ol> <li>I need to control access to a variety of resources, such as Users, Pages, Posts, et cetera.</li> <li>Authorization for a given resource must be finer-grained than simple CRUD.</li> <li>I wish to allow myself and others to edit the authorization rules from within the application.</li> <li>Authorization rules should be allowed to depend on predicates, such as (conceptually) Owner(User, Resource) or Locked(Topic)</li> </ol> <p>Consideration (2) is the one that concerns me the most. There seems to be an impedance mismatch between my conception of permissions and the RESTful conception of actions. For example, take Posts (as in a message board). REST dictates the existence of four operations on the Post resource: Create, Read, Update, and Delete. It's simple to say that a user should be able to Update his own Posts, but only certain users (or roles, or groups) should be permitted to Lock them. The traditional way to represent locking is within the state of the Post, but that leads to the smell that a User under the same conditions may or may not be able to Update a Post depending on the (completely valid) values he supplies. It seems clear to me that there are really two different actions to change the state of the Post, and to shoehorn them is merely to disguise a violation of RESTful principles.</p> <p>(I should note that this problem is quite distinct from the problem of an Update failing due to <em>invalid or inconsistent</em> data—a lock request from an unprivileged user is in principle quite valid, simply disallowed.)</p> <blockquote> <p><em>Isn't decomposition another word for rot?</em></p> </blockquote> <p>This may be overcome by decomposing the Post: a Lock is a subresource of a particular post, and to Create or Destroy one may then have separate permissions. This solution has the ring of REST to it, but is brings with it both theoretical and practical difficulties. If I factor out locks, then what about other attributes? Suppose I decide, in a fit of caprice, that only a member of Administrator should be allowed to modify the Post's title? A simple change in authorization would then require a restructuring of the database to accommodate it! This is not much of a solution. To allow for this kind of flexibility under a strategy of decomposition would require that every attribute be a resource. This presents a bit of a dilemma. My implicit assumption has been that a resource is represented in the database as a table. Under this assumption, a resource for every attribute means a table for every attribute. Clearly, this is not practical. However, to remove this assumption presents an impedance mismatch between tables and resources, which could open up its own can of worms. To use this approach would require far more in-depth consideration than I have given it. For one thing, users reasonably expect to be able to edit multiple attributes at once. Where does the request go? To the smallest resource that contains all attributes? To each individual resource in parallel? To the moon?</p> <blockquote> <p><em>Some of these things are not like the others…</em></p> </blockquote> <p>Suppose then that I do not decompose attributes. The alternative then seems to be defining a set of privileges for each resource. At this point, however, the homogeneity of REST is lost. In order to define access rules for a resource, the system must have specific knowledge of that resource's capabilities. Furthermore, it is now impossible to generically propagate permissions to descendant resources—even if a child resource had a privilege of the same name, there's no inherent semantic connection between the privileges. Defining a REST-like set of standard privileges seems to me to be the worst of both worlds, so I's be stuck with a separate permissions hierarchy for each type of resource.</p> <blockquote> <p><em>Well, we did do the nose. And the hat. But it's a resource!</em></p> </blockquote> <p>One suggestion I've seen that mitigates some of the disadvantages of the above approach is to define permissions as create/delete on <em>resources</em> and read/write on <em>attributes</em>. This system is a compromise between attributes-as-resources and privileges-per-resource: one is still left with only CRUD, but for the purposes of authorization, Read and Update pertain to attributes, which could be thought of as pseudo-resources. This provides many of the practical benefits of the attributes-as-resources approach, although the conceptual integrity is, to a certain extent, compromised. Permissions could still propagate from resource to resource and from resource to pseudo-resource, but never from a pseudo-resource. I have not fully explored the ramifications of this strategy, but it seems as though it may be promising. It occurs to me that such a system would best function as an integral part of the Model. In Rails, for example, it could be a retrofit of <code>ActiveRecord</code>. This seems rather drastic to me, but authorization is such a fundamental cross-cutting concern that this may be justified.</p> <blockquote> <p><em>Oh, and don't forget about the pony</em></p> </blockquote> <p>All of this ignores the issue of predicative permissions. Obviously, a User should be able to edit his own Posts, but no one else's. Equally obviously, the admin-written permissions table should not have separate records for each user. This is hardly an uncommon requirement—the trick is making it generic. I think that all of the functionality I need could be gained by making only the <em>rules</em> predicative, so that the applicability of the rule could be decided quickly and immediately. A rule "<code>allow User write Post where Author(User, Post)</code>" would translate to "<code>for all User, Post such that Author(User, Post), allow User write Post</code>", and "<code>deny all write Post where Locked(Post)</code>" to "<code>for all Post such that Locked(Post), deny all write Post</code>". (It would be <em>grand</em> if all such predicates could be expressed in terms of one User and one Resource.) The conceptually resultant "final" rules would be non-predicative. This raises the question of how to implement such a system. The predicates should be members of the Model classes, but I'm not sure how one could refer to them gracefully in the context of the rules. To do so safely would require some sort of reflection. Here again I have a feeling that this would require a retrofit of the Model implementation.</p> <blockquote> <p><em>How do you spell that again?</em></p> </blockquote> <p>The final question is how to best represent these authorization rules as data. A database table might do the trick, with enum columns for allow/deny and C/R/U/D (or perhaps CRUD bits? or perhaps {C, R, U, D} × {allow, deny, inherit}?), and a resource column with a path. Perhaps, as a convenience, an "inherit" bit. I'm at a loss as far as predicates. Separate table? Certainly lots of caching to prevent it from being <em>too</em> ungodly slow.</p> <hr> <p>I guess that this is a lot to ask for. I tried to do my homework before asking the question, but at this point I really need an outside perspective. I'd appreciate any input that any of y'all might have on the problem.</p>
1,418,741
3
1
null
2009-09-11 01:28:26.01 UTC
21
2015-06-16 23:17:45.537 UTC
2015-06-16 23:17:45.537 UTC
null
944,911
null
159,369
null
1
26
architecture|rest|permissions|authorization
7,128
<p>Sorry I don't have time to do this question justice, but it is nice to see some well thought out questions on SO. Here are some comments:</p> <p>Don't fall into the trap of mapping the HTTP verbs to CRUD. Yes GET and DELETE map pretty cleanly, but PUT can do Create and Update (but complete replacement only) and POST is a wildcard verb. POST is really to handle everything that does not fit into GET, PUT and DELETE. </p> <p>Using attributes to represent an object's status is only one approach to state management. I am guessing you can imagine what the following request might do:</p> <pre><code>POST /LockedPosts?url=/Post/2010 </code></pre> <p>A subresource is also a valid approach to manage the current state of a resource. I would not feel obliged to treat a resource's "state" attributes and its "data" attributes in a consistent manner.</p> <p>Attempting to map resources directly to tables is going to seriously constrain you. Don't forget that when you follow the REST constraints you suddenly are very limited in the verbs you have available. You need to be able to make up for that in being creative in the resources that you use. Limiting yourself to one resource equals one table will severely limit the functionality of your end application. </p> <p>We regularly see Rails, ASP.NET MVC and WCF Rest users posting questions here on StackOverflow about how do certain things within the constraints of REST. The problem is often not a constraint of REST but in the limitations of the framework in its support for RESTful applications. I think it is essential to first find a RESTful solution to a problem and then see if that can be mapped back to your framework of choice.</p> <p>As far as creating a permissions model that exists at a finer grain than the resource itself. Remember that one of the key REST constrains is hypermedia. Hypermedia can be used for more than just finding related entities, it can also be used to represent valid/permitted state transitions. If you return a representation than contains embedded links, conditionally based on permissions, then you can control what actions can be performed by who. i.e. If a user has permissions to unlock POST 342 then you could return the following link embedded in the representation:</p> <pre><code>&lt;Link href="/UnlockedPosts?url=/Post/342" method="POST"/&gt; </code></pre> <p>If they don't have that permission, then don't return the link. </p> <p>I think one of your difficulties here is that you are trying to chew too big of a problem at once. I think you need to look at the RESTful interface that you are trying to expose to the client as a distinct problem from how you are going to manage the permissions and predicates in order to manage authorization in your domain model. </p> <p>I realize that I haven't directly answered any of your questions, but hopefully I've provided some viewpoints that may help in some way.</p>
8,489,500
how do I subtract one week from this date in jquery?
<p>this is my code</p> <pre><code>var myDate = new Date(); todaysDate = ((myDate.getDate()) + '/' + (myDate.getMonth()) + '/' + (myDate.getFullYear())); $('#txtEndDate').val(todaysDate); </code></pre> <p>I need txtEndDate's value = today's date - one week</p>
8,489,546
4
1
null
2011-12-13 12:47:10.027 UTC
8
2020-07-10 20:04:30.377 UTC
2011-12-13 15:05:37.75 UTC
null
572,761
null
672,505
null
1
75
javascript|jquery
88,268
<p>You can modify a date using <code>setDate</code>. It automatically corrects for shifting to new months/years etc.</p> <pre><code>var oneWeekAgo = new Date(); oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); </code></pre> <p>And then go ahead to render the date to a string in any matter you prefer.</p>
27,252,934
Yii2: validation rule for array?
<p>I can define a rule for a single integer like this:</p> <pre><code>[['x'], 'integer'] </code></pre> <p>Is it possible to tell that x is an integer array? For example:</p> <pre><code>[['x'], 'integer[]'] </code></pre> <p>And could I specify the valid values in the array?</p> <p><strong>Update</strong>: From Yii version 2.0.4 we've got some help. See <a href="https://stackoverflow.com/questions/27252934/yii2-validation-rule-for-array/30300977#30300977">this answer</a>.</p>
30,300,977
3
3
null
2014-12-02 15:25:07.373 UTC
3
2016-08-19 18:29:53.727 UTC
2017-05-23 11:47:14.15 UTC
null
-1
null
57,091
null
1
25
php|validation|yii2
57,203
<p>From version 2.0.4 there is the new <a href="https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-core-validators.md#yiivalidatorseachvalidatoreach-">EachValidator</a> which makes it more easy now:</p> <pre><code>['x', 'each', 'rule' =&gt; ['integer']], </code></pre> <p>This should be sufficient. If the values should be also checked you could use this (with the <a href="http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#in">'in' validator</a> which actually is the RangeValidator):</p> <pre><code>['x', 'each', 'rule' =&gt; ['in', 'range' =&gt; [2, 4, 6, 8]]], // each value in x can only be 2, 4, 6 or 8 </code></pre> <p>However, you can use this 'in' validator also directly. And that is possible with Yii versions before 2.0.4:</p> <pre><code>['x', 'in', 'range' =&gt; [2, 4, 6, 8], 'allowArray' =&gt; true] </code></pre> <p>The use of <code>'strict' =&gt; true</code> would probably makes no sense in case the data is sent by the client and is set with <a href="http://www.yiiframework.com/doc-2.0/yii-base-model.html#load%28%29-detail">Model->load()</a>. I'm not quite sure but I think those values are all sent as strings (like "5" instead of 5).</p>
19,426,268
Difference between += and =+ in C++
<p>While programming in C++, I often confuse both "+=" and "=+", the former being the operator I actually mean. Visual Studio seems to accept both, yet they behave differently and is a source for a lot of my bugs. I know that a += b is semantically equivalent to a = a+b, but what does "=+" do?</p>
19,426,305
4
1
null
2013-10-17 12:04:40.743 UTC
1
2020-09-28 04:02:26.3 UTC
null
null
null
null
1,550,099
null
1
15
c++|operators
48,650
<p><code>=+</code> is really <code>= +</code> (assignment and the unary <code>+</code> operators).</p> <p>In order to help you remember <code>+=</code>, remember that it does addition first, then assignment. Of course that depends on the actual implementation, but it should be for the primitives.</p>
561,868
Custom iPhone camera controls (not using UIImagePickerController)
<p>While I understand that in order for an iPhone application to be accepted on the App Store, one requirement is that only documented libraries are to be used.</p> <p>If this is the case, how are certain applications such as "Night Camera" and "Camera Plus" using a camera control that seems to be something other than the one contained within UIImagePickerController?</p> <p>I have heard of certain cases where a developer has been given "special" access to certain headers that allow for features that would otherwise be impossible if constrained to only using documented libraries. However, given how opaque the application selection process is for the App Store, I would prefer to stick to what is recommended rather than take my chances.</p> <p>Anyone care to shed some more light on this?</p>
562,307
4
0
null
2009-02-18 16:39:23.443 UTC
15
2014-05-07 19:13:17.413 UTC
2014-05-07 19:13:17.413 UTC
null
3,532,040
abraginsky
52,759
null
1
13
ios|camera
15,151
<p>You might want to check out a classdump of apple's private framework headers. Run this perl script:</p> <p><a href="http://arstechnica.com/apple/news/2008/11/dumping-the-iphone-2-2-frameworks.ars" rel="nofollow noreferrer">http://arstechnica.com/apple/news/2008/11/dumping-the-iphone-2-2-frameworks.ars</a></p> <p>and navigate to the PhotoLibrary directory under PrivateFrameworks. Some of the classes in here look pretty promising for direct camera access.</p> <p>Using the undocumented API could hurt your chances of passing through the app store, but it's all very subjective - If your product is good, apple will probably let it slide through. I'd recommend making friends with a developer evangelist at Apple.</p>
327,701
Common Design Patterns for use in MVC Web Applications
<p>I am trying to coach some guys on building web applications. They understand and use MVC, but I am interested in other common patterns that you use in building web apps. </p> <p>So, what patterns have you found to fit nicely into a properly MVC app. Perhaps something for Asynchronous processes, scheduled tasks, dealing with email, etc. What do you wish you knew to look for, or avoid? </p> <p>Not that it matters for this question, but we are using ASP.NET and Rails for most of our applications.</p>
327,750
4
0
null
2008-11-29 16:58:56.317 UTC
15
2008-11-29 17:42:58.503 UTC
null
null
null
fuzzymonk
19,839
null
1
16
model-view-controller|design-patterns
11,455
<p>Once you get into MVC, it can be worthwhile to explore patterns beyond the "Gang of Four" book, and get into Martin Fowler's "<a href="http://martinfowler.com/eaaCatalog/index.html" rel="noreferrer">Patterns of Enterprise Application Architecture</a>."</p> <p>The <a href="http://martinfowler.com/eaaCatalog/registry.html" rel="noreferrer">Registry</a> pattern can be useful to make well-known objects available throughout the object hierarchy. Essentially a substitute for using global data.</p> <p>Many MVC frameworks also employ the <a href="http://martinfowler.com/eaaCatalog/frontController.html" rel="noreferrer">Front Controller</a> and the <a href="http://martinfowler.com/eaaCatalog/twoStepView.html" rel="noreferrer">Two-Step View</a> patterns.</p> <p>The "Model" in MVC is best designed as the <a href="http://martinfowler.com/eaaCatalog/domainModel.html" rel="noreferrer">Domain Model</a> pattern, although some frameworks (led by Rails) <a href="http://wiki.rubyonrails.org/rails/pages/Models" rel="noreferrer">conflate</a> the Model with the <a href="http://martinfowler.com/eaaCatalog/activeRecord.html" rel="noreferrer">ActiveRecord</a> pattern. I often <a href="http://karwin.blogspot.com/2008/05/activerecord-does-not-suck.html" rel="noreferrer">advise</a> that the relationship between a Model and ActiveRecord should be HAS-A, instead of IS-A.</p> <p>Also read about <a href="http://c2.com/cgi/wiki?ModelViewController" rel="noreferrer">ModelViewController</a> at the Portland Pattern Repository wiki. There is some good discussion about MVC, object-orientation, and other patterns that complement MVC, such as <a href="http://c2.com/cgi/wiki?ObserverPattern" rel="noreferrer">Observer</a>.</p>
702,256
F# extension methods in C#
<p>If you were to define some extension methods, properties in an assembly written in F#, and then use that assembly in C#, would you see the defined extensions in C#?</p> <p>If so, that would be so cool.</p>
702,321
4
1
null
2009-03-31 17:54:30.927 UTC
18
2016-09-24 16:57:40.313 UTC
2014-03-12 05:28:57.07 UTC
null
41,956
Joan Venge
51,816
null
1
38
c#|f#|extension-methods
7,001
<pre><code>[&lt;System.Runtime.CompilerServices.Extension&gt;] module Methods = [&lt;System.Runtime.CompilerServices.Extension&gt;] let Exists(opt : string option) = match opt with | Some _ -&gt; true | None -&gt; false </code></pre> <p>This method could be used in C# only by adding the namespace (using using) to the file where it will be used.</p> <pre><code>if (p2.Description.Exists()) { ...} </code></pre> <p><a href="http://langexplr.blogspot.com/2008/06/using-f-option-types-in-c.html" rel="noreferrer">Here is a link to the original blogpost.</a></p> <p>Answering question in comments "Extension Static Methods":</p> <pre><code>namespace ExtensionFSharp module CollectionExtensions = type System.Linq.Enumerable with static member RangeChar(first:char, last:char) = {first .. last} </code></pre> <p>In F# you call it like so:</p> <pre><code>open System.Linq open ExtensionFSharp.CollectionExtensions let rangeChar = Enumerable.RangeChar('a', 'z') printfn "Contains %i items" rangeChar.CountItems </code></pre> <p>In C# you call it like so:</p> <pre><code>using System; using System.Collections.Generic; using ExtensionFSharp; class Program { static void Main(string[] args) { var method = typeof (CollectionExtensions).GetMethod("Enumerable.RangeChar.2.static"); var rangeChar = (IEnumerable&lt;char&gt;) method.Invoke(null, new object[] {'a', 'z'}); foreach (var c in rangeChar) { Console.WriteLine(c); } } } </code></pre> <p>Now, give me my freaking medal!</p>
1,228,709
Best practices for integration tests with Maven?
<p>I have a project which I am building with Maven which uses Hibernate (and Spring) to retrieve data from a database, etc.</p> <p>My "tests" for the DAOs in my project extend Spring's <code>AbstractTransactionalDataSourceSpringContextTests</code> so that a DataSource can be wired into my class under test to be able to actually run the query/Hibernate logic, to fetch data, etc.</p> <p>On several other projects I've used these types of test in concert with a HSQL database (either in-memory or pointed at a file) to be able to efficiently test the actual database querying logic without relying on an external database. This works great, since it avoids any external dependencies and the "state" of the database prior to running the tests (each of which are wrapped in a transaction which is rolled back) is well defined.</p> <p>I'm curious though about the best way to organize these tests, which are really a loose flavor of integration tests, with Maven. It feels a bit dirty to keep these tests in <code>src/test/java</code>, but from what I've read there doesn't seem to be a consistent strategy or practice for organizing integration tests with Maven.</p> <p>From what I've read so far, seems like I can use the <a href="http://mojo.codehaus.org/failsafe-maven-plugin/usage.html" rel="noreferrer">Failsafe plugin</a> (or a second instance of Surefire) and bind it to the <code>integration-test</code> phase, and that I can also bind custom start-up or shutdown logic (such as for starting/stopping the HSQL instance) to <code>pre-integration-test</code> or <code>post-integration-test</code>. But, is this really the best method?</p> <p>So my question basically is - what is the generally accepted best practice on organizing this with Maven? I'm having trouble finding any sort of consistent answer in the documentation.</p> <p>What I'd like is to:</p> <ul> <li>Seperate unit tests from integration tests, so only unit tests are run during the <code>test</code> phase</li> <li>The ability to bind custom startup/shutdown logic to <code>pre-integration-test</code> and <code>post-integration-test</code></li> <li>Have the reports from the integration-tests merged/presented with the unit test Surefire reports</li> </ul>
1,229,211
4
1
null
2009-08-04 17:00:21.817 UTC
39
2016-04-27 05:59:39.86 UTC
2009-08-07 10:56:06.063 UTC
null
123,582
null
4,249
null
1
68
java|testing|maven-2|integration-testing
31,787
<p>There is this <a href="http://docs.codehaus.org/display/MAVENUSER/Maven+and+Integration+Testing" rel="nofollow noreferrer">codehaus page</a> with some guidelines. I found the failsafe plugin a bit of a hack, and it makes running the unit tests in Eclipse fiendishly complicated. I do broadly what you're describing.</p> <p>Define integration tests in src/itest/java In the pre-integration-test phase:</p> <ul> <li>Clear target/test-classes</li> <li>Use the <a href="http://mojo.codehaus.org/build-helper-maven-plugin/" rel="nofollow noreferrer">build-helper-maven-plugin</a>'s add-test-source goal to add the itest source location</li> <li>Use a custom Mojo to remove src/test/java from the configuration so the unit tests are not compiled again (I don't really like this, but it's needed to maintain the separation of unit and integration tests).</li> <li>Use the compiler-plugin to compile the integration tests</li> </ul> <p>Then in the integration-test phase, use the surefire-plugin to run the tests.</p> <p>Finally, bind any tidy up goals to the post-integration-test phase (though normally they're not needed as you can use the test teardown() to tidy up).</p> <p>I've not yet found a way to merge the test results as the reporting phase has passed, but I tend to view the integration tests as an added bonus, so as long as they pass the report is not so important.</p> <p>Update: I think it's worth pointing out that you can run Jetty from within your integration tests rather than using a jetty goal. This gives you much finer control over the tests. You can get more details from <a href="https://stackoverflow.com/questions/1186348/maven-ear-module-and-ejb-dependencies-tests/1186531#1186531">this answer</a> and the referenced blogs.</p>
398,237
How to use the CSV MIME-type?
<p>In a web application I am working on, the user can click on a link to a CSV file. There is no header set for the mime-type, so the browser just renders it as text. I would like for this file to be sent as a .csv file, so the user can directly open it with calc, excel, gnumeric, etc. </p> <pre><code>header('Content-Type: text/csv'); echo "cell 1, cell 2"; </code></pre> <p>This code works as expected on my computer (Isn't that how it always is?) but does not work on another computer.</p> <p>My browser is a nightly build of FF 3.0.1 (on linux). The browsers it did not work in were IE 7 and FF 3.0 (on windows)</p> <p>Are there any quirks I am unaware of?</p>
398,239
4
0
null
2008-12-29 18:08:38.417 UTC
18
2017-05-17 12:27:09.08 UTC
2012-12-20 03:28:48.083 UTC
null
548,696
theman_on_vista
null
null
1
127
php|csv|http-headers|mime
200,069
<p>You could try to force the browser to open a "Save As..." dialog by doing something like:</p> <pre><code>header('Content-type: text/csv'); header('Content-disposition: attachment;filename=MyVerySpecial.csv'); echo "cell 1, cell 2"; </code></pre> <p>Which should work across most major browsers.</p>
40,073,738
How to get the current Title of a button in Swift 3.0 , ios using sender.titleForState(.Normal)!
<p>I tried to get the <code>title</code> of a <code>button</code> in swift like below.</p> <pre><code>@IBAction func buttonAction(_ sender: Any) { let buttonTitle = sender.titleForState(.Normal)! } </code></pre> <p>but it didn't work,even it doesn't give any <code>hint</code> when we press <code>.</code> after the sender.</p> <blockquote> <p>so what is the correct way of doing this in swift 3.0</p> </blockquote> <p>Or else if we create an <code>IBOutlet</code> and then we use its <code>currentTitle</code>, it works fine like below. Why we cannot get it with <code>sender.</code> for above </p> <pre><code>@IBOutlet var thebutton: UIButton! @IBAction func buttonAction(_ sender: Any) { let buttonTitle = thebutton.currentTitle! print(buttonTitle) } </code></pre>
40,073,801
9
1
null
2016-10-16 18:16:23.777 UTC
6
2022-01-15 20:57:30.263 UTC
2016-11-16 11:54:55.657 UTC
null
793,428
null
5,729,421
null
1
20
ios|uibutton|swift3|title
38,781
<p>Because parameter <em>sender</em> is in type <code>Any</code> instead of <code>UIButton</code>. Change the method signature to:</p> <pre><code>@IBAction func buttonAction(_ sender: UIButton) { if let buttonTitle = sender.title(for: .normal) { print(buttonTitle) } } </code></pre> <p>and you should be good to go.</p>
40,060,850
C# Custom Attribute parameters
<p>I saw this answer from this link <a href="https://stackoverflow.com/questions/270187/can-i-initialize-a-c-sharp-attribute-with-an-array-or-other-variable-number-of-a">Adding parameters to custom attributes</a> of how is to add parameters on Custom Attribute </p> <pre><code>class MyCustomAttribute : Attribute { public int[] Values { get; set; } public MyCustomAttribute(params int[] values) { this.Values = values; } } [MyCustomAttribute(3, 4, 5)] class MyClass { } </code></pre> <p>Now I am wondering if can't it be write like this?</p> <pre><code>class MyCustomAttribute : Attribute { private int[] _values; public MyCustomAttribute(params int[] values) { _values = values; } } [MyCustomAttribute(3, 4, 5)] class MyClass { } </code></pre> <p>I changed the property Values into a variable _values. I also made it private and it works fine when I tried it.</p> <p>Can someone enlighten me why the accepted answer is valid?</p>
40,061,012
3
2
null
2016-10-15 15:25:59.73 UTC
0
2016-10-15 16:03:08.523 UTC
2017-05-23 12:10:30.09 UTC
null
-1
user5002462
null
null
1
12
c#|parameter-passing
41,417
<p>The accepted answer uses the public property instead of a private field. The benefit of public property is you can omit the constructor and supply the values of the properties in the default constructor.</p> <p>I change your first code, the one with public property, to something like this.</p> <pre><code>class MyCustomAttribute : Attribute { public int[] Values { get; set; } } [MyCustomAttribute(Values = new int[] { 3, 4, 5 })] class MyClass { } </code></pre>
45,378,918
specific location for inset axes
<p>I want to create a set of axes to form an inset at a specific location in the parent set of axes. It is therefore not appropriate to just use the parameter <code>loc=1,2,3</code> in the <code>inset_axes</code> as shown here:</p> <pre><code>inset_axes = inset_axes(parent_axes, width="30%", # width = 30% of parent_bbox height=1., # height : 1 inch loc=3) </code></pre> <p>However, I would like something close to this. And the answers <a href="https://stackoverflow.com/questions/14589600/matplotlib-insets-in-subplots">here</a> and <a href="https://stackoverflow.com/questions/19335900/inset-axes-anchored-to-specific-points-in-data-coordinates">here</a> seem to be answers to questions slightly more complicated than mine. </p> <p>So, the question is is there a parameter that I can replace in the above code that will allow custom locations of the inset axes within the parent axes? I've tried to use the <code>bbox_to_anchor</code> but do not understand it's specification or behavior from the <a href="https://matplotlib.org/mpl_toolkits/axes_grid/api/inset_locator_api.html" rel="noreferrer">documentation</a>. Specifically I've tried:</p> <pre><code> inset_axes = inset_axes(parent_axes, width="30%", # width = 30% of parent_bbox height=1., # height : 1 inch bbox_to_anchor=(0.4,0.1)) </code></pre> <p>to try to get the anchor for the left and bottom of the inset to be at 40% and 10% of the x and y axis respectively. Or, I tried to put it in absolute coordinates:</p> <pre><code>inset_axes = inset_axes(parent_axes, width="30%", # width = 30% of parent_bbox height=1., # height : 1 inch bbox_to_anchor=(-4,-100)) </code></pre> <p>Neither of these worked correctly and gave me a warning that I couldn't interpret. </p> <p>More generally, it seems like <code>loc</code> is a pretty standard parameter in many functions belonging to <code>matplotlib</code>, so, is there a general solution to this problem that can be used anywhere? It seems like that's what <code>bbox_to_anchor</code> is but again, I can't figure out how to use it correctly. </p>
45,379,451
2
1
null
2017-07-28 17:05:07.987 UTC
9
2018-12-07 10:44:59.7 UTC
2018-05-23 21:34:04.753 UTC
null
1,390,639
null
1,390,639
null
1
14
python|matplotlib|graph
15,761
<p>The approach you took is in principle correct. However, just like <a href="https://stackoverflow.com/a/43439132/4124317">when placing a legend</a> with <code>bbox_to_anchor</code>, the location is determined as an interplay between <code>bbox_to_anchor</code> and <code>loc</code>. Most of the explanation in the above linked answer applies here as well. </p> <p>The default <code>loc</code> for <a href="https://matplotlib.org/mpl_toolkits/axes_grid/api/inset_locator_api.html#mpl_toolkits.axes_grid1.inset_locator.inset_axes" rel="noreferrer"><code>inset_axes</code></a> is <code>loc=1</code> ("upper right"). This means that if you you specify <code>bbox_to_anchor=(0.4,0.1)</code>, those will be the coordinates of the upper right corner, not the lower left one.<br> You would therefore need to specify <code>loc=3</code> to have the lower left corner of the inset positionned at <code>(0.4,0.1)</code>. </p> <p>However, specifying a bounding as a 2-tuple only makes sense if not specifying the width and height in relative units (<code>"30%"</code>). Or in other words, in order to use relative units you need to use a 4-tuple notation for the <code>bbox_to_anchor</code>.</p> <p>In case of specifying the <code>bbox_to_anchor</code> in axes units one needs to use the <code>bbox_transform</code> argument, again, just as with legends explained <a href="https://stackoverflow.com/a/43439132/4124317">here</a>, and set it to <code>ax.transAxes</code>.</p> <pre><code>plt.figure(figsize=(6,3)) ax = plt.subplot(221) ax.set_title("100%, (0.5,1-0.3,.3,.3)") ax.plot(xdata, ydata) axins = inset_axes(ax, width="100%", height="100%", loc='upper left', bbox_to_anchor=(0.5,1-0.3,.3,.3), bbox_transform=ax.transAxes) ax = plt.subplot(222) ax.set_title("30%, (0.5,0,1,1)") ax.plot(xdata, ydata) axins = inset_axes(ax, width="30%", height="30%", loc='upper left', bbox_to_anchor=(0.5,0,1,1), bbox_transform=ax.transAxes) </code></pre> <p><a href="https://i.stack.imgur.com/TCvc0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TCvc0.png" alt="enter image description here"></a></p> <p>Find a complete example on the matplotlib page: <a href="https://matplotlib.org/gallery/axes_grid1/inset_locator_demo.html" rel="noreferrer">Inset Locator Demo</a></p> <p><strong>Another option</strong> is to use <code>InsetPosition</code> instead of <code>inset_axes</code> and to give an existing axes a new position. <code>InsetPosition</code> takes the x and y coordinates of the lower left corner of the axes in normalized axes coordinates, as well as the width and height as input.</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import InsetPosition fig, ax= plt.subplots() iax = plt.axes([0, 0, 1, 1]) ip = InsetPosition(ax, [0.4, 0.1, 0.3, 0.7]) #posx, posy, width, height iax.set_axes_locator(ip) iax.plot([1,2,4]) plt.show() </code></pre> <p><strong>Finally</strong> one should mention that from matplotlib 3.0 on, you can use <a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.inset_axes.html" rel="noreferrer"><code>matplotlib.axes.Axes.inset_axes</code></a></p> <pre><code>import matplotlib.pyplot as plt plt.figure(figsize=(6,3)) ax = plt.subplot(221) ax.set_title("ax.inset_axes, (0.5,1-0.3,.3,.3)") ax.plot([0,4], [0,10]) axins = ax.inset_axes((0.5,1-0.3,.3,.3)) plt.show() </code></pre> <p>The result is roughly the same, except that <code>mpl_toolkits.axes_grid1.inset_locator.inset_axes</code> allows for a padding around the axes (and applies it by default), while <code>Axes.inset_axes</code> does not have this kind of padding. </p> <p><a href="https://i.stack.imgur.com/EhPqu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EhPqu.png" alt="enter image description here"></a></p>
22,290,352
How to install missing woocommerce pages from tools menu in woocommerce 2.1.5
<p>I have recently installed WooCommerce 2.1.5 that skipped logout and change password links during pages install.</p> <p>In WooCommerce documentation, the WooCommerce team mentioned that there is a feature to add missing pages from tools menu but when I go to the tools menu, I don't see any button to install missing pages.</p> <p>How can I get it done?</p> <p>Is there any step I have missed?</p> <p>Do I need to install a plugin in order to get that button showing in the tools menu?</p>
22,386,746
6
0
null
2014-03-10 00:51:52.27 UTC
6
2022-05-26 08:25:56.903 UTC
2018-02-27 10:21:53.377 UTC
null
1,527,059
null
1,527,059
null
1
23
wordpress|woocommerce|woothemes
75,775
<p>This can be done by: </p> <ol> <li>Go to the "System Status" tab on Woocommerce</li> <li>Click on the "Tools" tab at the top of the page</li> <li>On that page, the ninth option down is called "create pages".</li> <li>Clicking that will "install all the missing WooCommerce pages. Pages already defined and set up will not be replaced."</li> </ol>
47,269,189
CSS class for pointer cursor
<p>Is there any CSS class or attribute for <code>pointer:cursor</code> in <a href="https://getbootstrap.com/docs/4.0/components/buttons/" rel="noreferrer">Bootstrap 4</a> specially for button or link?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;button type="button" class="btn btn-success"&gt;Sample Button&lt;/button&gt;</code></pre> </div> </div> </p>
62,228,646
11
0
null
2017-11-13 16:34:57.113 UTC
14
2022-09-01 06:47:35.303 UTC
2021-02-16 20:12:52.507 UTC
null
3,345,644
null
5,589,714
null
1
132
css|twitter-bootstrap|bootstrap-4
421,266
<p>As of June 2020, adding <code>role='button'</code> to any HTML tag would add <code>cursor: &quot;pointer&quot;</code> to the element styling.</p> <pre><code>&lt;span role=&quot;button&quot;&gt;Non-button element button&lt;/span&gt; </code></pre> <p>Official discussion on this feature - <a href="https://github.com/twbs/bootstrap/issues/23709" rel="noreferrer">https://github.com/twbs/bootstrap/issues/23709</a></p> <p>Documentation link - <a href="https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons" rel="noreferrer">https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons</a></p>
39,788,972
ffmpeg overwrite output file if exists
<p>I ran:</p> <pre><code>ffmpeg -i input.flac output.mp3 </code></pre> <p>This prompts:</p> <blockquote> <p>File 'output.mp3' already exists. Overwrite? [y/N] y</p> </blockquote> <p>How do I automatically say &quot;yes&quot;?</p>
39,789,131
3
0
null
2016-09-30 10:08:09.44 UTC
18
2022-05-05 08:04:47.863 UTC
2021-07-14 20:30:59.577 UTC
null
365,102
null
3,731,614
null
1
236
ffmpeg
152,448
<p>Use the <code>-y</code> option to automatically overwrite [<a href="https://ffmpeg.org/ffmpeg.html#Main-options" rel="noreferrer">docs</a>]:</p> <pre><code>ffmpeg -y -i input.flac output.mp3 </code></pre>
20,479,904
Set up custom subdomain for Jekyll Blog hosted in Github Pages
<p>I created a Jekyll-powered blog and am hosting it with GitHub Pages.</p> <p>Now, I want to set up a subdomain (blog.example.com), but can't make it work.</p> <p>I have added a CNAME file with the text: blog.example.com. And I have added two A records in my Dreamhost account for the subdomain, both pointing to 204.232.175.78, provided by GitHub.</p> <p>Any idea about what the missing part is, or if I'm doing something incorrectly?</p>
20,483,041
2
1
null
2013-12-09 20:18:52.78 UTC
22
2021-04-12 14:01:08.697 UTC
2021-04-12 14:01:08.697 UTC
null
3,084,211
null
3,084,211
null
1
21
github|subdomain|jekyll|host|github-pages
8,890
<p>The setup is different for domains like <code>example.com</code> and sub-domains like <code>blog.example.com</code>.</p> <h3>In case of a sub-domain: blog.example.com</h3> <ol> <li>Go to <strong>Domains | Manage Domains</strong> in your webpanel</li> <li>Locate <code>blog.example.com</code>, click <strong>Delete</strong> in the <strong>Actions</strong> column</li> <li>Wait 10 minutes, and then click the <strong>DNS</strong> link below <code>example.com</code></li> <li>Add a <code>CNAME</code> record: <ul> <li><strong>Name</strong> = <code>blog</code></li> <li><strong>Type</strong> = <code>CNAME</code></li> <li><strong>Value</strong> = <code>yourusername.github.io.</code> (yes there is a <code>.</code> at the end!)</li> </ul></li> </ol> <h3>In case of a domain: example.com</h3> <ol> <li>Go to <strong>Domains | Manage Domains</strong> in your webpanel</li> <li>Locate <code>example.com</code>, click <strong>Edit</strong> in the <strong>Actions</strong> column and switch to <strong>DNS only</strong> hosting (it's at the bottom)</li> <li>Go back to <strong>Domains | Manage Domains</strong> in your webpanel</li> <li>Click the <strong>DNS</strong> link below <code>example.com</code></li> <li>Add an <code>A</code> record: <ul> <li><strong>Name</strong> = (blank, nothing)</li> <li><strong>Type</strong> = <code>A</code></li> <li><strong>Value</strong> = <code>185.199.108.153</code> (GitHub, from <a href="https://help.github.com/articles/tips-for-configuring-an-a-record-with-your-dns-provider/#configuring-an-a-record-with-your-dns-provider" rel="noreferrer">this page</a>)</li> </ul></li> <li>Add a <code>CNAME</code> record: <ul> <li><strong>Name</strong> = <code>www</code></li> <li><strong>Type</strong> = <code>CNAME</code></li> <li><strong>Value</strong> = <code>yourusername.github.io.</code> (yes there is a <code>.</code> at the end!)</li> </ul></li> </ol> <p>(Yes, you need both the <code>A</code> and <code>CNAME</code> records in this case.)</p> <p>Btw, the only reason I know this is because I did the same thing last weekend. I was quite lost, but the helpful support guys helped me half way, and I figured out the rest. This procedure works for me, I needed both cases so I tested both.</p>
32,352,982
How to put methods onto the objects in Redux state?
<p>According to <a href="http://rackt.github.io/redux/docs/Glossary.html#state">docs</a> state of react app has to be something serializable. What about classes then?</p> <p>Let's say I have a ToDo app. Each of <code>Todo</code> items has properties like <code>name</code>, <code>date</code> etc. so far so good. Now I want to have methods on objects which are non serializable. I.e. <code>Todo.rename()</code> which would rename todo and do a lot of other stuff.</p> <p>As far as I understand I can have function declared somewhere and do <code>rename(Todo)</code> or perhaps pass that function via props <code>this.props.rename(Todo)</code> to the component.</p> <p>I have 2 problems with declaring <code>.rename()</code> somewhere: 1) Where? In reducer? It would be hard to find all <code>would be instance</code> methods somewhere in the reducers around the app. 2) Passing this function around. Really? should I manually pass it from all the higher level components via And each time I have more methods add a ton of boilerplate to just pass it down? Or always do and hope that I only ever have one rename method for one type of object. Not <code>Todo.rename()</code> <code>Task.rename()</code> and <code>Event.rename()</code></p> <p>That seems silly to me. Object should know what can be done to it and in which way. Is not it?</p> <p>What I'm missing here?</p>
32,922,984
3
3
null
2015-09-02 12:20:07.217 UTC
11
2017-11-20 03:02:12.18 UTC
2015-10-03 13:12:13.41 UTC
null
458,193
null
946,015
null
1
51
javascript|reactjs|flux|redux
27,486
<p>In Redux, you don't really have custom models. Your state should be plain objects (or Immutable records). They are not expected to have any custom methods.</p> <p>Instead of putting methods onto the models (e.g. <code>TodoItem.rename</code>) you are expected to <strong>write reducers that handle actions</strong>. That's the whole point of Redux.</p> <pre><code>// Manages single todo item function todoItem(state, action) { switch (action.type) { case 'ADD': return { name: action.name, complete: false }; case 'RENAME': return { ...state, name: action.name }; case 'TOGGLE_COMPLETE': return { ...state, complete: !state.complete }; default: return state; } } // Manages a list of todo items function todoItems(state = [], action) { switch (action.type) { case 'ADD': return [...state, todoItem(undefined, action)]; case 'REMOVE': return [ ...state.slice(0, action.index), ...state.slice(action.index + 1) ]; case 'RENAME': case 'TOGGLE_COMPLETE': return [ ...state.slice(0, action.index), todoItem(state[action.index], action), ...state.slice(action.index + 1) ]; } } </code></pre> <p>If this still doesn't make sense please read through the <a href="http://rackt.github.io/redux/docs/basics/index.html" rel="noreferrer">Redux basics tutorial</a> because you seem to have a wrong idea about how Redux applications are structured.</p>
4,151,637
PyQT4: Drag and drop files into QListWidget
<p>I've been coding a OCR book scanning thing (it renames pages by reading the page number), and have switched to a GUI from my basic CLI Python script.</p> <p>I'm using PyQT4 and looked at a ton of documents on drag and drop, but no luck. It just refuses to take those files! I was using these to articles for my UI design:</p> <ol> <li><p><a href="http://tech.xster.net/tips/pyqt-drag-images-into-list-widget-for-thumbnail-list/" rel="noreferrer">http://tech.xster.net/tips/pyqt-drag-images-into-list-widget-for-thumbnail-list/</a></p></li> <li><p><a href="http://zetcode.com/tutorials/pyqt4/dragdrop/" rel="noreferrer">http://zetcode.com/tutorials/pyqt4/dragdrop/</a></p></li> </ol> <p>I noticed that there are a TON of ways to setup a PyQT4 GUI. Which one works the best?</p> <p>Oops, here's the source code for the project.</p> <p>The main script:</p> <pre><code>import sys from PyQt4 import QtCore from PyQt4 import QtGui from PyQt4.QtGui import QListWidget from layout import Ui_window class StartQT4(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_window() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.listWidget, QtCore.SIGNAL("dropped"), self.picture_dropped) def picture_dropped(self, l): for url in l: if os.path.exists(url): picture = Image.open(url) picture.thumbnail((72, 72), Image.ANTIALIAS) icon = QIcon(QPixmap.fromImage(ImageQt.ImageQt(picture))) item = QListWidgetItem(os.path.basename(url)[:20] + "...", self.pictureListWidget) item.setStatusTip(url) item.setIcon(icon) class DragDropListWidget(QListWidget): def __init__(self, type, parent = None): super(DragDropListWidget, self).__init__(parent) self.setAcceptDrops(True) self.setIconSize(QSize(72, 72)) def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() l = [] for url in event.mimeData().urls(): l.append(str(url.toLocalFile())) self.emit(SIGNAL("dropped"), l) else: event.ignore() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = StartQT4() myapp.show() sys.exit(app.exec_()) </code></pre> <p>And the UI file...</p> <pre><code># Form implementation generated from reading ui file 'layout.ui' # # Created: Thu Nov 11 00:22:52 2010 # by: PyQt4 UI code generator 4.8.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_window(object): def setupUi(self, window): window.setObjectName(_fromUtf8("window")) window.resize(543, 402) window.setAcceptDrops(True) self.centralwidget = QtGui.QWidget(window) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.listWidget = QtGui.QListWidget(self.centralwidget) self.listWidget.setProperty(_fromUtf8("cursor"), QtCore.Qt.SizeHorCursor) self.listWidget.setAcceptDrops(True) self.listWidget.setObjectName(_fromUtf8("listWidget")) self.verticalLayout.addWidget(self.listWidget) window.setCentralWidget(self.centralwidget) self.retranslateUi(window) QtCore.QMetaObject.connectSlotsByName(window) def retranslateUi(self, window): window.setWindowTitle(QtGui.QApplication.translate("window", "PyNamer OCR", None, QtGui.QApplication.UnicodeUTF8)) </code></pre> <p>Thanks to anybody who can help!</p>
4,176,083
1
2
null
2010-11-11 05:36:12.603 UTC
18
2010-12-22 15:57:02.943 UTC
2010-12-22 15:57:02.943 UTC
null
98,494
null
464,744
null
1
13
python|drag-and-drop|pyqt
25,246
<p>The code you're using as an example seem to work fine and looks quite clean. According to your comment your list widget is not getting initialized; this should be the root cause of your issue. I've simplified your code a bit a tried it on my Ubuntu 10.04LTS and it worked fine. My code is listed below, see if it would for you also. You should be able to drag and drop a file into the list widget; once it's dropped a new item is added showing the image and image's file name. </p> <pre><code>import sys import os from PyQt4 import QtGui, QtCore class TestListView(QtGui.QListWidget): def __init__(self, type, parent=None): super(TestListView, self).__init__(parent) self.setAcceptDrops(True) self.setIconSize(QtCore.QSize(72, 72)) def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() links = [] for url in event.mimeData().urls(): links.append(str(url.toLocalFile())) self.emit(QtCore.SIGNAL("dropped"), links) else: event.ignore() class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.view = TestListView(self) self.connect(self.view, QtCore.SIGNAL("dropped"), self.pictureDropped) self.setCentralWidget(self.view) def pictureDropped(self, l): for url in l: if os.path.exists(url): print(url) icon = QtGui.QIcon(url) pixmap = icon.pixmap(72, 72) icon = QtGui.QIcon(pixmap) item = QtGui.QListWidgetItem(url, self.view) item.setIcon(icon) item.setStatusTip(url) def main(): app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() if __name__ == '__main__': main() </code></pre> <p>hope this helps, regards</p>
14,326,103
How do I get a product key for Visual Studio Express Desktop 2012 if I am not a business?
<p>I have been using VS Express 2012 for almost a month and now it states that I must enter a product key to continue using it. To get that product key I am asked to register. Only after creating a Microsoft account (great, another account to keep track of) does it inform me that I must enter details about my company, its address, its employees, and my role in it.<br> Is there a way for individuals or hobbyists to use Express or is it intended for businesses only? Is there any way to get a product key without entering fake business information (or is fake information the standard response to frustrating forms)?</p>
14,326,462
1
6
null
2013-01-14 20:28:14.407 UTC
null
2013-01-14 21:00:29.867 UTC
null
null
null
null
1,860,611
null
1
5
visual-studio|visual-studio-2012|registration|product-key
99,578
<p>Visual Studio 2012 Express for Desktop (or any other flavor) is distributed free of charge. It is not intended for businesses only. Go ahead and register it and use it.</p> <p>Now as for what to enter, I try to be as truthful as possible on forms that ask questions that there isn't a good answer for. In general:</p> <ul> <li>Business Name: My name (or sometimes N/A)</li> <li>Business Address: My home address</li> <li>Employees: 1</li> <li>My role: Sole Employee</li> </ul>
13,907,048
Get the number of elements in a json object using jquery
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5317298/find-length-size-of-an-array-in-jquery">Find length (size) of an array in jquery</a> </p> </blockquote> <p>I have a json object returned from a php file as follows:-</p> <pre><code>{"food":[ { "name" :"Belgian Waffles", "price" :"$5.95", "description":"two of our famous Belgian Waffles with plenty of real maple syrup", "calories" :"650" }, { "name" :"Strawberry Belgian Waffles", "price" :"$7.95", "description":"light Belgian waffles covered with strawberries and whipped cream", "calories" :"900" }, { "name" :"Berry-Berry Belgian Waffles", "price" :"$8.95", "description":"light Belgian waffles covered with an assortment of fresh berries and whipped cream", "calories" :"900" } ]} </code></pre> <p>This is essentially returning three food elements from the object. How can I get a count of the total number of elements being returned if the json data is dynamic and not known using jquery?</p>
13,907,068
3
1
null
2012-12-17 00:55:45.383 UTC
2
2012-12-17 02:25:13.097 UTC
2017-05-23 12:02:11.563 UTC
null
-1
null
1,197,319
null
1
6
jquery|json
60,244
<p>Assuming you've parsed the JSON (or jQuery has done it for you, which it will if you use its Ajax functions) and you have the resulting object in a variable, just do this:</p> <pre><code>var data = /* your parsed JSON here */ var numberOfElements = data.food.length; </code></pre> <p>(Note: <a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/">There's no such thing as a JSON object</a>: before you parse JSON it's a <em>string;</em> after you parse it it's an <em>object.</em>)</p> <p>EDIT: In a comment you said you wouldn't know that the property is called <code>food</code> - if you <em>do</em> know that there will be exactly one property and that property will be an array you can do this:</p> <pre><code>var data = /* your object */ var propName; var numberOfElements; for (propName in data); numberOfElements = propName ? data[propName].length : 0; </code></pre> <p>If you <em>don't</em> know that there will be exactly one property then your requirement is too vague: if there might be multiple properties which one would you want to check the length of?</p>
14,156,625
Fetching tweets with hashtag from Twitter using Python
<p>How do we find or fetch tweets on the basis of hash tag. i.e. I want to find tweets regarding on a certain subject? Is it possible in Python using Twython?</p> <p>Thanks </p>
14,177,040
1
1
null
2013-01-04 11:49:01.123 UTC
9
2019-09-07 20:43:25.787 UTC
2013-01-07 15:39:40.91 UTC
null
1,147,918
null
1,758,521
null
1
6
python|twitter|twython
23,804
<p><strong>EDIT</strong> My original solution using Twython's hooks for the Search API appears to be no longer valid because Twitter now wants users authenticated for using Search. To do an authenticated search via Twython, just supply your Twitter authentication credentials when you initialize the Twython object. Below, I'm pasting an example of how you can do this, but you'll want to consult the Twitter API documentation for <a href="https://dev.twitter.com/docs/api/1.1/get/search/tweets" rel="nofollow noreferrer">GET/search/tweets</a> to understand the different optional parameters you can assign in your searches (for instance, to page through results, set a date range, etc.)</p> <pre><code>from twython import Twython TWITTER_APP_KEY = 'xxxxxx' #supply the appropriate value TWITTER_APP_KEY_SECRET = 'xxxxxx' TWITTER_ACCESS_TOKEN = 'xxxxxxx' TWITTER_ACCESS_TOKEN_SECRET = 'xxxxxx' t = Twython(app_key=TWITTER_APP_KEY, app_secret=TWITTER_APP_KEY_SECRET, oauth_token=TWITTER_ACCESS_TOKEN, oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET) search = t.search(q='#omg', #**supply whatever query you want here** count=100) tweets = search['statuses'] for tweet in tweets: print tweet['id_str'], '\n', tweet['text'], '\n\n\n' </code></pre> <hr> <p><strong>Original Answer</strong></p> <p>As indicated <a href="https://github.com/ryanmcgrath/twython/blob/master/core_examples/search_results.py" rel="nofollow noreferrer">here in the Twython documentation</a>, you can use Twython to access the Twitter Search API:</p> <pre><code>from twython import Twython twitter = Twython() search_results = twitter.search(q="#somehashtag", rpp="50") for tweet in search_results["results"]: print "Tweet from @%s Date: %s" % (tweet['from_user'].encode('utf-8'),tweet['created_at']) print tweet['text'].encode('utf-8'),"\n" </code></pre> <p>etc... Note that for any given search, you're probably going to max out at around 2000 tweets at most, going back up to around a week or two. You can read more about the Twitter Search API <a href="https://dev.twitter.com/docs/api/1.1/get/search/tweets" rel="nofollow noreferrer">here</a>.</p>
31,547,466
Is x = std::move(x) undefined?
<p>Let <code>x</code> be a variable of some type that has been previously initialized. Is the following line:</p> <pre><code>x = std::move(x) </code></pre> <p>undefined? Where is this in the standard and what does it say about it?</p>
31,547,722
3
6
null
2015-07-21 19:00:28.61 UTC
7
2018-10-04 20:26:02.26 UTC
2018-10-04 20:26:02.26 UTC
null
225,186
null
855,050
null
1
61
c++|c++11|language-lawyer|c++14
3,117
<p>No, this is not undefined behavior, it is going to be implementation defined behavior, it will depend on how move assignment is implemented.</p> <p>Relevant to this is <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2468" rel="nofollow noreferrer">LWG issue 2468: Self-move-assignment of library types </a>, note this is an active issue and does not have an official proposal so this should be considered indicative rather than definitive, but it does point out the sections that are involved for the standard library and points out they currently conflict. It says:</p> <blockquote> <p>Suppose we write</p> <pre><code>vector&lt;string&gt; v{"a", "b", "c", "d"}; v = move(v); </code></pre> <p>What should be the state of v be? The standard doesn't say anything specific about self-move-assignment. There's relevant text in several parts of the standard, and it's not clear how to reconcile them.</p> <p>[...]</p> <p>It's not clear from the text how to put these pieces together, because it's not clear which one takes precedence. Maybe 17.6.4.9 [res.on.arguments] wins (it imposes an implicit precondition that isn't mentioned in the MoveAssignable requirements, so v = move(v) is undefined), or maybe 23.2.1 [container.requirements.general] wins (it explicitly gives additional guarantees for Container::operator= beyond what's guaranteed for library functions in general, so v = move(v) is a no-op), or maybe something else.</p> <p>On the existing implementations that I checked, for what it's worth, v = move(v) appeared to clear the vector; it didn't leave the vector unchanged and it didn't cause a crash. </p> </blockquote> <p>and proposes:</p> <blockquote> <p>Informally: change the MoveAssignable and Container requirements tables (and any other requirements tables that mention move assignment, if any) to make it explicit that x = move(x) is defined behavior and it leaves x in a valid but unspecified state. That's probably not what the standard says today, but it's probably what we intended and it's consistent with what we've told users and with what implementations actually do. </p> </blockquote> <p>Note, for built-in types this is basically a copy, we can see from draft C++14 standard section <code>5.17</code> <em>[expr.ass]</em>:</p> <blockquote> <p>In simple assignment (=), the value of the expression replaces that of the object referred to by the left operand.</p> </blockquote> <p>which is different than the case for classes, where <code>5.17</code> says:</p> <blockquote> <p>If the left operand is of class type, the class shall be complete. Assignment to objects of a class is defined by the copy/move assignment operator (12.8, 13.5.3).</p> </blockquote> <p>Note, clang has a <a href="http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20150105/120983.html" rel="nofollow noreferrer">self move warning</a>:</p> <blockquote> <p>Log: Add a new warning, -Wself-move, to Clang.</p> <p>-Wself-move is similiar to -Wself-assign. This warning is triggered when a value is attempted to be moved to itself. See r221008 for a bug that would have been caught with this warning.</p> </blockquote>
39,253,307
Export GIT LOG into an Excel file
<p>I have looked into the forum, but with no luck.</p> <p>Requirement :</p> <p>Run GIT LOG (format) command and write the results into an Excel File . </p> <p>I have seen examples wherein with GIT Log command, data can be written into a CSV, but formatting is double the effort.</p> <p>Any utility or approach would be helpful.</p> <p>Thanks Milind</p>
39,269,572
2
4
null
2016-08-31 15:13:57.723 UTC
13
2019-07-05 20:18:03.687 UTC
null
null
null
null
3,398,578
null
1
32
git|logging
30,423
<p>Git gives your the control on how to format the log output using <code>pretty</code> option. Check this out:</p> <pre><code>git log --pretty=format:%h,%an,%ae,%s </code></pre> <p>This prints the log in the format of (hash [abbreviated], author name, author email, subject).</p> <p>To see the full list of format options:</p> <pre><code>git help log </code></pre> <p>And scroll down until you see the list of format options.</p> <p>To redirect the output, use <code>&gt;</code> redirection operator as follows:</p> <pre><code>git log --pretty=format:%h,%an,%ae,%s &gt; /path/to/file.csv </code></pre>
19,899,299
Querying MongoDB to match in the first item in an array
<p>I'm aware of the <code>$in</code> operator, which appears to search for an item's presence in array, but I only want to find a match if the item is in the first position in an array.</p> <p>For instance:</p> <pre><code>{ "_id" : ObjectId("0"), "imgs" : [ "http://foo.jpg", "http://bar.jpg", "http://moo.jpg", ] }, { "_id" : ObjectId("1"), "imgs" : [ "http://bar.jpg", "http://foo.jpg", "http://moo.jpg", ] } </code></pre> <p>I'm looking for a query akin to:</p> <pre><code>db.products.find({"imgs[0]": "http://foo.jpg"}) </code></pre> <p>This would/should return the <code>ObjectId("0")</code> but not <code>ObjectId("1")</code>, as it's only checking against the first image in the array.</p> <p>How can this be achieved? I'm aware I could just create a separate field which contains a single string for <code>firstImg</code> but that's not really what I'm after here.</p>
19,899,347
2
0
null
2013-11-11 05:15:17.717 UTC
10
2016-01-18 15:56:35.24 UTC
null
null
null
null
556,006
null
1
61
arrays|mongodb|mongodb-query
80,381
<p>I believe you want <code>imgs.0</code>. eg, given your example document, you want to say: <code>db.products.find({"imgs.0": "http://foo.jpg"})</code></p> <p>Be aware that referencing array indexes only works for the first-level array. Mongo doesn't support searching array indexes any deeper.</p>
20,135,841
Rails 4 static assets in public/ or app/assets/
<p>Sorry if this is a lengthy buildup to a simple question, but I wanted to get my thoughts clear.</p> <p>I've used Rails 4 on a couple projects now and I've been using <code>image_tag('/assets/image.png')</code> to get around the changes to how asset path helpers work in Rails 4. That is until today when I decided to learn more about the changes and found <a href="https://github.com/rails/sprockets-rails#changes-from-rails-3x" rel="nofollow noreferrer">this first change note in sprockets-rails</a>. I've also noted that the <code>ASSET_PUBLIC_DIRECTORIES</code> in /actionview/lib/action_view/helpers/asset_url_helper.rb#L170 in Rails helpers only point to public folders. It became pretty obvious to me that if you are accessing static files, Rails wants you to use use the public folder.</p> <p>So now that I've figured this out, I just can't understand why the <strong>edge rails docs</strong> clearly state this:</p> <blockquote> <p>In previous versions of Rails, all assets were located in subdirectories of public such as images, javascripts and stylesheets. With the asset pipeline, the preferred location for these assets is now the app/assets directory.</p> </blockquote> <p>image_path in practice generates a uri to the public/images folder which is totally contrary.</p> <p>And to sum this all up I do need to use all available helpers and digest builders, because I end up deploying my assets to S3 with <a href="https://github.com/rumblelabs/asset_sync" rel="nofollow noreferrer">asset_sync</a>.</p> <p>So my question is just; is there a <strong>correct</strong> place to put images/non-compiled assets and use asset_path helpers? All the documentation and every other stack overflow conversation is about people using the app/assets folder, but sprockets-rails wants us to use public for non-digest assets. Are the docs and info on the web just in need of an update, or are others just making due with prepending all asset paths with /assets/?</p> <p><strong>UPDATE: I think I did actually have an issue where I wasn't restarting my development server and images in app/assets/images were not showing up so it would fallback to public. Also note that I was using asset helpers in my paperclip default_url (which is referenced as the way to point to assets in several stack overflow answers I found, however using the asset path helpers with interpolated options in paperclip will also fallback to public, because the uninterpolated asset name wouldn't be found as an existing file obviously.</strong></p>
21,585,826
1
1
null
2013-11-22 02:24:17.293 UTC
9
2020-08-03 05:20:46.773 UTC
2020-08-03 05:20:46.773 UTC
null
214,143
null
597,980
null
1
20
ruby-on-rails-4|asset-pipeline|sprockets|asset-sync
20,241
<p>When you use <code>rake assets:precompile</code>, Rails moves all of the assets from your <code>app/assets</code> folder, to <code>public/assets</code>. This is as a normal browser does not have access to your <code>app</code> directory, but does have access to <code>public</code>.</p> <p>So, to answer your question, here are my thoughts. If your images are for your sites layout e.g logos or backgrounds, then you should store them in the <code>app/assets/images</code> directory, however, if the images are user generated, such as profile images, then these should be stored directly in something such as <code>public/images</code>. Ideally you would store those in S3 or a CDN, but you're already doing that.</p> <p>As a bonus, Carrierwave, a Rails image upload gem, uses a <code>public/images</code> type path as the default store for its images, as you can see in their config file:</p> <pre><code> # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "images/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end </code></pre> <p>Hope this helps!</p>
20,101,834
pip install from git repo branch
<p>Trying to <code>pip</code> install a repo's specific branch. Google tells me to</p> <pre><code>pip install https://github.com/user/repo.git@branch </code></pre> <p>The branch's name is <code>issue/34/oscar-0.6</code> so I did <code>pip install https://github.com/tangentlabs/django-oscar-paypal.git@/issue/34/oscar-0.6</code> but its returning a 404.</p> <p>How do I install this branch?</p>
20,101,940
8
1
null
2013-11-20 16:46:42.983 UTC
224
2022-05-02 00:12:51.893 UTC
2021-06-19 18:54:22.63 UTC
null
236,195
null
357,236
null
1
979
python|git|pip
662,769
<p>Prepend the url prefix <code>git+</code> (See <a href="https://pip.pypa.io/en/stable/topics/vcs-support/" rel="noreferrer">VCS Support</a>):</p> <pre><code>pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6 </code></pre> <p>And specify the branch name without the leading <code>/</code>.</p>
6,774,197
OpenGL ES 2.0 Object Picking on iOS
<p>What is the best method to select objects that have been drawn in OpenGL ES 2.0 (iOS)?</p> <p>I am drawing points.</p>
10,784,181
2
1
null
2011-07-21 09:47:12.35 UTC
14
2017-01-19 16:18:25.28 UTC
2017-01-19 16:18:25.28 UTC
null
815,724
user400055
null
null
1
12
ios|selection|opengl-es-2.0|picking
6,648
<p>Here is working prototype of color picking, tested on most old ipads and working well. This is actually some part of project called InCube Chess that one may find in app store. The main code you will see is located in a class derived from GLKViewController like this:</p> <pre><code>@interface IncubeViewController : GLKViewController </code></pre> <p>This means you have glkview in it: ((GLKView *)self.view).</p> <p>Here are also some properties:</p> <pre><code>@property (strong, nonatomic) EAGLContext *context; @property (strong, nonatomic) GLKBaseEffect *effect; </code></pre> <p>Don't forget to synthesize them in your *.m file.</p> <pre><code>@synthesize context = _context; @synthesize effect = _effect; </code></pre> <p>The idea is that you have chess pieces on your table (or some objects in your 3d scene) and you need to find a piece in your list of pieces by tapping on a screen. That is, you need to convert your 2d screen tap coords (@point in this case) to chess piece instance.</p> <p>Each piece has its unique id that I call a "seal". You can allocate the seals from from 1 up to something. Selection function returns piece seal found by tap coords. Then having the seal you can easily find your piece in pieces hash table or array in a way like this:</p> <pre><code>-(Piece *)findPieceBySeal:(GLuint)seal { /* !!! Black background in off screen buffer produces 0 seals. This allows to quickly filter out taps that did not select anything (will be mentioned below) !!! */ if (seal == 0) return nil; PieceSeal *sealKey = [[PieceSeal alloc] init:s]; Piece *p = [sealhash objectForKey:sealKey]; [sealKey release]; return p; } </code></pre> <p>"sealhash" is a NSMutableDictionary.</p> <p>Now this is the main selection function. Note, that my glkview is antialised and you can't use its buffers for color picking. This mean you need to create your own off screen buffer with antialiasing disabled for picking purposes only.</p> <pre><code>- (NSUInteger)findSealByPoint:(CGPoint)point { NSInteger height = ((GLKView *)self.view).drawableHeight; NSInteger width = ((GLKView *)self.view).drawableWidth; Byte pixelColor[4] = {0,}; GLuint colorRenderbuffer; GLuint framebuffer; glGenFramebuffers(1, &amp;framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glGenRenderbuffers(1, &amp;colorRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8_OES, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER, colorRenderbuffer); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { NSLog(@"Framebuffer status: %x", (int)status); return 0; } [self render:DM_SELECT]; CGFloat scale = UIScreen.mainScreen.scale; glReadPixels(point.x * scale, (height - (point.y * scale)), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixelColor); glDeleteRenderbuffers(1, &amp;colorRenderbuffer); glDeleteFramebuffers(1, &amp;framebuffer); return pixelColor[0]; } </code></pre> <p>Note that function takes into account display scale (retina or new iPads).</p> <p>Here is render() function used in function above. Note, that for rendering purposes it clear s the buffer with some background color and for selecting case it makes it black so that you can easily check if you tapped on any piece at all or not.</p> <pre><code>- (void) render:(DrawMode)mode { if (mode == DM_RENDER) glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1.0f); else glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Draw all pieces. */ for (int i = 0; i &lt; [model-&gt;pieces count]; i++) { Piece *p = [model-&gt;pieces objectAtIndex:i]; [self drawPiece:p mode:mode]; } } </code></pre> <p>Next is how we draw the piece.</p> <pre><code>- (void) drawPiece:(Piece *)p mode:(DrawMode)mode { PieceType type; [self pushMatrix]; GLKMatrix4 modelViewMatrix = self.effect.transform.modelviewMatrix; GLKMatrix4 translateMatrix = GLKMatrix4MakeTranslation(p-&gt;drawPos.X, p-&gt;drawPos.Y, p-&gt;drawPos.Z); modelViewMatrix = GLKMatrix4Multiply(modelViewMatrix, translateMatrix); GLKMatrix4 rotateMatrix; GLKMatrix4 scaleMatrix; if (mode == DM_RENDER) { scaleMatrix = GLKMatrix4MakeScale(p-&gt;scale.X, p-&gt;scale.Y, p-&gt;scale.Z); } else { /* !!! Make the piece a bit bigger in off screen buffer for selection purposes so that we always sure that we tapped it correctly by finger.*/ scaleMatrix = GLKMatrix4MakeScale(p-&gt;scale.X + 0.2, p-&gt;scale.Y + 0.2, p-&gt;scale.Z + 0.2); } modelViewMatrix = GLKMatrix4Multiply(modelViewMatrix, scaleMatrix); self.effect.transform.modelviewMatrix = modelViewMatrix; type = p-&gt;type; if (mode == DM_RENDER) { /* !!! Use real pieces color and light on for normal drawing !!! */ GLKVector4 color[pcLast] = { [pcWhite] = whitesColor, [pcBlack] = blacksColor }; self.effect.constantColor = color[p-&gt;color]; self.effect.light0.enabled = GL_TRUE; } else { /* !!! Use piece seal for color. Important to turn light off !!! */ self.effect.light0.enabled = GL_FALSE; self.effect.constantColor = GLKVector4Make(p-&gt;seal / 255.0f, 0.0f, 0.0f, 0.0f); } /* Actually normal render the piece using it geometry buffers. */ [self renderPiece:type]; [self popMatrix]; } </code></pre> <p>This is how to use the functions shown above.</p> <pre><code>- (IBAction) tapGesture:(id)sender { if ([(UITapGestureRecognizer *)sender state] == UIGestureRecognizerStateEnded) { CGPoint tap = [(UITapGestureRecognizer *)sender locationInView:self.view]; Piece *p = [self findPieceBySeal:[self findSealByPoint:tap]]; /* !!! Do something with your selected object !!! */ } } </code></pre> <p>This is basically it. You will have very precise picking algorithm that is much better than ray tracing or others.</p> <p>Here helpers for push/pop matrix things.</p> <pre><code>- (void)pushMatrix { assert(matrixSP &lt; sizeof(matrixStack) / sizeof(GLKMatrix4)); matrixStack[matrixSP++] = self.effect.transform.modelviewMatrix; } - (void)popMatrix { assert(matrixSP &gt; 0); self.effect.transform.modelviewMatrix = matrixStack[--matrixSP]; } </code></pre> <p>Here also glkview setup/cleanup functions that I used.</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; self.context = [[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2] autorelease]; if (!self.context) NSLog(@"Failed to create ES context"); GLKView *view = (GLKView *)self.view; view.context = self.context; view.drawableDepthFormat = GLKViewDrawableDepthFormat24; [self setupGL]; } - (void)viewDidUnload { [super viewDidUnload]; [self tearDownGL]; if ([EAGLContext currentContext] == self.context) [EAGLContext setCurrentContext:nil]; self.context = nil; } - (void)setupGL { [EAGLContext setCurrentContext:self.context]; self.effect = [[[GLKBaseEffect alloc] init] autorelease]; if (self.effect) { self.effect.useConstantColor = GL_TRUE; self.effect.colorMaterialEnabled = GL_TRUE; self.effect.light0.enabled = GL_TRUE; self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 1.0f, 1.0f, 1.0f); } /* !!! Draw antialiased geometry !!! */ ((GLKView *)self.view).drawableMultisample = GLKViewDrawableMultisample4X; self.pauseOnWillResignActive = YES; self.resumeOnDidBecomeActive = YES; self.preferredFramesPerSecond = 30; glDisable(GL_DITHER); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glLineWidth(2.0f); /* Load pieces geometry */ [self loadGeometry]; } - (void)tearDownGL { drawReady = NO; [EAGLContext setCurrentContext:self.context]; [self unloadGeometry]; } </code></pre> <p>Hope this helps and may be closes "the picking question" forever :)</p>
6,555,040
Multiple input in JOptionPane.showInputDialog
<p>Is there a way to create multiple input in <code>JOptionPane.showInputDialog</code> instead of just one input?</p>
6,555,051
2
0
null
2011-07-02 04:01:31.447 UTC
23
2015-03-08 19:53:36.097 UTC
2011-07-02 06:44:16.017 UTC
null
714,968
null
807,882
null
1
65
java|swing|joptionpane
171,884
<p>Yes. You know that you can put any <code>Object</code> into the <code>Object</code> parameter of most <code>JOptionPane.showXXX methods</code>, and often that <code>Object</code> happens to be a <code>JPanel</code>.</p> <p>In your situation, perhaps you could use a <code>JPanel</code> that has several <code>JTextFields</code> in it:</p> <pre><code>import javax.swing.*; public class JOptionPaneMultiInput { public static void main(String[] args) { JTextField xField = new JTextField(5); JTextField yField = new JTextField(5); JPanel myPanel = new JPanel(); myPanel.add(new JLabel("x:")); myPanel.add(xField); myPanel.add(Box.createHorizontalStrut(15)); // a spacer myPanel.add(new JLabel("y:")); myPanel.add(yField); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("x value: " + xField.getText()); System.out.println("y value: " + yField.getText()); } } } </code></pre>
7,533,711
What is the answer to the bonus question in test_changing_hashes of Ruby Koans?
<p>In the <a href="http://rubykoans.com">Ruby Koans</a>, the section about_hashes.rb includes the following code and comment:</p> <pre><code>def test_changing_hashes hash = { :one =&gt; "uno", :two =&gt; "dos" } hash[:one] = "eins" expected = { :one =&gt; "eins", :two =&gt; "dos" } assert_equal true, expected == hash # Bonus Question: Why was "expected" broken out into a variable # rather than used as a literal? end </code></pre> <p>I can't figure out the answer to the bonus question in the comment - I tried actually doing the substitution they suggest, and the result is the same. All I can figure out is that it is for readability, but I don't see general programming advice like that called out elsewhere in this tutorial.</p> <p>(I know this sounds like something that would already be answered somewhere, but I can't dig up anything authoritative.)</p>
7,533,906
3
0
null
2011-09-23 19:13:06.093 UTC
12
2020-01-08 07:56:32.14 UTC
2015-01-23 17:20:49.623 UTC
user2555451
null
null
6,310
null
1
62
ruby
5,588
<p>It's because you can't use something like this:</p> <pre><code>assert_equal { :one =&gt; "eins", :two =&gt; "dos" }, hash </code></pre> <p>Ruby thinks that <code>{ ... }</code> is a block, so it should be "broken out into a variable", but you can always use <code>assert_equal({ :one =&gt; "eins", :two =&gt; "dos" }, hash)</code></p>
7,127,521
remove ColorFilter / undo setColorFilter
<p>How can a ColorFilter be removed or setColorFilter on a view be undone?</p>
7,127,646
3
1
null
2011-08-19 21:17:33.133 UTC
4
2019-02-20 05:54:12.45 UTC
2011-11-09 23:44:15.62 UTC
null
203,458
null
450,404
null
1
72
android
33,291
<p>Have you tried setting it to <code>null</code>?</p> <p>According to <a href="http://developer.android.com/reference/android/widget/ImageView.html#setColorFilter%28android.graphics.ColorFilter%29" rel="noreferrer">Android Documentation</a>:</p> <blockquote> <p>public void setColorFilter (ColorFilter cf)</p> <p>Since: API Level 1 Apply an arbitrary colorfilter to the image. Parameters</p> <p>cf the colorfilter to apply <strong>(may be null)</strong></p> </blockquote>
7,058,267
Why use SQLiteOpenHelper over SQLiteDatabase?
<p>In my activity I have for example</p> <pre><code>SQLiteDatabase db = openOrCreateDatabase(Preferences.DB_NAME, Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value VARCHAR)"); Cursor dbResult = db.rawQuery("SELECT value FROM data", null); // do sometning with cursors dbResult.close(); db.close(); </code></pre> <p>What's the benefit of using <strong>SQLiteOpenHelper</strong> like</p> <pre><code>DatabaseHelper helper = new DatabaseHelper(this); SQLiteDatabase db = helper.getWriteableDatabase(); SQLiteDatabase db_2 = helper.getReadableDatabase(); Cursor dbResult = db_2.rawQuery("SELECT value FROM data", null); // do sometning with cursors dbResult.close(); helper.close(); </code></pre> <p>Class itself</p> <pre><code>public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, Preferences.DB_NAME, null, Preferences.DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String query = "CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value VARCHAR)"; db.execSQL(query); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } </code></pre>
7,059,190
4
0
null
2011-08-14 16:56:08.383 UTC
4
2017-11-22 13:44:04.663 UTC
null
null
null
null
455,268
null
1
38
android|sqlite
25,076
<p><a href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html" rel="noreferrer">SQLiteDatabase</a></p> <blockquote> <p>SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.</p> </blockquote> <p><a href="http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html" rel="noreferrer">SQLiteOpenHelper</a></p> <blockquote> <p>A helper class to manage database creation and version management.</p> </blockquote> <p>I will say this much, the onUpgrade that comes with SQLiteOpenHelper comes in REALLY handy when upgrading your application. It's mainly for creation and upgrading / version management. SQLiteDatabase is mainly for CRUD operations (you can create with it but that is what SQLiteOpenHelper is for).</p>
21,817,397
Event Handler Namespace in Vanilla JavaScript
<p>I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:</p> <pre><code>$('#id').on('click.namespace', _handlerFunction); </code></pre> <p>And then I can remove all event handlers in that namespace:</p> <pre><code>$('#id').off('.namespace'); </code></pre> <p>The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.</p> <p>Does anyone have any tips on how I can not use jQuery, but achieve a similar result?</p>
21,817,552
3
2
null
2014-02-16 22:10:32.663 UTC
13
2021-09-09 09:41:08.89 UTC
2019-09-19 16:46:34.553 UTC
null
4,370,109
null
1,717,740
null
1
42
javascript|namespaces|dom-events
20,907
<p>I think you are looking for <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener">addEventListener</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.removeEventListener">removeEventListener</a>. You can also define custom events and fire them using <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.dispatchEvent">dispatchEvent</a>. </p> <p>However, to remove an event listener, you will need to retain a reference to the event function to remove just the function you want to remove instead of clearing the whole event. </p>
1,532,571
How to link to a folder in document library from sharepoint list item?
<p><strong>Background:</strong></p> <p>I have an items on the sharepoint list. I also have a corresponding folder in a document library that contains documents about this item. I want to be able to get to this folder straight from the item properties. I have tried to create a lookup column containing folder ID, but that doesn't help cause folder is not a type and it just doesn't work. Other solution would be to create link column but if I will create it staticly - after creating alternative mapping (and getting to the page from the internet for example) it won't work. (so solution posted <a href="https://stackoverflow.com/questions/1042771/is-it-possible-to-create-a-link-to-a-folder-in-a-sharepoint-document-library">here</a> won't work for me).</p> <p>I want to create this link from sharepoint workflow. I have a custom action that can return any info about the folder I want (ID, URL etc).</p> <p><strong>Question:</strong></p> <p>How to link from sharepoint list item to a folder in document library?</p>
1,534,646
4
0
null
2009-10-07 16:01:55.33 UTC
0
2019-12-01 12:05:26.57 UTC
2017-05-23 12:13:50.553 UTC
null
-1
null
98,810
null
1
3
sharepoint|workflow|wss
57,738
<p>I would personally try to avoid using folders. In numerous instance I've found they arn't worth the trouble and the key with SharePoint is not to reproduce the typical folder hierarchy that you'll find on a file system. Break away from that mess and do it the SharePoint way and put the documents straight into the list and use views and metadata to break up the documents into manageable groupings.</p> <p>That said, a folder is it's own content type and it works perfectly well in a lookup column. You have to reference the list item id for the folder of course. I just created a folder in a standard document library, added a lookup column to a custom list and successfully referenced the folder in a new item. When I click the folder lookup then I get taken to the folder item, which contains an "Open" link that takes me to the documents contained within the folder.</p>
2,110,595
Redaction in git
<p>I started working on a little Python script for FTP recently. To start off with, I had server, login and password details for an FTP site hardwired in the script, but this didn't matter because I was only working on it locally.</p> <p>I then had the genius idea of putting the project on github. I realised my mistake soon after, and replaced the hardwired details with a solution involving <code>.netrc</code>. I've now removed the project from github, as anyone could look at the history, and see the login details in plain text.</p> <p>The question is, is there any way to go through the git history and remove user name and password throughout, but otherwise leave the history intact? Or do I need to start a new repo with no history?</p>
2,111,378
4
4
null
2010-01-21 15:52:47.903 UTC
12
2017-12-31 07:34:33.72 UTC
null
null
null
null
49,376
null
1
18
git
4,108
<p>First of all, you should change the password on the FTP site. The password has already been made public; you can't guarantee that no one has cloned the repo, or it's not in plain-text in a backup somewhere, or something of the sort. If the password is at all valuable, I would consider it compromised by now.</p> <p>Now, for your question about how to edit history. The <a href="http://git-scm.com/docs/git-filter-branch" rel="nofollow noreferrer"><code>git filter-branch</code></a> command is intended for this purpose; it will walk through each commit in your repository's history, apply a command to modify it, and then create a new commit.</p> <p>In particular, you want <code>git filter-branch --tree-filter</code>. This allows you to edit the contents of the tree (the actual files and directories) for each commit. It will run a command in a directory containing the entire tree, your command may edit files, add new files, delete files, move them, and so on. Git will then create a new commit object with all of the same metadata (commit message, date, and so on) as the previous one, but with the tree as modified by your command, treating new files as adds, missing files as deletes, etc (so, your command does not need to do <code>git add</code> or <code>git rm</code>, it just needs to modify the tree).</p> <p>For your purposes, something like the following should work, with the appropriate regular expression and file name depending on your exact situation:</p> <pre><code>git filter-branch --tree-filter "sed -i -e 's/SekrtPassWrd/REDACTED/' myscript.py" -- --all </code></pre> <p>Remember to do this to a copy of your repository, so if something goes wrong, you will still have the original and can start over again. <code>filter-branch</code> will also save references to your original branches, as <code>original/refs/heads/master</code> and so on, so you should be able to recover even if you forget to do this; when doing some global modification to my source code history, I like to make sure I have multiple fallbacks in case something goes wrong.</p> <p>To explain how this works in more detail:</p> <pre><code>sed -i -e 's/SekrtPassWrd/REDACTED/' myscript.py </code></pre> <p>This will replace <code>SekrtPassWrd</code> in your <code>myscript.py</code> file with <code>REDACTED</code>; the <code>-i</code> option to <code>sed</code> tells it to edit the file in place, with no backup file (as that backup would be picked up by Git as a new file).</p> <p>If you need to do something more complicated than a single substitution, you can write a script, and just invoke that for your command; just be sure to call it with an absolute pathname, as <code>git filter-branch</code> call your command from within a temporary directory.</p> <pre><code>git filter-branch --tree-filter &lt;command&gt; -- --all </code></pre> <p>This tells <code>git</code> to run a tree filter, as described above, over every branch in your repository. The <code>-- --all</code> part tells Git to apply this to all branches; without it, it would only edit the history of the current branch, leaving all of the other branches unchanged (which probably isn't what you want).</p> <p>See the documentation on GitHub on <a href="http://help.github.com/removing-sensitive-data/" rel="nofollow noreferrer">Removing Sensitive Data</a> (as <a href="https://stackoverflow.com/questions/2110595/redaction-in-git/2110667#2110667">originally pointed out by MBO</a>) for some more information about dealing with the copies of the information that have been pushed to GitHub. Note that they reiterate my advice to change your password, and provide some tips for dealing with cached copies that GitHub may still have.</p>
52,670,937
How do I convert pngs directly to android vector drawables?
<p>Are there online tools to convert png file to vector drawable files (xml in Android)?</p> <p>I have few pngs that I was using for icons &amp; various places in my app. So, now I want to convert them to xmls. Is it possible to do so?</p>
52,671,273
1
4
null
2018-10-05 17:51:00.487 UTC
18
2018-10-05 18:37:48.32 UTC
2018-10-05 18:06:48.343 UTC
null
3,623,128
null
3,623,128
null
1
33
android|png|android-vectordrawable
49,480
<p>Ok, so you can convert PNG to Android vector drawable following these steps</p> <ul> <li>Step 1: Convert PNG to SVG (Scalable Vector Graphics)</li> </ul> <p><a href="https://www.autotracer.org/" rel="noreferrer">https://www.autotracer.org/</a></p> <p>Or you can use any online converter of your choice</p> <ul> <li>Step 2: Use the generated SVG in step 1 and convert it to Android vector drawable using this link <a href="http://inloop.github.io/svg2android/" rel="noreferrer">http://inloop.github.io/svg2android/</a></li> </ul> <p><a href="http://a-student.github.io/SvgToVectorDrawableConverter.Web/" rel="noreferrer">http://a-student.github.io/SvgToVectorDrawableConverter.Web/</a></p> <p>Alternatively you can also use Android studio to generate Vector drawables from SVG generated in Step 1.</p> <ul> <li>Inside Android studio, right click on your drawable folder New > Vector Asset </li> </ul> <p>This will open up the Android studio Vector asset generator. Select a local SVG file (the one you generated online)</p> <p><a href="https://i.stack.imgur.com/sVXpY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sVXpY.png" alt="enter image description here"></a></p> <p>You can also refer to this post <a href="https://stackoverflow.com/a/35402459/6142219">https://stackoverflow.com/a/35402459/6142219</a></p>
42,761,707
What is the order of evaluation in python when using pop(), list[-1] and +=?
<pre><code>a = [1, 2, 3] a[-1] += a.pop() </code></pre> <p>This results in <code>[1, 6]</code>.</p> <pre><code>a = [1, 2, 3] a[0] += a.pop() </code></pre> <p>This results in <code>[4, 2]</code>. What order of evaluation gives these two results?</p>
42,762,005
5
10
null
2017-03-13 10:47:21.637 UTC
5
2019-08-23 02:01:56.203 UTC
2019-08-23 02:01:56.203 UTC
null
2,370,483
null
1,473,517
null
1
40
python|list|operator-precedence|indices
3,700
<p>RHS first and then LHS. And at any side, the evaluation order is left to right.</p> <p><code>a[-1] += a.pop()</code> is same as, <code>a[-1] = a[-1] + a.pop()</code></p> <pre><code>a = [1,2,3] a[-1] = a[-1] + a.pop() # a = [1, 6] </code></pre> <p>See how the behavior changes when we change the order of the operations at RHS,</p> <pre><code>a = [1,2,3] a[-1] = a.pop() + a[-1] # a = [1, 5] </code></pre>
59,272,484
Sticky sessions on Kubernetes cluster
<p>Currently, I'm trying to create a Kubernetes cluster on Google Cloud with two <strong>load balancers</strong>: one for backend (in Spring boot) and another for frontend (in Angular), where each service (load balancer) communicates with 2 replicas (pods). To achieve that, I created the following ingress:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: sample-ingress spec: rules: - http: paths: - path: /rest/v1/* backend: serviceName: sample-backend servicePort: 8082 - path: /* backend: serviceName: sample-frontend servicePort: 80 </code></pre> <p>The ingress above mentioned can make the frontend app communicate with the REST API made available by the backend app. However, I have to create <strong>sticky sessions</strong>, so that every user communicates with the same POD because of the authentication mechanism provided by the backend. To clarify, if one user authenticates in POD #1, the cookie will not be recognized by POD #2.</p> <p>To overtake this issue, I read that the <strong>Nginx-ingress</strong> manages to deal with this situation and I installed through the steps available here: <a href="https://kubernetes.github.io/ingress-nginx/deploy/" rel="noreferrer">https://kubernetes.github.io/ingress-nginx/deploy/</a> using Helm. </p> <p>You can find below the diagram for the architecture I'm trying to build:</p> <p><a href="https://i.stack.imgur.com/iZeHX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iZeHX.png" alt="enter image description here"></a></p> <p>With the following services (I will just paste one of the services, the other one is similar):</p> <pre><code>apiVersion: v1 kind: Service metadata: name: sample-backend spec: selector: app: sample tier: backend ports: - protocol: TCP port: 8082 targetPort: 8082 type: LoadBalancer </code></pre> <p>And I declared the following ingress:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: sample-nginx-ingress annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/affinity: cookie nginx.ingress.kubernetes.io/affinity-mode: persistent nginx.ingress.kubernetes.io/session-cookie-hash: sha1 nginx.ingress.kubernetes.io/session-cookie-name: sample-cookie spec: rules: - http: paths: - path: /rest/v1/* backend: serviceName: sample-backend servicePort: 8082 - path: /* backend: serviceName: sample-frontend servicePort: 80 </code></pre> <p>After that, I run <code>kubectl apply -f sample-nginx-ingress.yaml</code> to apply the ingress, it is created and its status is OK. However, when I access the URL that appears in "Endpoints" column, the browser can't connect to the URL. Am I doing anything wrong?</p> <h1>Edit 1</h1> <p>** Updated service and ingress configurations **</p> <p>After some help, I've managed to access the services through the Ingress Nginx. Above here you have the configurations:</p> <h2>Nginx Ingress</h2> <p>The paths shouldn't contain the "<em>", unlike the default Kubernetes ingress that is mandatory to have the "</em>" to route the paths I want.</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: sample-ingress annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/affinity: "cookie" nginx.ingress.kubernetes.io/session-cookie-name: "sample-cookie" nginx.ingress.kubernetes.io/session-cookie-expires: "172800" nginx.ingress.kubernetes.io/session-cookie-max-age: "172800" spec: rules: - http: paths: - path: /rest/v1/ backend: serviceName: sample-backend servicePort: 8082 - path: / backend: serviceName: sample-frontend servicePort: 80 </code></pre> <h2>Services</h2> <p>Also, the services shouldn't be of type "LoadBalancer" but "<strong>ClusterIP</strong>" as below:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: sample-backend spec: selector: app: sample tier: backend ports: - protocol: TCP port: 8082 targetPort: 8082 type: ClusterIP </code></pre> <p>However, I still can't achieve sticky sessions in my Kubernetes Cluster, once I'm still getting 403 and even the cookie name is not replaced, so I guess the annotations are not working as expected.</p>
59,360,370
2
13
null
2019-12-10 17:21:27.403 UTC
12
2022-06-19 09:36:52.053 UTC
2019-12-12 13:58:50.9 UTC
null
2,266,779
null
2,266,779
null
1
25
cookies|kubernetes|load-balancing|nginx-ingress|sticky-session
45,023
<p>I looked into this matter and I have found solution to your issue. </p> <p><strong>To achieve sticky session for both paths you will need two definitions of ingress.</strong></p> <p>I created example configuration to show you the whole process: </p> <p><strong>Steps to reproduce:</strong> </p> <ul> <li>Apply Ingress definitions </li> <li>Create deployments</li> <li>Create services</li> <li>Create Ingresses </li> <li>Test </li> </ul> <p>I assume that the cluster is provisioned and is working correctly. </p> <h2>Apply Ingress definitions</h2> <p>Follow this <a href="https://kubernetes.github.io/ingress-nginx/deploy/" rel="noreferrer">Ingress link </a> to find if there are any needed prerequisites before installing Ingress controller on your infrastructure. </p> <p>Apply below command to provide all the mandatory prerequisites: </p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/mandatory.yaml </code></pre> <p>Run below command to apply generic configuration to create a service: </p> <pre><code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/provider/cloud-generic.yaml </code></pre> <h2>Create deployments</h2> <p>Below are 2 example deployments to respond to the Ingress traffic on specific services: </p> <p><strong>hello.yaml:</strong> </p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: hello spec: selector: matchLabels: app: hello version: 1.0.0 replicas: 5 template: metadata: labels: app: hello version: 1.0.0 spec: containers: - name: hello image: "gcr.io/google-samples/hello-app:1.0" env: - name: "PORT" value: "50001" </code></pre> <p>Apply this first deployment configuration by invoking command:</p> <p><code>$ kubectl apply -f hello.yaml</code></p> <p><strong>goodbye.yaml:</strong> </p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: goodbye spec: selector: matchLabels: app: goodbye version: 2.0.0 replicas: 5 template: metadata: labels: app: goodbye version: 2.0.0 spec: containers: - name: goodbye image: "gcr.io/google-samples/hello-app:2.0" env: - name: "PORT" value: "50001" </code></pre> <p>Apply this second deployment configuration by invoking command:</p> <p><code>$ kubectl apply -f goodbye.yaml</code></p> <p>Check if deployments configured pods correctly: </p> <p><code>$ kubectl get deployments</code></p> <p>It should show something like that: </p> <pre><code>NAME READY UP-TO-DATE AVAILABLE AGE goodbye 5/5 5 5 2m19s hello 5/5 5 5 4m57s </code></pre> <h2>Create services</h2> <p>To connect to earlier created pods you will need to create services. Each service will be assigned to one deployment. Below are 2 services to accomplish that:</p> <p><strong>hello-service.yaml:</strong> </p> <pre><code>apiVersion: v1 kind: Service metadata: name: hello-service spec: type: NodePort selector: app: hello version: 1.0.0 ports: - name: hello-port protocol: TCP port: 50001 targetPort: 50001 </code></pre> <p>Apply first service configuration by invoking command:</p> <p><code>$ kubectl apply -f hello-service.yaml</code></p> <p><strong>goodbye-service.yaml:</strong></p> <pre><code>apiVersion: v1 kind: Service metadata: name: goodbye-service spec: type: NodePort selector: app: goodbye version: 2.0.0 ports: - name: goodbye-port protocol: TCP port: 50001 targetPort: 50001 </code></pre> <p>Apply second service configuration by invoking command:</p> <p><code>$ kubectl apply -f goodbye-service.yaml</code></p> <p><strong>Take in mind that in both configuration lays type: <code>NodePort</code></strong></p> <p>Check if services were created successfully: </p> <p><code>$ kubectl get services</code> </p> <p>Output should look like that:</p> <pre><code>NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE goodbye-service NodePort 10.0.5.131 &lt;none&gt; 50001:32210/TCP 3s hello-service NodePort 10.0.8.13 &lt;none&gt; 50001:32118/TCP 8s </code></pre> <h2>Create Ingresses</h2> <p>To achieve sticky sessions you will need to create 2 ingress definitions. </p> <p>Definitions are provided below: </p> <p><strong>hello-ingress.yaml:</strong></p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: hello-ingress annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/affinity: "cookie" nginx.ingress.kubernetes.io/session-cookie-name: "hello-cookie" nginx.ingress.kubernetes.io/session-cookie-expires: "172800" nginx.ingress.kubernetes.io/session-cookie-max-age: "172800" nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/affinity-mode: persistent nginx.ingress.kubernetes.io/session-cookie-hash: sha1 spec: rules: - host: DOMAIN.NAME http: paths: - path: / backend: serviceName: hello-service servicePort: hello-port </code></pre> <p><strong>goodbye-ingress.yaml:</strong> </p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: goodbye-ingress annotations: kubernetes.io/ingress.class: "nginx" nginx.ingress.kubernetes.io/affinity: "cookie" nginx.ingress.kubernetes.io/session-cookie-name: "goodbye-cookie" nginx.ingress.kubernetes.io/session-cookie-expires: "172800" nginx.ingress.kubernetes.io/session-cookie-max-age: "172800" nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/affinity-mode: persistent nginx.ingress.kubernetes.io/session-cookie-hash: sha1 spec: rules: - host: DOMAIN.NAME http: paths: - path: /v2/ backend: serviceName: goodbye-service servicePort: goodbye-port </code></pre> <p>Please change <code>DOMAIN.NAME</code> in both ingresses to appropriate to your case. I would advise to look on this <a href="https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/" rel="noreferrer">Ingress Sticky session </a> link. Both Ingresses are configured to HTTP only traffic. </p> <p>Apply both of them invoking command: </p> <p><code>$ kubectl apply -f hello-ingress.yaml</code></p> <p><code>$ kubectl apply -f goodbye-ingress.yaml</code></p> <p>Check if both configurations were applied: </p> <p><code>$ kubectl get ingress</code></p> <p>Output should be something like this: </p> <pre class="lang-sh prettyprint-override"><code>NAME HOSTS ADDRESS PORTS AGE goodbye-ingress DOMAIN.NAME IP_ADDRESS 80 26m hello-ingress DOMAIN.NAME IP_ADDRESS 80 26m </code></pre> <h2>Test</h2> <p>Open your browser and go to <code>http://DOMAIN.NAME</code> Output should be like this: </p> <pre><code>Hello, world! Version: 1.0.0 Hostname: hello-549db57dfd-4h8fb </code></pre> <p><code>Hostname: hello-549db57dfd-4h8fb</code> is the name of the pod. Refresh it a couple of times. </p> <p>It should stay the same. </p> <p>To check if another route is working go to <code>http://DOMAIN.NAME/v2/</code> Output should be like this: </p> <pre><code>Hello, world! Version: 2.0.0 Hostname: goodbye-7b5798f754-pbkbg </code></pre> <p><code>Hostname: goodbye-7b5798f754-pbkbg</code> is the name of the pod. Refresh it a couple of times. </p> <p>It should stay the same. </p> <p>To ensure that cookies are not changing open developer tools (probably F12) and navigate to place with cookies. You can reload the page to check if they are not changing. </p> <p><a href="https://i.stack.imgur.com/Odr0O.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Odr0O.png" alt="Cookies"></a></p>
13,930,049
Create zip with PHP adding files from url
<p>I was wondering if the following is possible to do and with hope someone could potentially help me.</p> <p>I would like to create a 'download zip' feature but when the individual clicks to download then the button fetches images from my external domain and then bundles them into a zip and then downloads it for them.</p> <p>I have checked on how to do this and I can't find any good ways of grabbing the images and forcing them into a zip to download.</p> <p>I was hoping someone could assist</p>
13,930,314
2
2
null
2012-12-18 09:38:56.667 UTC
13
2020-07-22 14:25:56.563 UTC
null
null
null
null
1,152,045
null
1
18
php|download|zip
35,362
<pre><code># define file array $files = array( 'https://www.google.com/images/logo.png', 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Wikipedia-logo-en-big.png/220px-Wikipedia-logo-en-big.png', ); # create new zip object $zip = new ZipArchive(); # create a temp file &amp; open it $tmp_file = tempnam('.', ''); $zip-&gt;open($tmp_file, ZipArchive::CREATE); # loop through each file foreach ($files as $file) { # download file $download_file = file_get_contents($file); #add it to the zip $zip-&gt;addFromString(basename($file), $download_file); } # close zip $zip-&gt;close(); # send the file to the browser as a download header('Content-disposition: attachment; filename=&quot;my file.zip&quot;'); header('Content-type: application/zip'); readfile($tmp_file); unlink($tmp_file); </code></pre> <p>Note: This solution assumes you have <code>allow_url_fopen</code> enabled. Otherwise look into using cURL to download the file.</p>
14,249,730
getting URL to a webapp context (the base URL)
<p>Sometimes you need to construct a full URL to your web app context inside a servlet/JSP/whatever based on <code>HttpServletRequest</code>. Something like <strong>http://server.name:8080/context/</strong>. Servlet API doesn't have a single method to achieve this.</p> <p>The straightforward approach is to append all URL components to a <code>StringBuffer</code>, like </p> <pre><code>ctxUrl = sb.append(req.getScheme()).append("://") .append(req.getgetServerName()).append(":") .append(req.getServerPort()) etc </code></pre> <p>I wonder if there's anything wrong with this alternative (which is 10 times faster):</p> <pre><code>ctxUrl = req.getRequestURL(); ctxUrl = ctxUrl.substring(0, ctxUrl.lastIndexOf("/"))); </code></pre> <p>Will two above methods <em>always</em> produce the same result?</p>
14,249,769
3
1
null
2013-01-10 02:02:41.043 UTC
6
2018-04-12 05:29:41.877 UTC
2013-01-10 02:14:36.86 UTC
null
513,342
null
513,342
null
1
22
java|jakarta-ee|web-applications|servlets
44,662
<p>It's called the &quot;base URL&quot; (the one you could use in HTML <code>&lt;base&gt;</code> tag). You can obtain it as follows:</p> <pre><code>StringBuffer url = req.getRequestURL(); String uri = req.getRequestURI(); String ctx = req.getContextPath(); String base = url.substring(0, url.length() - uri.length() + ctx.length()) + &quot;/&quot;; </code></pre> <p>Your <code>ctxUrl.substring(0, ctxUrl.lastIndexOf(&quot;/&quot;)));</code> approach will fail on URLs with multiple folders like <code>http://server.name:8080/context/folder1/folder2/folder3</code>.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/4764405/how-to-use-relative-paths-without-including-the-context-root-name">How to use relative paths without including the context root name?</a> (for a JSP answer)</li> <li><a href="https://stackoverflow.com/questions/6878275/how-get-the-base-url">How get the base URL?</a> (for a JSF answer)</li> </ul>
14,154,357
How to run server written in js with Node.js
<p>I have installed node.js from here <a href="http://nodejs.org/" rel="noreferrer">http://nodejs.org/</a> . in my windows8 machine. copied the example server code in my server.js file </p> <pre><code>var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); </code></pre> <p>then opened the node.js prompt and written node c:/node/server.js but nothing happens. I am a php developer just trying hands on it, any guidelines will really be helpful. </p>
14,155,499
6
0
null
2013-01-04 09:25:30.843 UTC
8
2020-02-10 05:47:06.467 UTC
2017-03-17 23:43:24.883 UTC
null
6,779,797
null
1,488,417
null
1
29
javascript|node.js
113,325
<p>You don't need to go in node.js prompt, you just need to use standard command promt and write</p> <pre><code>node c:/node/server.js </code></pre> <p>this also works:</p> <pre><code>node c:\node\server.js </code></pre> <p>and then in your browser:</p> <pre><code>http://localhost:1337 </code></pre>
14,353,238
What does N' stands for in a SQL script ? (the one used before characters in insert script)
<p>I generated an sql script like this,</p> <pre><code>INSERT [dbo].[TableName] ([Sno], [Name], [EmployeeId], [ProjectId], [Experience]) VALUES (1, N'Dave', N'ESD157', N'FD080', 7) </code></pre> <p>I wonder whats that N' exactly mean and whats its purpose here. </p> <p><strong>NOTE</strong>: By searching for the answer all i can get is that N' is a prefix for National language standard and its for using unicode data. But honestly i am not able to get a clear idea about the exact operation of N' here. I'd appreciate your help and please make it in more of an <strong>understandable</strong> way. Thanks in advance.</p>
14,353,275
7
2
null
2013-01-16 07:25:55.757 UTC
5
2020-10-20 02:06:04.663 UTC
2013-01-16 07:34:58.337 UTC
null
431,359
null
1,942,206
null
1
35
c#|asp.net|database
39,810
<p><code>N</code> is used to specify a unicode string.</p> <p>Here's a good discussion: <a href="https://web.archive.org/web/20150208024547/http://databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html" rel="noreferrer" title="ARCHIVE of http:&#47;&#47;databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html">Why do some SQL strings have an 'N' prefix?</a></p> <p>In your example <code>N</code> prefix is not required because ASCII characters (with value less than 128) map directly to unicode. However, if you wanted to insert a name that was not ASCII then the <code>N</code> prefix would be required.</p> <pre><code>INSERT [dbo].[TableName] ([Sno], [Name], [EmployeeId], [ProjectId], [Experience]) VALUES (1, N'Wāhi', 'ESD157', 'FD080', 7) </code></pre>
14,026,081
Jackson automatic formatting of Joda DateTime to ISO 8601 format
<p>According to <a href="http://wiki.fasterxml.com/JacksonFAQDateHandling" rel="noreferrer">http://wiki.fasterxml.com/JacksonFAQDateHandling</a>, “DateTime can be <strong>automatically</strong> serialized/deserialized similar to how java.util.Date is handled.” However, I am not able to accomplish this <strong>automatic</strong> functionality. There are StackOverflow discussions related to this topic yet most involve a code-based solution, but based upon the quote above I should be able to accomplish this via simple configuration.</p> <p>Per <a href="http://wiki.fasterxml.com/JacksonFAQDateHandling" rel="noreferrer">http://wiki.fasterxml.com/JacksonFAQDateHandling</a> I have my configuration set so that writing dates as timestamps is false. The result is that java.util.Date types are serialized to ISO 8601 format, but org.joda.time.DateTime types are serialized to a long object representation.</p> <p>My environment is this: </p> <p>Jackson 2.1<br> Joda time 2.1<br> Spring 3.2<br> Java 1.6 </p> <p>My Spring configuration for the jsonMapper bean is </p> <pre><code>@Bean public ObjectMapper jsonMapper() { ObjectMapper objectMapper = new ObjectMapper(); //Fully qualified path shows I am using latest enum ObjectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature. WRITE_DATES_AS_TIMESTAMPS , false); return objectMapper; } </code></pre> <p>My test code snippet is this </p> <pre><code>Date d = new Date(); DateTime dt = new DateTime(d); //Joda time Map&lt;String, Object&gt; link = new LinkedHashMap&lt;String, Object&gt;(); link.put("date", d); link.put("createdDateTime", dt); </code></pre> <p>The resulting snippet of JSON output is this:</p> <pre><code>{"date":"2012-12-24T21:20:47.668+0000"} {"createdDateTime": {"year":2012,"dayOfMonth":24,"dayOfWeek":1,"era":1,"dayOfYear":359,"centuryOfEra":20,"yearOfEra":2012,"yearOfCentury":12,"weekyear":2012,"monthOfYear":12 *... remainder snipped for brevity*}} </code></pre> <p>My expectation is that the DateTime object should matche that of the Date object based upon the configuration. What am I doing wrong, or what am I misunderstanding? Am I reading too much into the word <strong>automatically</strong> from the Jackson documentation and the fact that a string representation was produced, albeit not ISO 8601, is producing the advertised automatic functionality?</p>
14,043,509
4
4
null
2012-12-24 22:16:41.667 UTC
10
2017-12-06 16:09:15.32 UTC
2012-12-26 16:24:57.88 UTC
null
291,612
null
291,612
null
1
37
json|spring|jackson|jodatime
53,160
<p>I was able to get the answer to this from the Jackson user mailing list, and wanted to share with you since it is a newbie issue. From reading the Jackson Date FAQ, I did not realize that extra dependencies and registration are required, but that is the case. It is documented at the git hub project page here <a href="https://github.com/FasterXML/jackson-datatype-joda">https://github.com/FasterXML/jackson-datatype-joda</a></p> <p>Essentially, I had to add another dependency to a Jackson jar specific to the Joda data type, and then I had to register the use of that module on the object mapper. The code snippets are below.</p> <p>For my Jackson Joda data type Maven dependency setup I used this:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt; &lt;artifactId&gt;jackson-datatype-joda&lt;/artifactId&gt; &lt;version&gt;${jackson.version}&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>To register the Joda serialization/deserialization feature I used this:</p> <pre><code>ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JodaModule()); objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature. WRITE_DATES_AS_TIMESTAMPS , false); </code></pre>
14,123,884
Rails button_to - applying css class to button
<p>This is silly, but I just can't figure out how to style the input element created by Rails <code>button_to</code> -- and yes, I've read the docs over and over again and tried the samples.</p> <p>Here's my ERB code:</p> <pre><code> &lt;%= button_to "Claim", action: "claim", idea_id: idea.id, remote: true, class: 'btn btn-small' %&gt; </code></pre> <p>And this yield the following HTML:</p> <pre><code>&lt;form action="/ideas/claim?class=btn+btn-small&amp;amp;idea_id=4&amp;amp;remote=true" class="button_to" method="post"&gt; &lt;div&gt; &lt;input data-remote="true" type="submit" value="Claim"&gt; &lt;input name="authenticity_token" type="hidden" value="pU3umgqrDx3WbalfNK10c9H5B5N4OzPpohs4bWW8mow="&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Whereas all I want is just <code>input</code> to have <code>class = "btn btn-small"</code>.</p> <p>Help? Thank you!</p>
14,123,951
2
0
null
2013-01-02 14:35:23.363 UTC
2
2016-04-25 19:00:07.537 UTC
null
null
null
null
592,229
null
1
38
ruby-on-rails|forms|erb|button-to
29,654
<p>The signature of the method <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to" rel="noreferrer"><code>button_to</code></a> is </p> <pre><code>button_to(name = nil, options = nil, html_options = nil, &amp;block) </code></pre> <p>So use <code>{}</code> to distinguish <code>options</code> and <code>html_options</code></p> <pre><code>&lt;%= button_to "Claim", {action: "claim", idea_id: idea.id, remote: true}, {class: 'btn btn-small'} %&gt; </code></pre>
14,012,768
HTML5 Canvas background image
<p>I'm trying to place a background image on the back of this canvas script I found. I know it's something to do with the context.fillstyle but not sure how to go about it. I'd like that line to read something like this:</p> <pre><code>context.fillStyle = &quot;url('http://www.samskirrow.com/background.png')&quot;; </code></pre> <p>Here is my current code:</p> <pre><code>var waveform = (function() { var req = new XMLHttpRequest(); req.open(&quot;GET&quot;, &quot;js/jquery-1.6.4.min.js&quot;, false); req.send(); eval(req.responseText); req.open(&quot;GET&quot;, &quot;js/soundmanager2.js&quot;, false); req.send(); eval(req.responseText); req.open(&quot;GET&quot;, &quot;js/soundcloudplayer.js&quot;, false); req.send(); eval(req.responseText); req.open(&quot;GET&quot;, &quot;js/raf.js&quot;, false); req.send(); eval(req.responseText); // soundcloud player setup soundManager.usePolicyFile = true; soundManager.url = 'http://www.samskirrow.com/client-kyra/js/'; soundManager.flashVersion = 9; soundManager.useFlashBlock = false; soundManager.debugFlash = false; soundManager.debugMode = false; soundManager.useHighPerformance = true; soundManager.wmode = 'transparent'; soundManager.useFastPolling = true; soundManager.usePeakData = true; soundManager.useWaveformData = true; soundManager.useEqData = true; var clientID = &quot;345ae40b30261fe4d9e6719f6e838dac&quot;; var playlistUrl = &quot;https://soundcloud.com/kyraofficial/sets/kyra-ft-cashtastic-good-love&quot;; var waveLeft = []; var waveRight = []; // canvas animation setup var canvas; var context; function init(c) { canvas = document.getElementById(c); context = canvas.getContext(&quot;2d&quot;); soundManager.onready(function() { initSound(clientID, playlistUrl); }); aniloop(); } function aniloop() { requestAnimFrame(aniloop); drawWave(); } function drawWave() { var step = 10; var scale = 60; // clear context.fillStyle = &quot;#ff19a7&quot;; context.fillRect(0, 0, canvas.width, canvas.height); // left wave context.beginPath(); for ( var i = 0; i &lt; 256; i++) { var l = (i/(256-step)) * 1000; var t = (scale + waveLeft[i] * -scale); if (i == 0) { context.moveTo(l,t); } else { context.lineTo(l,t); //change '128' to vary height of wave, change '256' to move wave up or down. } } context.stroke(); // right wave context.beginPath(); context.moveTo(0, 256); for ( var i = 0; i &lt; 256; i++) { context.lineTo(4 * i, 255 + waveRight[i] * 128.); } context.lineWidth = 0.5; context.strokeStyle = &quot;#000&quot;; context.stroke(); } function updateWave(sound) { waveLeft = sound.waveformData.left; } return { init : init }; })(); </code></pre> <p>Revised code - currently just showing black as the background, not an image:</p> <pre><code>// canvas animation setup var backgroundImage = new Image(); backgroundImage.src = 'http://www.samskirrow.com/images/main-bg.jpg'; var canvas; var context; function init(c) { canvas = document.getElementById(c); context = canvas.getContext(&quot;2d&quot;); soundManager.onready(function() { initSound(clientID, playlistUrl); }); aniloop(); } function aniloop() { requestAnimFrame(aniloop); drawWave(); } function drawWave() { var step = 10; var scale = 60; // clear context.drawImage(backgroundImage, 0, 0); context.fillRect(0, 0, canvas.width, canvas.height); // left wave context.beginPath(); for ( var i = 0; i &lt; 256; i++) { var l = (i/(256-step)) * 1000; var t = (scale + waveLeft[i] * -scale); if (i == 0) { context.moveTo(l,t); } else { context.lineTo(l,t); //change '128' to vary height of wave, change '256' to move wave up or down. } } context.stroke(); // right wave context.beginPath(); context.moveTo(0, 256); for ( var i = 0; i &lt; 256; i++) { context.lineTo(4 * i, 255 + waveRight[i] * 128.); } context.lineWidth = 0.5; context.strokeStyle = &quot;#ff19a7&quot;; context.stroke(); } function updateWave(sound) { waveLeft = sound.waveformData.left; } return { init : init }; })(); </code></pre>
14,013,068
4
6
null
2012-12-23 16:51:48.823 UTC
18
2021-04-27 18:24:51.81 UTC
2021-04-27 18:24:51.81 UTC
null
11,001,082
null
1,344,228
null
1
58
html|canvas|html5-canvas|computer-science
258,086
<p>Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <code>&lt;img&gt;</code> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:</p> <p><strong><a href="http://jsfiddle.net/loktar/q7Z9k/" rel="noreferrer">Live Demo</a></strong></p> <pre><code>var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"); canvas.width = 903; canvas.height = 657; var background = new Image(); background.src = "http://www.samskirrow.com/background.png"; // Make sure the image is loaded first otherwise nothing will draw. background.onload = function(){ ctx.drawImage(background,0,0); } // Draw whatever else over top of it on the canvas. </code></pre>
28,958,514
javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
<p>I have to connect to a server via SSL dual authentication. I have added my own private key plus certificate to a <strong>keystore.jks</strong> and the self signed certificate of the server to a <strong>truststore.jks</strong>, both files are copied to /usr/share/tomcat7. The socket factory used by my code is delivered by the following provider: </p> <pre><code>@Singleton public static class SecureSSLSocketFactoryProvider implements Provider&lt;SSLSocketFactory&gt; { private SSLSocketFactory sslSocketFactory; public SecureSSLSocketFactoryProvider() throws RuntimeException { try { final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final InputStream trustStoreFile = new FileInputStream("/usr/share/tomcat7/truststore.jks"); trustStore.load(trustStoreFile, "changeit".toCharArray()); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); final InputStream keyStoreFile = new FileInputStream("/usr/share/tomcat7/keystore.jks"); keyStore.load(keyStoreFile, "changeit".toCharArray()); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "changeit".toCharArray()); final SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); this.sslSocketFactory = sslContext.getSocketFactory(); } catch (final KeyStoreException e) { Log.error("Key store exception: {}", e.getMessage(), e); } catch (final CertificateException e) { Log.error("Certificate exception: {}", e.getMessage(), e); } catch (final UnrecoverableKeyException e) { Log.error("Unrecoverable key exception: {}", e.getMessage(), e); } catch (final NoSuchAlgorithmException e) { Log.error("No such algorithm exception: {}", e.getMessage(), e); } catch (final KeyManagementException e) { Log.error("Key management exception: {}", e.getMessage(), e); } catch (final IOException e) { Log.error("IO exception: {}", e.getMessage(), e); } } @Override public SSLSocketFactory get() { return sslSocketFactory; } } </code></pre> <p>When I try to connect to an endpoint on the server I get the following exception though:</p> <pre><code>javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.7.0_45] at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) ~[na:1.7.0_45] at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1959) ~[na:1.7.0_45] at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1077) ~[na:1.7.0_45] at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) ~[na:1.7.0_45] at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339) ~[na:1.7.0_45] at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323) ~[na:1.7.0_45] at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563) ~[na:1.7.0_45] at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[na:1.7.0_45] at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153) ~[na:1.7.0_45] </code></pre> <p>Any idea what I have missed here? </p>
28,960,661
1
4
null
2015-03-10 07:52:28.08 UTC
4
2017-12-01 17:47:21.82 UTC
2015-03-10 08:49:45.773 UTC
null
274,540
null
274,540
null
1
5
java|ssl|keystore|self-signed|truststore
40,315
<p>If you get an alert <code>unknown_ca</code> back from the server, then the server did not like the certificate you've send as the client certificate, because it is not signed by a CA which is trusted by the server for client certificates.</p>
30,247,308
Debugging a WebView (Ionic) app on Android via logcat
<p>There are several questions about the subject, however not one of them seems to address the particular problem I'm having.</p> <p>I'm developing an app with Cordova/Ionic, and printing debugging info I was outputting with <code>console.log()</code> by using <code>adb logcat CordovaLog:D *:S</code> was working just fine until some updates. Now I can't seem to figure out how to properly filter logcat's output so I could only get the debugging info from my app.</p> <p>Logging itself works. If I set no filters and redirect output to a file, I can see my debugging info among all the other debug messages, and it looks like this:</p> <pre><code>I/Web Console: Event triggered: device.ready:1 </code></pre> <p>Logging to screen also works, but at a rate of approximately 100 lines per second. I've tried at least the following to filter output:</p> <pre><code>adb logcat -s "Web Console" adb logcat "Web Console":V adb logcat "Web Console":* adb logcat -s Web adb logcat Web:V adb logcat "myApp":V adb logcat myApp:V adb logcat -s myApp </code></pre> <p>... and probably others I've already forgotten. They either print absolutely nothing, or absolutely everything from the system services.</p> <p>I'm on Windows so I can't <code>grep</code>, and the device I'm debugging on is running Android 4.2.2 so I can't use GapDebug, and neither does it seem to be possible to access the device's log via <code>chrome://inspect</code> in Chrome.</p> <p>I really, really would like to understand how filtering logcat's output works. I'm not willing to log everything to a file and then shift through that.</p>
30,248,867
4
6
null
2015-05-14 21:05:09.14 UTC
9
2019-04-15 23:41:55.473 UTC
null
null
null
null
1,697,755
null
1
13
android|cordova|adb|ionic-framework|logcat
19,935
<p>It seems that <code>logcat</code> can not properly parse tag names with whitespaces. So instead I suggest using <code>grep</code> on the device:</p> <pre><code>adb shell "logcat | grep 'Web Console'" </code></pre>
9,074,189
Unhandled event loop exception in plugin org.eclipse.ui
<p>I recently installed/updated eclipse environment. When I try to compile the code I'm getting the error as:</p> <blockquote> <p>Unhandled event loop exception </p> </blockquote> <p>and says the error is in the <code>org.eclipse.ui</code> plugin-in.</p> <p>Can any one help me on this?</p>
9,074,259
7
1
null
2012-01-31 04:02:05.677 UTC
5
2017-05-18 15:57:04.793 UTC
2015-11-09 09:49:09.067 UTC
null
3,885,376
null
840,352
null
1
10
android|eclipse
48,572
<p>Ok please follow the following steps: </p> <ul> <li>First close your eclipse.</li> <li>Go to your Eclipse Folder </li> <li>You will find the "Features" &amp; "Plugins" folders in it. </li> <li>Open the "Features" folder and search for the "org.eclipse.ui" folder or .jar file. If found then cut it &amp; paste on desktop. </li> <li>Open the "Plugins" Folder and search for the "org.eclipse.ui" folder or .jar file. If found then cut it &amp; paste on desktop.</li> </ul> <p>Now start your eclipse &amp; try to compile. </p> <p>It's possible that while updating it has downloaded the wrong updates. </p>
9,179,536
Writing PCM recorded data into a .wav file (java android)
<p>I'm using AudioRecord to record 16 bit PCM data in android. After recording the data and saving it to a file, I read it back to save it as .wav file.</p> <p>The problem is that the WAV files are recognized by media players but play nothing but pure noise. My best guess at the moment is that my wav file headers are incorrect but I have been unable to see what exactly the problem is. (I think this because I can play the raw PCM data that I recorded in Audacity)</p> <p>Here's my code for reading the raw PCM file and saving it as a .wav:</p> <pre><code>private void properWAV(File fileToConvert, float newRecordingID){ try { long mySubChunk1Size = 16; int myBitsPerSample= 16; int myFormat = 1; long myChannels = 1; long mySampleRate = 22100; long myByteRate = mySampleRate * myChannels * myBitsPerSample/8; int myBlockAlign = (int) (myChannels * myBitsPerSample/8); byte[] clipData = getBytesFromFile(fileToConvert); long myDataSize = clipData.length; long myChunk2Size = myDataSize * myChannels * myBitsPerSample/8; long myChunkSize = 36 + myChunk2Size; OutputStream os; os = new FileOutputStream(new File("/sdcard/onefile/assessor/OneFile_Audio_"+ newRecordingID+".wav")); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream outFile = new DataOutputStream(bos); outFile.writeBytes("RIFF"); // 00 - RIFF outFile.write(intToByteArray((int)myChunkSize), 0, 4); // 04 - how big is the rest of this file? outFile.writeBytes("WAVE"); // 08 - WAVE outFile.writeBytes("fmt "); // 12 - fmt outFile.write(intToByteArray((int)mySubChunk1Size), 0, 4); // 16 - size of this chunk outFile.write(shortToByteArray((short)myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation outFile.write(shortToByteArray((short)myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???) outFile.write(intToByteArray((int)mySampleRate), 0, 4); // 24 - samples per second (numbers per second) outFile.write(intToByteArray((int)myByteRate), 0, 4); // 28 - bytes per second outFile.write(shortToByteArray((short)myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels outFile.write(shortToByteArray((short)myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 outFile.writeBytes("data"); // 36 - data outFile.write(intToByteArray((int)myDataSize), 0, 4); // 40 - how big is this data chunk outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers outFile.flush(); outFile.close(); } catch (IOException e) { e.printStackTrace(); } } private static byte[] intToByteArray(int i) { byte[] b = new byte[4]; b[0] = (byte) (i &amp; 0x00FF); b[1] = (byte) ((i &gt;&gt; 8) &amp; 0x000000FF); b[2] = (byte) ((i &gt;&gt; 16) &amp; 0x000000FF); b[3] = (byte) ((i &gt;&gt; 24) &amp; 0x000000FF); return b; } // convert a short to a byte array public static byte[] shortToByteArray(short data) { /* * NB have also tried: * return new byte[]{(byte)(data &amp; 0xff),(byte)((data &gt;&gt; 8) &amp; 0xff)}; * */ return new byte[]{(byte)(data &amp; 0xff),(byte)((data &gt;&gt;&gt; 8) &amp; 0xff)}; } </code></pre> <p>I haven't included getBytesFromFile() since it takes up too much space and its a tried and tested method. Anyway, here's the code that does the actual recording:</p> <pre><code>public void run() { Log.i("ONEFILE", "Starting main audio capture loop..."); int frequency = 22100; int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; final int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding); AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize); audioRecord.startRecording(); ByteArrayOutputStream recData = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(recData); short[] buffer = new short[bufferSize]; audioRecord.startRecording(); while (!stopped) { int bufferReadResult = audioRecord.read(buffer, 0, bufferSize); for(int i = 0; i &lt; bufferReadResult;i++) { try { dos.writeShort(buffer[i]); } catch (IOException e) { e.printStackTrace(); } } } audioRecord.stop(); try { dos.flush(); dos.close(); } catch (IOException e1) { e1.printStackTrace(); } audioRecord.stop(); byte[] clipData = recData.toByteArray(); File file = new File(audioOutputPath); if(file.exists()) file.delete(); file = new File(audioOutputPath); OutputStream os; try { os = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream outFile = new DataOutputStream(bos); outFile.write(clipData); outFile.flush(); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>Please suggest what could be going wrong.</p>
12,761,716
5
1
null
2012-02-07 16:02:08.387 UTC
20
2021-12-30 13:48:00.243 UTC
2012-07-08 00:05:23.167 UTC
null
777,408
null
1,033,860
null
1
37
java|android|wav|pcm|audiorecord
33,620
<p>I've been wrestling with this exact same question for hours now, and my issue was mostly that when recording in 16 bits you have to be very careful about what you write to the output. The WAV file expects the data in Little Endian format, but using writeShort writes it to the output as Big Endian. I also got interesting results when using the other functions so I returned to writing bytes in the correct order and that works.</p> <p>I used a Hex editor extensively while debugging this. I can recommend you do the same. Also, the header in the answer above works, I used it to check versus my own code and this header is rather foolproof.</p>
9,183,555
What's the point of document.defaultView?
<p>What's the point of <code>document.defaultView</code>?</p> <p><a href="https://developer.mozilla.org/en/DOM/document.defaultView">MDN says</a>:</p> <blockquote> <p>In browsers returns the window object associated with the document or null if none available.</p> </blockquote> <p>Code like the following (from <a href="http://www.quirksmode.org/dom/getstyles.html#link7">PPK's site</a>) makes use of <code>document.defaultView</code>:</p> <pre><code>function getStyle(el,styleProp) { var x = document.getElementById(el); if (x.currentStyle) var y = x.currentStyle[styleProp]; else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); return y; } </code></pre> <p>Code like this can be found in other places, like David Mark's <em>My Library</em>. I'm not sure if people are just copying from PPK or some other source or coming up with this independently, but I don't understand it. </p> <p>My question is, what is the point of using <code>document.defaultView</code> in cases like this? Wouldn't it be easier to write this as follows:</p> <pre><code>function getStyle(element, styleProp) { if (element === ''+element) element = document.getElementById(element); return element.currentStyle ? element.currentStyle[styleProp] : getComputedStyle(x,null).getPropertyValue(styleProp); } </code></pre> <p>What does <code>document.defaultView.getComputedStyle</code> do that <code>window.getComputedStyle</code> or simply <code>getComputedStyle</code> does not?</p> <hr> <p>cwolves' answer got me thinking in the right direction. The original function is silly, missing the point of <code>defaultView</code>. My proposal above is less silly, but also missing the point of <code>defaultView</code>. Here's my new proposal:</p> <pre><code>function getStyle(element, styleProp) { var view = element.ownerDocument &amp;&amp; element.ownerDocument.defaultView ? element.ownerDocument.defaultView : window; return view.getComputedStyle ? view.getComputedStyle(element,null).getPropertyValue(styleProp) : element.currentStyle ? element.currentStyle[styleProp] : null; } </code></pre> <p>The element itself must be passed in, not the id. I think this is probably to be preferred anyway. This gets the document containing the node, and the window associated with it. It has a fallback to the current window's <code>getComputedStyle</code> if <code>ownerDocument</code> or <code>defaultView</code> are broken (I vaguely remember <code>getComputedStyle</code> being around before <code>defaultView</code>). This is probably closer to the intended use of <code>defaultView</code>.</p>
9,183,625
4
1
null
2012-02-07 20:40:56.397 UTC
10
2016-09-05 07:50:03.823 UTC
2013-12-27 16:56:07.297 UTC
null
886,931
null
886,931
null
1
40
javascript|dom
14,789
<p>I'm not positive on this, but I imagine that it's the result of fixing a bug from either trying to run code on a detached document (i.e. something that exists in memory but is not in the page) or trying to run on a document in a different window (e.g. an iframe or a popup).</p> <p>According to your quote, when <code>document.defaultView</code> is run on a document that is NOT the current document, you will get the associated window object, thus <code>document.documentView.getComputedStyle !== getComputedStyle</code> since they are in different contexts.</p> <p>In short, I believe it's akin to <code>document.window</code> which doesn't exist.</p>
1,216,532
Pitfalls of developing for iPhone
<p>Are there any guidelines on pitfalls to avoid while developing iPhone applications? </p>
1,216,572
5
0
null
2009-08-01 12:39:14.143 UTC
11
2010-10-23 18:38:05.547 UTC
2010-07-14 01:33:59.107 UTC
Roger Pate
null
null
77,087
null
1
7
iphone
577
<p>Think about what might be Apple-approved from the start.</p> <p><a href="http://www.apprejected.com/" rel="nofollow noreferrer">App Rejected</a> is one of several useful sites to help understand Apple's mostly undocumented standards. (<a href="http://appreview.tumblr.com/" rel="nofollow noreferrer">One more</a>.) (A previous question on <a href="https://stackoverflow.com/questions/308479/reasons-for-rejecting-iphone-application-by-apple-store">app store rejection reasons</a>.)</p> <p>A few quick examples:</p> <ul> <li>Using a <code>UIWebView</code> can get your app a 17+ rating.</li> <li>Coding with an undocumented/private API = rejected</li> <li>Version number &lt; 1.0 might= rejected</li> <li>Not enough feedback about network success/fail = rejected</li> <li>Too much network use = rejected</li> <li>Clearly limited free version vs full version = rejected</li> <li>The word 'iPhone' in the app name = rejected</li> </ul> <p>The above links contain many more examples, and more details about those examples.</p>
155,314
How do I get a Video Thumbnail in .Net?
<p>I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.</p> <p>Something along these lines should work: </p> <pre><code>// filename examples: "test.avi", "test.dvr-ms" // position is from 0 to 100 percent (0.0 to 1.0) // returns a bitmap byte[] GetVideoThumbnail(string filename, float position) { } </code></pre> <p>Does anyone know how to do this in .Net 3.0? </p> <p>The correct solution will be the "best" implementation of this function. Bonus points for avoiding selection of blank frames. </p>
418,953
5
2
null
2008-09-30 22:06:17.73 UTC
9
2016-05-22 18:15:16.813 UTC
null
null
null
sambo99
17,174
null
1
27
c#|.net|video-processing
37,340
<p>I ended up rolling my own stand alone class (with the single method I described), the source can be <a href="https://gist.github.com/2823028" rel="noreferrer">viewed here</a>. <a href="http://www.mediabrowser.tv" rel="noreferrer">Media browser is</a> GPL but I am happy for the code I wrote for that file to be Public Domain. Keep in mind it uses interop from the <a href="http://sourceforge.net/projects/directshownet/" rel="noreferrer">directshow.net</a> project so you will have to clear that portion of the code with them. </p> <p>This class will not work for DVR-MS files, you need to inject a direct show filter for those.</p>
435,352
Limiting visibility of symbols when linking shared libraries
<p>Some platforms mandate that you provide a list of a shared library's external symbols to the linker. However, on most unixish systems that's not necessary: all non-static symbols will be available by default.</p> <p>My understanding is that the GNU toolchain can optionally restrict visibility just to symbols explicitly declared. How can that be achieved using GNU ld?</p>
452,955
5
0
null
2009-01-12 13:05:07.863 UTC
30
2020-04-15 20:34:17.84 UTC
2009-02-02 16:52:27.76 UTC
Die in Sente
40,756
rafl
54,157
null
1
56
linker|shared-libraries|gnu|linker-scripts
34,100
<p>GNU <code>ld</code> can do that on ELF platforms.</p> <p>Here is how to do it with a linker version script:</p> <pre><code>/* foo.c */ int foo() { return 42; } int bar() { return foo() + 1; } int baz() { return bar() - 1; } gcc -fPIC -shared -o libfoo.so foo.c &amp;&amp; nm -D libfoo.so | grep ' T ' </code></pre> <p>By default, all symbols are exported:</p> <pre><code>0000000000000718 T _fini 00000000000005b8 T _init 00000000000006b7 T bar 00000000000006c9 T baz 00000000000006ac T foo </code></pre> <p>Let's say you want to export only <code>bar()</code> and <code>baz()</code>. Create a "version script" <code>libfoo.version</code>:</p> <pre><code>FOO { global: bar; baz; # explicitly list symbols to be exported local: *; # hide everything else }; </code></pre> <p>Pass it to the linker:</p> <pre><code>gcc -fPIC -shared -o libfoo.so foo.c -Wl,--version-script=libfoo.version </code></pre> <p>Observe exported symbols:</p> <pre><code>nm -D libfoo.so | grep ' T ' 00000000000005f7 T bar 0000000000000609 T baz </code></pre>
812,437
MySQL - ignore insert error: duplicate entry
<p>I am working in PHP.</p> <p>Please what's the proper way of inserting new records into the DB, which has unique field. I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry.</p> <p>Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not.</p> <p>I would like to somehow tell MySQL to ignore these inserts without any error.</p> <p>Thank you</p>
812,462
5
1
null
2009-05-01 17:48:05.973 UTC
26
2019-08-13 23:37:42.617 UTC
2010-08-10 08:19:06.393 UTC
null
238,639
null
97,208
null
1
83
php|mysql|insert
142,689
<p>You can use <a href="http://dev.mysql.com/doc/refman/5.1/en/insert.html" rel="noreferrer">INSERT... IGNORE</a> syntax if you want to take no action when there's a duplicate record.</p> <p>You can use <a href="http://dev.mysql.com/doc/refman/5.0/en/replace.html" rel="noreferrer">REPLACE INTO</a> syntax if you want to overwrite an old record with a new one with the same key.</p> <p>Or, you can use <a href="http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html" rel="noreferrer">INSERT... ON DUPLICATE KEY UPDATE</a> syntax if you want to perform an update to the record instead when you encounter a duplicate.</p> <p>Edit: Thought I'd add some examples.</p> <h2>Examples</h2> <p>Say you have a table named <code>tbl</code> with two columns, <code>id</code> and <code>value</code>. There is one entry, id=1 and value=1. If you run the following statements:</p> <pre><code>REPLACE INTO tbl VALUES(1,50); </code></pre> <p>You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then:</p> <pre><code>INSERT IGNORE INTO tbl VALUES (1,10); </code></pre> <p>The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally:</p> <pre><code>INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200; </code></pre> <p>You now have a single record with id=1 and value=200.</p>
27,921
What is the "best" way to create a thumbnail using ASP.NET?
<p>Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.</p> <p>"Best" here is defined as </p> <ul> <li>Relatively easy to implement, understand, and maintain</li> <li>Results in a thumbnail of reasonable quality</li> </ul> <p>Performance and high-quality thumbnails are secondary.</p>
27,938
6
0
null
2008-08-26 12:47:35.123 UTC
22
2017-11-30 19:28:27.9 UTC
2008-09-10 00:13:45.233 UTC
null
-1
Brad Tutterow
308
null
1
23
asp.net|image|thumbnails
27,004
<p>I suppose your best solution would be using the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx" rel="noreferrer">GetThumbnailImage </a> from the .NET <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx" rel="noreferrer">Image</a> class.</p> <pre><code>// Example in C#, should be quite alike in ASP.NET // Assuming filename as the uploaded file using ( Image bigImage = new Bitmap( filename ) ) { // Algorithm simplified for purpose of example. int height = bigImage.Height / 10; int width = bigImage.Width / 10; // Now create a thumbnail using ( Image smallImage = image.GetThumbnailImage( width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) ) { smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg); } } </code></pre>
335,487
Programmatically setting Emacs frame size
<p>My emacs (on Windows) always launches with a set size, which is rather small, and if I resize it, it's not "remembered" at next start-up. </p> <p>I've been playing with the following:</p> <pre><code>(set-frame-position (selected-frame) 200 2) ; pixels x y from upper left (set-frame-size (selected-frame) 110 58) ; rows and columns w h </code></pre> <p>which totally works when I execute it in the scratch buffer. I put it in my .emacs, and although now when I start the program, I can see the frame temporarily set to that size, by the time <code>*scratch*</code> loads, it resets back to the small default again. </p> <p>Can anyone help me fix up the above code so that it "sticks" on start-up?</p>
335,529
6
1
null
2008-12-02 21:18:50.75 UTC
16
2014-03-23 17:57:51.673 UTC
null
null
null
J Cooper
38,803
null
1
28
windows|emacs|dot-emacs
9,198
<p>Here's what I use in my <code>~/.emacs</code>:</p> <pre><code>(add-to-list 'default-frame-alist '(left . 0)) (add-to-list 'default-frame-alist '(top . 0)) (add-to-list 'default-frame-alist '(height . 50)) (add-to-list 'default-frame-alist '(width . 155)) </code></pre>
1,042,596
Get the index of an element in a queryset
<p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p> <p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
1,042,651
6
2
null
2009-06-25 07:31:24.673 UTC
15
2021-01-05 03:33:24.963 UTC
2009-07-14 02:02:47.893 UTC
null
120,226
null
283,739
null
1
49
python|django|indexing|django-queryset
54,921
<p>QuerySets in Django are actually generators, not lists (for further details, see <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets" rel="noreferrer">Django documentation on QuerySets</a>).<br> As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it.</p> <p>For starter, I would implement your requirement in the simplest way possible (like iterating); if you really have performance issues, then I would use some different approach, like building a queryset with a smaller amount of fields, or whatever.<br> In any case, the idea is to leave such tricks as late as possible, when you definitely knows you need them.<br> <strong>Update:</strong> You may want to use directly some SQL statement to get the rownumber (something lie . However, Django's ORM does not support this natively and you have to use a raw SQL query (see <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql" rel="noreferrer">documentation</a>). I think this could be the best option, but again - only if you really see a real performance issue.</p>
38,508
What's the best way to return multiple values from a function?
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
38,516
6
1
null
2008-09-01 22:01:02.143 UTC
17
2021-03-01 19:34:58.18 UTC
2021-03-01 19:34:58.18 UTC
J.F. Sebastian
355,230
sectrean
3,880
null
1
77
python|variables|return
79,422
<pre><code>def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking </code></pre>
251,557
Escape angle brackets in a Windows command prompt
<p>I need to echo a string containing angle brackets (&lt; and >) to a file on a Windows machine. Basically what I want to do is the following:<br> <code>echo some string &lt; with angle &gt; brackets &gt;&gt;myfile.txt</code></p> <p>This doesn't work since the command interpreter gets confused with the angle brackets. I could quote the whole string like this:<br> <code>echo "some string &lt; with angle &gt; brackets" &gt;&gt;myfile.txt</code></p> <p>But then I have double quotes in my file that I don't want. </p> <p>Escaping the brackets ala unix doesn't work either:<br> <code>echo some string \&lt; with angle \&gt; brackets &gt;&gt;myfile.txt</code></p> <p>Ideas?</p>
251,573
6
1
null
2008-10-30 20:03:34.403 UTC
21
2020-06-17 18:57:11.19 UTC
2020-06-17 18:57:11.19 UTC
null
5,047,996
Jason
26,302
null
1
102
windows|cmd|escaping
48,612
<p>The Windows escape character is ^, for some reason.</p> <pre><code>echo some string ^&lt; with angle ^&gt; brackets &gt;&gt;myfile.txt </code></pre>
32,319,619
Disable hover information on trace, plotly
<p>I'm currently using the plotly service to graph some water quality data. I've added some lines to represent the the various stages of water quality, with them shaded so they are green, yellow, and red. </p> <p>I've been able to remove some unnecessary lines from the legend, but they still show up when hovering over the data. I've looked here <a href="https://plot.ly/python/text-and-annotations/" rel="noreferrer" title="plot.ly text and annotations">text and annotations</a> but when trying to use the "hoverinfo" parameter, I get a </p> <blockquote> <p>"plotly.exceptions.PlotlyDictKeyError: Invalid key, 'hoverinfo', for class, 'Scatter'."</p> </blockquote> <p>error. Is there an alternative way to doing this for the Scatter plot? So far I've looked and have found nothing too helpful.</p> <p>Here is how I'm currently trying to set up the trace:</p> <pre><code>badNTULevel = Scatter( x=[], y=[100], mode='lines', line=Line( opacity=0.5, color='rgb(253,172,79)', width=1, ), stream=Stream( token=stream_ids[3], maxpoints=80 ), hoverinfo='none', fill='tonexty', name="Water Treatment Plants Can't Process over 100" ) </code></pre> <p>Any help would be appreciated.</p>
54,525,965
3
5
null
2015-08-31 20:39:37.457 UTC
3
2019-02-04 23:44:57.14 UTC
2015-09-01 08:11:35.783 UTC
null
1,172,002
null
1,028,796
null
1
32
python|plot|plotly
51,578
<p>On your trace add: <strong>hoverinfo='skip'</strong></p> <pre><code>trace = dict( x=[1,2,3,4], y=[1,2,3,4], hoverinfo='skip' ) </code></pre>
18,154,736
has_many :through with class_name and foreign_key
<p>I'm working with a fairly straightforward has_many through: situation where I can make the class_name/foreign_key parameters work in one direction but not the other. Perhaps you can help me out. (p.s. I'm using Rails 4 if that makes a diff):</p> <p>English: A User manages many Listings through ListingManager, and a Listing is managed by many Users through ListingManager. Listing manager has some data fields, not germane to this question, so I edited them out in the below code</p> <p>Here's the simple part which works:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :listing_managers has_many :listings, through: :listing_managers end class Listing &lt; ActiveRecord::Base has_many :listing_managers has_many :managers, through: :listing_managers, class_name: "User", foreign_key: "manager_id" end class ListingManager &lt; ActiveRecord::Base belongs_to :listing belongs_to :manager, class_name:"User" attr_accessible :listing_id, :manager_id end </code></pre> <p>as you can guess from above the ListingManager table looks like:</p> <pre><code>create_table "listing_managers", force: true do |t| t.integer "listing_id" t.integer "manager_id" end </code></pre> <p>so the only non-simple here is that ListingManager uses <code>manager_id</code> rather than <code>user_id</code></p> <p>Anyway, the above works. I can call <code>user.listings</code> to get the Listings associated with the user, and I can call <code>listing.managers</code> to get the managers associated with the listing.</p> <p>However (and here's the question), I decided it wasn't terribly meaningful to say <code>user.listings</code> since a user can also "own" rather than "manage" listings, what I really wanted was <code>user.managed_listings</code> so I tweaked <code>user.rb</code> to change has_many :listings, through: :listing_managers to has_many :managed_listings, through: :listing_managers, class_name: "Listing", foreign_key: "listing_id"</p> <p>This is an exact analogy to the code in <code>listing.rb</code> above, so I thought this should work right off. Instead my rspec test of this barfs by saying <code>ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :managed_listing or :managed_listings in model ListingManager. Try 'has_many :managed_listings, :through =&gt; :listing_managers, :source =&gt; &lt;name&gt;'. Is it one of :listing or :manager?</code></p> <p>the test being:</p> <pre><code>it "manages many managed_listings" do user = FactoryGirl.build(:user) l1 = FactoryGirl.build(:listing) l2 = FactoryGirl.build(:listing) user.managed_listings &lt;&lt; l1 user.managed_listings &lt;&lt; l2 expect( @user.managed_listings.size ).to eq 2 end </code></pre> <p>Now, I'm convinced I know nothing. Yes, I guess I could do an alias, but I'm bothered that the same technique used in <code>listing.rb</code> doesn't seem to work in <code>user.rb</code>. Can you help explain?</p> <p>UPDATE: I updated the code to reflect @gregates suggestions, but I'm still running into a problem: I wrote an additional test which fails (and confirmed by "hand"-tesing in the Rails console). When one writes a test like this:</p> <pre><code>it "manages many managed_listings" do l1 = FactoryGirl.create(:listing) @user = User.last ListingManager.destroy_all @before_count = ListingManager.count expect( @before_count ).to eq 0 lm = FactoryGirl.create(:listing_manager, manager_id: @user.id, listing_id: l1.id) expect( @user.managed_listings.count ).to eq 1 end </code></pre> <p>The above fails. Rails generates the error <code>PG::UndefinedColumn: ERROR: column listing_managers.user_id does not exist</code> (It should be looking for 'listing_managers.manager_id'). So I think there's still an error on the User side of the association. In <code>user.rb</code>'s <code>has_many :managed_listings, through: :listing_managers, source: :listing</code>, how does User know to use <code>manager_id</code> to get to its Listing(s) ?</p>
18,154,959
3
0
null
2013-08-09 20:01:44.567 UTC
10
2021-06-20 20:42:51.95 UTC
2013-08-11 17:50:52.537 UTC
null
1,371,070
null
2,669,055
null
1
48
ruby-on-rails|ruby-on-rails-4
27,191
<p>The issue here is that in</p> <pre><code>has_many :managers, through: :listing_managers </code></pre> <p>ActiveRecord can infer that the name of the association on the join model (:listing_managers) <em>because it has the same name</em> as the <code>has_many :through</code> association you're defining. That is, both listings and listing_mangers have many <em>managers</em>.</p> <p>But that's not the case in your other association. There, a listing_manager <code>has_many :listings</code>, but a user <code>has_many :managed_listings</code>. So ActiveRecord is unable to infer the name of the association on <code>ListingManager</code> that it should use.</p> <p>This is what the <code>:source</code> option is for (see <a href="http://guides.rubyonrails.org/association_basics.html#has-many-association-reference" rel="nofollow noreferrer">http://guides.rubyonrails.org/association_basics.html#has-many-association-reference</a>). So the correct declaration would be:</p> <pre><code>has_many :managed_listings, through: :listing_managers, source: :listing </code></pre> <p>(p.s. you don't actually need the <code>:foreign_key</code> or <code>:class_name</code> options on the other <code>has_many :through</code>. You'd use those to define <em>direct</em> associations, and then all you need on a <code>has_many :through</code> is to point to the correct association on the <code>:through</code> model.)</p>