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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,874,330 | Rake aborted... table 'users' already exists | <p>I have created a database with devise and the nifty generator. I'm trying to make a new database with the nifty generator (<code>rails g nifty:scaffold Asset user_id:integer</code>), but when I try to migrate the database (<code>rake db:migrate</code>), I get the following error:</p>
<pre><code>charlotte-dator:showwwdown holgersindbaek$ rake db:migrate
== DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
rake aborted!
An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'users' already exists: CREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `email` varchar(255) DEFAULT '' NOT NULL, `encrypted_password` varchar(128) DEFAULT '' NOT NULL, `reset_password_token` varchar(255), `reset_password_sent_at` datetime, `remember_created_at` datetime, `sign_in_count` int(11) DEFAULT 0, `current_sign_in_at` datetime, `last_sign_in_at` datetime, `current_sign_in_ip` varchar(255), `last_sign_in_ip` varchar(255), `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code></pre>
<p>I'm following a tutorial and have quite a hard time understanding why this happens. Can anyone explain what is going on?</p> | 7,874,633 | 10 | 0 | null | 2011-10-24 10:34:37.407 UTC | 14 | 2019-07-06 16:04:42.23 UTC | 2011-10-24 10:42:39.72 UTC | null | 84,631 | null | 1,005,396 | null | 1 | 33 | ruby-on-rails|ruby|database | 48,524 | <p>The migration is trying to create a table that already exists in your database.</p>
<p>Try to remove the user table from your database. Something went wrong with you migration process. You should also compare your schema.rb version with your db/migrate/*.rb files.</p>
<p><strong>Clarification:</strong></p>
<p>It seems that many SO users don't agree with my reply, either because they consider it inaccurate or not recommended.</p>
<p>Removing a table is always destructive, and I think that everyone understands that.</p>
<p>I should have mentioned <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column" rel="nofollow noreferrer">add_column</a>, since the table was being created in another migration file.</p> |
8,215,781 | How do I compile with -Xlint:unchecked? | <p>I'm getting a message when I compile my code:</p>
<pre><code>Note: H:\Project2\MyGui2.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code></pre>
<p>How do I recompile with <code>-Xlint:unchecked</code>?</p> | 8,215,793 | 11 | 3 | null | 2011-11-21 17:19:41.517 UTC | 12 | 2021-07-10 17:20:29.317 UTC | 2012-02-12 02:04:50.493 UTC | null | 109,696 | null | 1,021,739 | null | 1 | 94 | java|compiler-errors|unchecked | 155,327 | <p>Specify it on the command line for javac:</p>
<blockquote>
<p>javac -Xlint:unchecked</p>
</blockquote>
<p>Or if you are using Ant modify your javac target</p>
<pre><code> <javac ...>
<compilerarg value="-Xlint"/>
</javac>
</code></pre>
<p>If you are using Maven, configure this in the <a href="http://maven.apache.org/plugins/maven-compiler-plugin/examples/pass-compiler-arguments.html"><code>maven-compiler-plugin</code></a> </p>
<pre><code><compilerArgument>-Xlint:unchecked</compilerArgument>
</code></pre> |
4,240,074 | JTree: how to get the text of selected item? | <p>How can I get the text of selected item in a <code>JTree</code>?</p> | 4,240,143 | 3 | 0 | null | 2010-11-21 20:10:33.607 UTC | null | 2017-06-01 18:25:16.31 UTC | 2011-07-20 16:44:22.383 UTC | null | 418,556 | null | 141,579 | null | 1 | 13 | java|swing | 41,000 | <p>From Java tutorial website on <a href="http://download.oracle.com/javase/tutorial/uiswing/components/tree.html" rel="noreferrer">JTree</a>:</p>
<pre><code>//Where the tree is initialized:
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
//Listen for when the selection changes.
tree.addTreeSelectionListener(this);
public void valueChanged(TreeSelectionEvent e) {
//Returns the last path element of the selection.
//This method is useful only when the selection model allows a single selection.
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null)
//Nothing is selected.
return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
BookInfo book = (BookInfo) nodeInfo;
displayURL(book.bookURL);
} else {
displayURL(helpURL);
}
}
</code></pre> |
4,837,492 | Difference between object and class in PHP? | <p>What is the difference between Object and Class in PHP? I ask because, I don't really see the point to both of them.</p>
<p>Can you tell me the difference with a <strong>good example</strong>?</p> | 4,837,497 | 3 | 1 | null | 2011-01-29 14:52:45 UTC | 9 | 2019-06-14 20:34:21.777 UTC | 2011-02-10 04:08:19.617 UTC | null | 106,224 | null | 272,478 | null | 1 | 28 | php|oop|class|object | 22,209 | <p>I assume you have <a href="http://www.php.net/manual/en/language.oop5.basic.php" rel="noreferrer">read the manual</a> on basic PHP OOP.</p>
<p>A class is what you use to <strong>define</strong> the properties, methods and behavior of objects. Objects are the <strong>things you create</strong> out of a class. Think of a class as a <em>blueprint</em>, and an object as the actual <em>building</em> you build by following the blueprint (class). <em>(Yes, I know the blueprint/building analogy has been done to death.)</em></p>
<pre><code>// Class
class MyClass {
public $var;
// Constructor
public function __construct($var) {
echo 'Created an object of MyClass';
$this->var = $var;
}
public function show_var() {
echo $this->var;
}
}
// Make an object
$objA = new MyClass('A');
// Call an object method to show the object's property
$objA->show_var();
// Make another object and do the same
$objB = new MyClass('B');
$objB->show_var();
</code></pre>
<p>The objects here are distinct (A and B), but they are both objects of the <code>MyClass</code> class. Going back to the blueprint/building analogy, think of it as using the same blueprint to build two different buildings.</p>
<p>Here's another snippet that actually talks about buildings if you need a more literal example:</p>
<pre><code>// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // Each building has 5 floors
private $color;
// Constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
// Build a building and paint it red
$bldgA = new Building('red');
// Build another building and paint it blue
$bldgB = new Building('blue');
// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
$bldgB->describe();
</code></pre> |
4,555,150 | Retrieving a list of GORM persistent properties for a domain | <p>What's the best/easiest way to get a list of the persistent properties associated with a given GORM domain object? I can get the list of all properties, but this list contains non-persistent fields such as <code>class</code> and <code>constraints</code>.</p>
<p>Currently I'm using this and filtering out the list of <code>nonPersistent</code> properties using a list I created:</p>
<pre><code> def nonPersistent = ["log", "class", "constraints", "properties", "errors", "mapping", "metaClass"]
def newMap = [:]
domainObject.getProperties().each { property ->
if (!nonPersistent.contains(property.key)) {
newMap.put property.key, property.value
}
}
</code></pre>
<p>There seems like there must be a better way of getting just the persistent properties.</p> | 4,556,090 | 3 | 1 | null | 2010-12-29 14:59:37.193 UTC | 14 | 2017-08-15 10:57:00.563 UTC | 2011-09-26 15:30:06.4 UTC | null | 29,995 | null | 515,065 | null | 1 | 30 | grails|grails-orm | 22,475 | <p>Try this:</p>
<pre><code>import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
...
def d = new DefaultGrailsDomainClass(YourDomain.class)
d.persistentProperties
</code></pre>
<p>Here's a link to the Grails API for <a href="http://www.grails.org/doc/1.2.x/api/org/codehaus/groovy/grails/commons/GrailsDomainClass.html" rel="noreferrer">GrailsDomainClass</a> (it's a link to an older version; I couldn't find a newer one after some quick searches). It's got a <code>getPersistentProperties()</code> (used in the code snippet above). You can traverse the API documentation to see what other methods might be useful to you.</p>
<p>If you want an example, do a <code>grails install-templates</code> and then look at <code>src/templates/scaffolding/create.gsp</code>. There's a block in there where it iterates over the persistent domain properties.</p> |
4,444,091 | Update a development team with rewritten Git repo history, removing big files | <p>I have a git repo with some very large binaries in it. I no longer need them, and I don't care about being able to checkout the files from earlier commits. So, to reduce the repo size, I want to delete the binaries from the history altogether.</p>
<p>After a web search, I concluded that my best (only?) option is to use <code>git-filter-branch</code>:</p>
<pre><code>git filter-branch --index-filter 'git rm --cached --ignore-unmatch big_1.zip big_2.zip etc.zip' HEAD
</code></pre>
<p>Does this seem like a good approach so far?</p>
<p>Assuming the answer is yes, I have another problem to contend with. The <a href="http://git-scm.com/docs/git-filter-branch" rel="noreferrer">git manual has this warning</a>:</p>
<blockquote>
<p>WARNING! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem. (See the "RECOVERING FROM UPSTREAM REBASE" section in git-rebase(1) for further information about rewriting published history.)</p>
</blockquote>
<p>We have a remote repo on our server. Each developer pushes to and pulls from it. Based on the warning above (and my understanding of how <code>git-filter-branch</code> works), I don't think I'll be able to run <code>git-filter-branch</code> on my local copy and then push the changes.</p>
<p>So, I'm tentatively planning to go through the following steps:</p>
<ol>
<li>Tell all my developers to commit, push, and stop working for a bit.</li>
<li>Log into the server and run the filter on the central repo.</li>
<li>Have everyone delete their old copies and clone again from the server.</li>
</ol>
<p>Does this sound right? Is this the best solution?</p> | 4,444,139 | 4 | 7 | null | 2010-12-14 20:51:54.09 UTC | 12 | 2014-02-19 13:02:29.467 UTC | 2013-08-08 16:10:49.627 UTC | null | 438,886 | null | 284,681 | null | 1 | 33 | git|project-planning|git-filter-branch|git-rewrite-history | 12,544 | <p>Yes, your solution will work. You also have another option: instead of doing this on the central repo, run the filter on your clone and then push it back with <code>git push --force --all</code>. This will force the server to accept the new branches from your repository. This replaces step 2 only; the other steps will be the same.</p>
<p>If your developers are pretty Git-savvy, then they might not have to delete their old copies; for example, they could fetch the new remotes and rebase their topic branches as appropriate.</p> |
4,555,938 | Auto compact the deleted space in mongodb? | <p>The mongodb document says that</p>
<blockquote>
<p>To compact this space, run db.repairDatabase() from the mongo shell (note this operation will block and is slow).</p>
</blockquote>
<p>in <a href="http://www.mongodb.org/display/DOCS/Excessive+Disk+Space">http://www.mongodb.org/display/DOCS/Excessive+Disk+Space</a></p>
<p>I wonder how to make the mongodb free deleted disk space <strong>automatically</strong> ?</p>
<p>p.s. We stored many downloading task in mongodb, up to 20GB, and finished these in half an hour.</p> | 4,560,096 | 4 | 0 | null | 2010-12-29 16:42:46.107 UTC | 31 | 2014-10-23 15:21:57.063 UTC | 2011-01-01 02:30:32.063 UTC | null | 557,346 | null | 557,346 | null | 1 | 41 | mongodb|diskspace|repair | 37,842 | <p>In general if you don't need to shrink your datafiles you shouldn't shrink them at all. This is because "growing" your datafiles on disk is a fairly expensive operation and the more space that MongoDB can allocate in datafiles the less fragmentation you will have.</p>
<p>So, you should try to provide as much disk-space as possible for the database.</p>
<p><em>However</em> if you must shrink the database you should keep two things in mind.</p>
<ol>
<li><p>MongoDB grows it's data files by
doubling so the datafiles may be
64MB, then 128MB, etc up to 2GB (at
which point it stops doubling to
keep files until 2GB.)</p></li>
<li><p>As with most any database ... to
do operations like shrinking you'll
need to schedule a separate job to
do so, there is no "autoshrink" in
MongoDB. In fact of the major noSQL databases
(hate that name) only Riak
will autoshrink. So, you'll need to
create a job using your OS's
scheduler to run a shrink. You could use an bash script, or have a job run a php script, etc.</p></li>
</ol>
<p><strong>Serverside Javascript</strong></p>
<p>You can use server side Javascript to do the shrink and run that JS via mongo's shell on a regular bases via a job (like cron or the windows scheduling service) ...</p>
<p>Assuming a collection called <strong>foo</strong> you would save the javascript below into a file called <strong>bar.js</strong> and run ...</p>
<pre><code>$ mongo foo bar.js
</code></pre>
<p>The javascript file would look something like ...</p>
<pre><code>// Get a the current collection size.
var storage = db.foo.storageSize();
var total = db.foo.totalSize();
print('Storage Size: ' + tojson(storage));
print('TotalSize: ' + tojson(total));
print('-----------------------');
print('Running db.repairDatabase()');
print('-----------------------');
// Run repair
db.repairDatabase()
// Get new collection sizes.
var storage_a = db.foo.storageSize();
var total_a = db.foo.totalSize();
print('Storage Size: ' + tojson(storage_a));
print('TotalSize: ' + tojson(total_a));
</code></pre>
<p>This will run and return something like ...</p>
<pre><code>MongoDB shell version: 1.6.4
connecting to: foo
Storage Size: 51351
TotalSize: 79152
-----------------------
Running db.repairDatabase()
-----------------------
Storage Size: 40960
TotalSize: 65153
</code></pre>
<p>Run this on a schedule (during none peak hours) and you are good to go.</p>
<p><strong>Capped Collections</strong></p>
<p>However there is one other option, <a href="http://www.mongodb.org/display/DOCS/Capped+Collections" rel="noreferrer">capped collections</a>. </p>
<blockquote>
<p>Capped collections are fixed sized
collections that have a very high
performance auto-FIFO age-out feature
(age out is based on insertion order).
They are a bit like the "RRD" concept
if you are familiar with that.</p>
<p>In addition, capped collections
automatically, with high performance,
maintain insertion order for the
objects in the collection; this is
very powerful for certain use cases
such as logging.</p>
</blockquote>
<p>Basically you can limit the size of (or number of documents in ) a collection to say .. 20GB and once that limit is reached MongoDB will start to throw out the oldest records and replace them with newer entries as they come in.</p>
<p>This is a great way to keep a large amount of data, discarding the older data as time goes by and keeping the same amount of disk-space used.</p> |
4,496,359 | How to parse date string to Date? | <p>How do I parse the date string below into a <code>Date</code> object?</p>
<pre><code>String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result = df.parse(target);
</code></pre>
<p>Throws exception...</p>
<pre><code>java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
at java.text.DateFormat.parse(DateFormat.java:337)
</code></pre> | 4,496,398 | 6 | 2 | null | 2010-12-21 04:45:54.263 UTC | 25 | 2016-02-02 16:57:26.62 UTC | 2016-02-02 16:57:26.62 UTC | null | 4,851,565 | null | 355,044 | null | 1 | 122 | java|date|format | 356,291 | <p>The pattern is wrong. You have a 3-letter day abbreviation, so it must be <code>EEE</code>. You have a 3-letter month abbreviation, so it must be <code>MMM</code>. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the <code>SimpleDateFormat</code> locale to English as well, otherwise it will use the platform default locale which may not be English per se.</p>
<pre><code>public static void main(String[] args) throws Exception {
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date result = df.parse(target);
System.out.println(result);
}
</code></pre>
<p>This prints here</p>
<pre>Thu Sep 28 07:29:30 BOT 2000</pre>
<p>which is correct as per my timezone.</p>
<p>I would also reconsider if you wouldn't rather like to use <code>HH</code> instead of <code>kk</code>. Read the <a href="http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html">javadoc</a> for details about valid patterns. </p> |
4,835,925 | unsigned APK can not be installed | <p>I am trying to distribute my application to some people for testing.
I have installed it on my Desire directly from eclipse and it works fine.</p>
<p>To create an APK-file, I choose <em>"Export Unsigned Application Package"</em> directly from eclipse, and then an APK file was created. I emailed it to myself and downloaded the file to the SD-card. But when I try to install it (using ES File Browser), I get a message saying <em>"Application not installed"</em>.</p>
<p>(I have already checked the "Allow installation of non-Market application" on my phone)
Any ideas?</p>
<p><strong>Yeah I found the problem, see my answer below:</strong></p>
<p>I did not know that even with the "<a href="http://www.androiddevelopment.org/tag/apk/">Allow Installation of non-Marked application</a>", I still needed to sign the application.
I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.</p> | 4,836,014 | 7 | 2 | null | 2011-01-29 08:40:03.43 UTC | 20 | 2019-11-24 22:46:09.117 UTC | 2012-12-03 09:40:47.697 UTC | null | 576,671 | null | 576,671 | null | 1 | 93 | android|apk|self-signed | 171,559 | <p><em>I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.</em></p>
<p>I self-signed my application, following this link <a href="http://www.androiddevelopment.org/tag/apk/" rel="noreferrer">self-sign and release application</a>, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.</p> |
4,692,161 | Non-retaining array for delegates | <p>In a Cocoa Touch project, I need a specific class to have not only a single delegate object, but many of them.</p>
<p>It looks like I should create an NSArray for these delegates;
the problem is that NSArray would have all these delegates retained, which it shouldn't (by convention objects should not retain their delegates).</p>
<p>Should I write my own array class to prevent retaining or are there simpler methods?
Thank you!</p> | 4,692,229 | 10 | 4 | null | 2011-01-14 14:37:46.63 UTC | 25 | 2017-04-13 08:24:10.2 UTC | null | null | null | null | 499,206 | null | 1 | 43 | iphone|cocoa-touch|delegates|nsarray|retain | 12,785 | <p>I found this bit of code awhile ago (can't remember who to attribute it to).</p>
<p>It's quite ingenius, using a Category to allow the creation of a mutable array that does no retain/release by backing it with a <code>CFArray</code> with proper callbacks.</p>
<pre><code>@implementation NSMutableArray (WeakReferences)
+ (id)mutableArrayUsingWeakReferences {
return [self mutableArrayUsingWeakReferencesWithCapacity:0];
}
+ (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity {
CFArrayCallBacks callbacks = {0, NULL, NULL, CFCopyDescription, CFEqual};
// We create a weak reference array
return (id)(CFArrayCreateMutable(0, capacity, &callbacks));
}
@end
</code></pre>
<p><strong>EDIT</strong> Found the original article: <a href="http://ofcodeandmen.poltras.com">http://ofcodeandmen.poltras.com</a></p> |
4,240,080 | Generating all permutations of a given string | <p>What is an elegant way to find all the permutations of a string. E.g. permutation for <code>ba</code>, would be <code>ba</code> and <code>ab</code>, but what about longer string such as <code>abcdefgh</code>? Is there any Java implementation example?</p> | 4,240,323 | 56 | 9 | null | 2010-11-21 20:11:54.423 UTC | 238 | 2021-01-02 15:50:48.91 UTC | 2020-02-01 23:23:34.553 UTC | null | 3,244,948 | null | 32,484 | null | 1 | 458 | java|algorithm | 673,548 | <pre><code>public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
</code></pre>
<p>(via <a href="http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html" rel="noreferrer">Introduction to Programming in Java</a>)</p> |
14,704,559 | How to insert image in mysql database(table)? | <p>I want to insert image into a table like</p>
<pre><code> CREATE TABLE XX_SAMPLE(ID INT
,IMAGE BLOB);
</code></pre>
<p>So can you help out form how to insert image into the above table. </p> | 14,704,709 | 8 | 1 | null | 2013-02-05 09:53:37.217 UTC | 15 | 2022-06-22 13:55:45.957 UTC | 2018-10-01 02:15:36.733 UTC | null | 3,168,721 | null | 1,845,138 | null | 1 | 22 | mysql|database|blob|mysql-loadfile | 243,183 | <p>Please try below code</p>
<pre><code>INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('E:/Images/jack.jpg'));
</code></pre> |
14,775,040 | matplotlib axis label format | <p>I am having an issue with the format of the tick labels of an axis. I disabled the offset from the y_axis:</p>
<pre><code>ax1.ticklabel_format(style = 'sci', useOffset=False)
</code></pre>
<p>and tried to put it a scientific format but all I get is:</p>
<pre><code>0.00355872
</code></pre>
<p>but I expected something like:</p>
<pre><code>3.55872...E-2
</code></pre>
<p>or similar.</p>
<p>what I really want is something like:</p>
<pre><code>3.55872... (on the tick label)
x 10^2 (or something similar - on the axis label)
</code></pre>
<p>I could try to set the labels as static,, but in the end I will have a few tens or hundreds of plots with different values, so it needs to be set dynamically.</p>
<p>An alternative would be to place the y_axis offset as the label, but I also have no clue on how to do this.</p> | 14,775,453 | 2 | 0 | null | 2013-02-08 14:45:06.69 UTC | 13 | 2017-01-14 20:39:30.27 UTC | 2013-08-16 16:21:44.147 UTC | null | 380,231 | null | 2,008,573 | null | 1 | 27 | python|matplotlib | 58,983 | <p>There are a number of ways to do this</p>
<p>You could just tweak the power limits <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.ScalarFormatter.set_powerlimits" rel="noreferrer">(doc)</a></p>
<pre><code>ax1.xaxis.get_major_formatter().set_powerlimits((0, 1))
</code></pre>
<p>which set the powers where <code>ScalerFormatter</code> switches to scientific notation</p>
<p>Or, you could use a <code>FuncFormatter</code> which gives you a good deal of control (but you can blow your foot off).</p>
<pre><code>from matplotlib import ticker
scale_pow = 2
def my_formatter_fun(x, p):
return "%.2f" % (x * (10 ** scale_pow))
ax1.get_xaxis().set_major_formatter(ticker.FuncFormatter(my_formatter_fun))
ax1.set_xlabel('my label ' + '$10^{{{0:d}}}$'.format(scale_pow))
</code></pre>
<p><code>FuncFormatter</code> <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter" rel="noreferrer">(doc)</a> takes a 2 argument function that returns a string and uses that function to format the label. (Be aware, this will also change how the values are displayed in the corner of interactive figures). The second argument is for 'position' which is an argument handed when the formatter makes the labels. You can safely ignore it, but you must take it (other wise you will get errors from wrong number of arguments). This is a consequence of the unified API of all the formatters and using the formatter for displaying the location of the mouse in interactive.</p> |
14,768,171 | Convert string representing key-value pairs to Map | <p>How can I convert a String into a Map:</p>
<pre><code>Map m = convert("A=4 H=X PO=87"); // What's convert?
System.err.println(m.getClass().getSimpleName()+m);
</code></pre>
<p>Expected output:</p>
<pre><code>HashMap{A=4, H=X, PO=87}
</code></pre> | 14,768,279 | 8 | 4 | null | 2013-02-08 08:05:14.223 UTC | 10 | 2021-04-10 09:03:39.817 UTC | 2015-09-18 12:15:51.853 UTC | user166390 | 1,816,580 | null | 114,226 | null | 1 | 42 | java|dictionary | 111,419 | <p>There is no need to reinvent the wheel. The Google Guava library provides the <a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/base/Splitter.html" rel="noreferrer"><code>Splitter</code> class</a>.</p>
<p>Here's how you can use it along with some test code:</p>
<pre><code>package com.sandbox;
import com.google.common.base.Splitter;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
Map<String, String> map = splitToMap("A=4 H=X PO=87");
assertEquals("4", map.get("A"));
assertEquals("X", map.get("H"));
assertEquals("87", map.get("PO"));
}
private Map<String, String> splitToMap(String in) {
return Splitter.on(" ").withKeyValueSeparator("=").split(in);
}
}
</code></pre> |
24,337,100 | How to create a one-to-many relationship with JDBI SQL object API? | <p>I'm creating a simple REST application with dropwizard using JDBI. The next step is to integrate a new resource that has a one-to-many relationship with another one. Until now I couldn't figure out how to create a method in my DAO that retrieves a single object that holds a list of objects from another table.</p>
<p>The POJO representations would be something like this:</p>
<p>User POJO:</p>
<pre><code>public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<p>Account POJO:</p>
<pre><code>public class Account {
private int id;
private String name;
private List<User> users;
public Account(int id, String name, List<User> users) {
this.id = id;
this.name = name;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
</code></pre>
<p>The DAO should look something like this</p>
<pre><code>public interface AccountDAO {
@Mapper(AccountMapper.class)
@SqlQuery("SELECT Account.id, Account.name, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
public Account getAccountById(@Bind("id") int id);
}
</code></pre>
<p>But when the method has a single object as return value (<em>Account</em> instead of <em>List<Account></em>) there seems to be no way to access more than one line of the resultSet in the Mapper class. The only solution that comes close I could find is described at <a href="https://groups.google.com/d/msg/jdbi/4e4EP-gVwEQ/02CRStgYGtgJ" rel="noreferrer">https://groups.google.com/d/msg/jdbi/4e4EP-gVwEQ/02CRStgYGtgJ</a> but that one also only returns a Set with a single object which does not seem very elegant. (And can't be properly used by the resouce classes.)</p>
<p>There seems to be a way using a <em>Folder2</em> in the fluent API. But I don't know how to integrate that properly with dropwizard and I'd rather stick to JDBI's SQL object API as recommended in the dropwizard documentation.</p>
<p>Is there really no way to get a one-to-many mapping using the SQL object API in JDBI? That is such a basic use case for a database that I think I must be missing something.</p>
<p>All help is greatly appreciated,
<br/> Tilman</p> | 24,548,748 | 4 | 0 | null | 2014-06-20 23:34:43.787 UTC | 18 | 2020-04-24 11:17:51.043 UTC | 2020-04-24 11:17:51.043 UTC | null | 604,156 | null | 3,761,783 | null | 1 | 33 | java|join|one-to-many|dropwizard|jdbi | 20,336 | <p>OK, after a lot of searching, I see two ways dealing with this:</p>
<p>The <strong>first option</strong> is to retrieve an object for each column and merge it in the Java code at the resource (i.e. do the join in the code instead of having it done by the database).
This would result in something like</p>
<pre><code>@GET
@Path("/{accountId}")
public Response getAccount(@PathParam("accountId") Integer accountId) {
Account account = accountDao.getAccount(accountId);
account.setUsers(userDao.getUsersForAccount(accountId));
return Response.ok(account).build();
}
</code></pre>
<p>This is feasible for smaller join operations but seems not very elegant to me, as this is something the database is supposed to do. However, I decided to take this path as my application is rather small and I did not want to write a lot of mapper code.</p>
<p>The <strong>second option</strong> is to write a mapper, that retrieves the result of the join query and maps it to the object like this:</p>
<pre><code>public class AccountMapper implements ResultSetMapper<Account> {
private Account account;
// this mapping method will get called for every row in the result set
public Account map(int index, ResultSet rs, StatementContext ctx) throws SQLException {
// for the first row of the result set, we create the wrapper object
if (index == 0) {
account = new Account(rs.getInt("id"), rs.getString("name"), new LinkedList<User>());
}
// ...and with every line we add one of the joined users
User user = new User(rs.getInt("u_id"), rs.getString("u_name"));
if (user.getId() > 0) {
account.getUsers().add(user);
}
return account;
}
}
</code></pre>
<p>The DAO interface will then have a method like this:</p>
<pre><code>public interface AccountDAO {
@Mapper(AccountMapper.class)
@SqlQuery("SELECT Account.id, Account.name, User.id as u_id, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
public List<Account> getAccountById(@Bind("id") int id);
}
</code></pre>
<p><em>Note:</em> Your abstract DAO class will quietly compile if you use a non-collection return type, e.g. <code>public Account getAccountById(...);</code>. However, your mapper will only receive a result set with a single row even if the SQL query would have found multiple rows, which your mapper will happily turn into a single account with a single user. JDBI seems to impose a <code>LIMIT 1</code> for <code>SELECT</code> queries that have a non-collection return type. It is possible to put concrete methods in your DAO if you declare it as an abstract class, so one option is to wrap up the logic with a public/protected method pair, like so:</p>
<pre><code>public abstract class AccountDAO {
@Mapper(AccountMapper.class)
@SqlQuery("SELECT Account.id, Account.name, User.id as u_id, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
protected abstract List<Account> _getAccountById(@Bind("id") int id);
public Account getAccountById(int id) {
List<Account> accountList = _getAccountById(id);
if (accountList == null || accountList.size() < 1) {
// Log it or report error if needed
return null;
}
// The mapper will have given a reference to the same value for every entry in the list
return accountList.get(accountList.size() - 1);
}
}
</code></pre>
<p>This still seems a little cumbersome and low-level to me, as there are usually a lot of joins in working with relational data. I would love to see a better way or having JDBI supporting an abstract operation for this with the SQL object API.</p> |
40,452,034 | Disable zoom in WKWebView? | <p>Does anyone know a nice simple way to disable double-click and pinch zooming in a WKWebView? Nothing I've tried works:</p>
<pre><code>Webview.scrollView.allowsMagnification = false; // Error: value of type WKWebView has no member allowsMagnification
Webview.scrollView.isMultipleTouchEnabled = false; // doesn't do anything
</code></pre>
<p>In the html:</p>
<pre><code><meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> // pile of crap, does nothing
</code></pre> | 41,741,125 | 6 | 0 | null | 2016-11-06 17:03:40.75 UTC | 8 | 2021-09-20 17:22:50.36 UTC | null | null | null | null | 346,613 | null | 1 | 29 | ios|iphone|swift|xcode | 38,141 | <p>You will have to add maximum scale in script.</p>
<p>The following code should help you:</p>
<pre><code>let source: String = "var meta = document.createElement('meta');" +
"meta.name = 'viewport';" +
"meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
"var head = document.getElementsByTagName('head')[0];" +
"head.appendChild(meta);"
let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let userContentController: WKUserContentController = WKUserContentController()
let conf = WKWebViewConfiguration()
conf.userContentController = userContentController
userContentController.addUserScript(script)
let webView = WKWebView(frame: CGRect.zero, configuration: conf)
</code></pre> |
49,468,321 | How to downgrade Flutter SDK (Dart 1.x) | <p>I upgraded my Flutter SDK and now my project is broken. I need to basically revert back to a Flutter SDK which uses Dart 1.x.</p>
<p>I tried the following in the pubspec.yaml, </p>
<pre><code>environment:
sdk: ">=1.19.0 <2.0.0"
flutter: "^0.1.2"
dependencies:
flutter:
sdk: flutter
</code></pre>
<p>but now the project just simply doesn't build.</p>
<pre><code>Running "flutter packages get" in binformed...
Package binformed requires Flutter SDK version ^0.1.2 but the current SDK is 0.2.5-pre.38.
pub get failed (1)
</code></pre>
<p>Do i need to uninstall the SDK and reinstall it?</p> | 56,127,174 | 21 | 0 | null | 2018-03-24 18:26:51.787 UTC | 31 | 2022-08-17 00:59:43.71 UTC | null | null | null | null | 2,394,052 | null | 1 | 184 | flutter | 264,769 | <p>Flutter is versioned using git. Changing the Flutter version is as simple as changing git branch.</p>
<p>There are 2 different ways:</p>
<ul>
<li><code>flutter channel <branch></code> (example: <code>flutter channel stable</code>)</li>
</ul>
<p>This command is used to change between branches – usually <code>stable</code>/<code>dev</code>/<code>beta</code>/<code>master</code>.
We can also put a specific commit id from git.</p>
<ul>
<li><code>flutter downgrade <version></code> (example: <code>flutter downgrade v1.2.1</code>)</li>
</ul>
<p>This command will use a specific version number.
You can have the list of the available version numbers using <code>flutter downgrade</code> or <a href="https://github.com/flutter/flutter/tags" rel="noreferrer">here</a></p>
<p>After this, run any Flutter command (such as <code>flutter doctor</code>), and Flutter will take care of downloading/compiling everything required to run this version.</p> |
49,787,327 | Selenium on MAC, Message: 'chromedriver' executable may have wrong permissions | <p>I'm just trying to do something very basic on my Mac using selenium and I can't even open a webpage. I'm getting an error of :</p>
<pre><code>Traceback (most recent call last):
File "/Users/godsinred/Desktop/InstagramLiker/GmailAccountGenerator.py", line 10, in <module>
driver = webdriver.Chrome()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__
self.service.start()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 88, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code></pre>
<p>Here is my code below:</p>
<pre><code>from selenium import webdriver
import time
link = "https://accounts.google.com"
driver = webdriver.Chrome()
driver.get(link)
time.sleep(5)
driver.quit()
</code></pre> | 49,788,993 | 6 | 0 | null | 2018-04-12 03:06:46.85 UTC | 8 | 2021-08-09 20:49:23.413 UTC | 2018-04-12 05:46:09.59 UTC | null | 7,429,447 | null | 9,232,616 | null | 1 | 13 | python|selenium|selenium-webdriver|webdriver|selenium-chromedriver | 65,364 | <p>The error says it all :</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code></pre>
<p>The error clearly mentions that the <em>chromedriver</em> which is getting detected have wrong permissions.</p>
<hr>
<h2>Solution</h2>
<ul>
<li>Download the latest <em>chromedriver</em> binary from <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="noreferrer">ChromeDriver - WebDriver for Chrome</a> and save it in your system.</li>
<li>Ensure that <em>chromedriver</em> binary have the required permissions.</li>
<li><p>While initiating the <em>WebDriver</em> and <em>WebClient</em> pass the argument <strong>executable_path</strong> along with the absolute path of the <em>chromedriver</em> binary as follows :</p>
<pre><code>from selenium import webdriver
link = "https://accounts.google.com"
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get(link)
</code></pre></li>
</ul>
<hr>
<h2>Reference</h2>
<p>You can find a detailed relevant discussion in:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/47148872/webdrivers-executable-may-have-wrong-permissions-please-see-https-sites-goo/47150939#47150939">'Webdrivers' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home</a></li>
</ul> |
49,976,188 | Copy docker image between repositories | <p>I have 2 private docker repositories. Is any way how can I copy one image from one repository to the second one?</p> | 49,976,528 | 2 | 0 | null | 2018-04-23 08:06:17.033 UTC | 8 | 2022-03-04 18:32:57.273 UTC | null | null | null | null | 1,749,895 | null | 1 | 43 | docker | 27,103 | <p>You can pull the image, tag it and push it to the new registry.</p>
<p>Example:</p>
<pre class="lang-sh prettyprint-override"><code>docker pull old-registry/app:some_tag
docker tag old-registry/app:some_tag new-registry/app:some_tag
docker push new-registry/app:some_tag
</code></pre> |
49,826,230 | Regional/Edge-optimized API Gateway VS Regional/Edge-optimized custom domain name | <p>This does not make sense to me at all. When you create a new API Gateway you can specify whether it should be regional or edge-optimized. But then again, when you are creating a custom domain name for API Gateway, you can choose between the two.</p>
<p>Worst of all, you can mix and match them!!! You can have a regional custom domain name for an edge-optimized API gateway and it's absolutely meaningless to me!</p>
<p>Why these two can be regional/edge-optimized separately? And when do I want each of them to be regional/edge-optimized?</p> | 49,845,124 | 1 | 0 | null | 2018-04-13 23:08:13.773 UTC | 41 | 2021-07-29 16:00:24.023 UTC | null | null | null | null | 866,082 | null | 1 | 99 | amazon-web-services|aws-api-gateway | 29,947 | <blockquote>
<p><em>Why these two can be regional/edge-optimized separately?</em></p>
</blockquote>
<p>Regional and Edge-Optimized are deployment options. Neither option changes anything fundamental about how the API is processed by the AWS infrastructure once the request arrives at the core of the API Gateway service or how the services behind API Gateway ultimately are accessed -- what changes is <em>how</em> the requests initially arrive at AWS and are delivered to the API Gateway core for execution. More about this, below.</p>
<p>When you use a custom domain name, your selected API stage is deployed a second time, on a second endpoint, which is why you have a second selection of a deployment type that must be made.</p>
<p>Each endpoint has the characteristics of its deployment type, whether regional or edge-optimized. The original deployment type of the API itself does not impact the behavior of the API if deployed with a custom domain name, and subsequently accessed using that custom domain name -- they're independent.</p>
<p>Typically, if you deploy your API with a custom domain name, you wouldn't continue to use the deployment endpoint created for the main API (e.g. <code>xxxx.execute-api.{region}.amazonaws.com</code>), so the initial selection should not matter.</p>
<blockquote>
<p><em>And when do I want each of them to be regional/edge-optimized?</em></p>
</blockquote>
<p>If you're using a custom domain name, then, as noted above, your original deployment selection for the API as a whole has no further impact when you use the custom domain.</p>
<p>Edge-optimized endpoints were originally the only option available. If you don't have anything on which to base your selection, this choice is usually a reasonable one.</p>
<p>This option routes incoming requests through the AWS "Edge Network," which is the CloudFront network, with its 100+ global edge locations. This does not change where the API Gateway core ultimately handles your requests -- they are still ultimately handled within the same region -- but the requests are routed from all over the world into the nearest AWS edge, and they travel from there on networks operated by AWS to arrive at the region where you deployed your API.</p>
<p>If the clients of your API Gateway stage are globally dispersed, and you are only deploying your API in a single region, you probably want an edge-optimized deployment.</p>
<p>The edge-optimized configuration tends to give you better global responsiveness, since it tends to reduce the impact of network round trips, and the quality of the transport is not subject to as many of the vagaries of the public Internet because the request covers the least amount of distance possible before jumping off the Internet and onto the AWS network. The TCP handshake and TLS are negotiated with the connecting browser/client across a short distance (from the client to the edge) and the edge network maintains keep-alive connections that can be reused, all of which usually works in your favor... but this optimization becomes a relative impairment when your clients are always (or usually) calling the API from within the AWS infrastructure, within the same region, since the requests need to hop over to the edge network and then back into the core regional network.</p>
<p>If the clients of your API Gateway stage are inside AWS and within the same region where you deployed the API (such as when the API is being called by other systems in EC2 within the region), then you will most likely want a regional endpoint. Regional endpoints route requests through less of the AWS infrastructure, ensuring minimal latency and reduced jitter when requests are coming from EC2 within the same region.</p>
<p>As a side-effect of routing through the edge network, edge-optimized endpoints also provide some additional request headers that you may find useful, such as <code>CloudFront-Viewer-Country: XX</code> which attempts to identify the two-digit country code of the geographic location of the client making the API request. Regional endpoints don't have these headers.</p>
<p>As a general rule, go with edge-optimized unless you find a reason not to.</p>
<p>What would be some reasons not to? As mentioned above, if you or others are calling the API from within the same AWS region, you probably want a regional endpoint. Edge-optimized endpoints can introduce some edge-case side-effects in more advanced or complicated configurations, because of the way they integrate into the rest of the infrastructure. There are some things you can't do with an edge-optimized deployment, or that are not optimal if you do:</p>
<ul>
<li><p>if you are using CloudFront for other sites, unrelated to API Gateway, and CloudFront is configured for a wildcard alternate domain name, like <code>*.example.com</code>, then you can't use a subdomain from that wildcard domain, such as <code>api.example.com</code>, on an edge-optimized endpoint with a custom domain name, because API Gateway submits a request to the edge network on your behalf to claim all requests for that subdomain when they arrive via CloudFront, and CloudFront rejects this request since it represents an unsupported configuration when used with API Gateway, even though CloudFront supports it in some other circumstances.</p>
</li>
<li><p>if you want to provide redundant APIs that respond to the same custom domain name in multiple regions, and use Route 53 Latency-Based Routing to deliver requests to the region nearest to the requester, you can't do this with an edge-optimized custom domain, because the second API Gateway region will not be able to claim the traffic for that subdomain on the edge network, since the edge network requires exactly 1 target for any given domain name (subdomain). This configuration can be achieved using regional endpoints and Route 53 LBR, or can be achieved while leveraging the edge network by using your own CloudFront distribution, Lambda@Edge to select the target endpoint based on the caller's location, and API Gateway regional deployments. Note that this can't be achieved by any means if you need to support IAM authentication of the caller, because the caller needs to know the target region before signing and submitting the request.</p>
</li>
<li><p>if you want to use your API as part of a larger site that integrates multiple resources, is deployed behind CloudFront, and uses the path to route to different services -- for example, <code>/images/*</code> might route to an S3 bucket, <code>/api/*</code> might route to your API Gateway stage, and <code>*</code> (everything else) might route to an elastic load balancer in EC2 -- then you don't want to use an edge-optimized API, because this causes your requests to loop through the edge network twice (increasing latency) and causes some header values to be lost. This configuration doesn't break, but it isn't optimal. For this, a regional endpoint is desirable.</p>
</li>
</ul> |
39,283,807 | How to take screenshot of portion of UIView? | <p>I want the user to go on my app and take a screenshot of the app after pressing a button programmatically in Swift. I know that <code>UIGraphicsGetImageFromCurrentImageContext()</code> takes a screenshot but I don't want a picture of the entire screen. I want a rectangle to pop up (sort of like a crop tool) and the user can drag and resize the rectangle to take a screenshot of only a certain part of the screen. I want the rectangle to go over a <code>WKWebView</code> and crop a pic of the web view.</p> | 39,299,100 | 3 | 0 | null | 2016-09-02 03:20:12.393 UTC | 10 | 2022-07-29 05:59:03.477 UTC | 2016-09-02 20:04:01.55 UTC | null | 1,271,826 | null | 5,808,311 | null | 1 | 15 | ios|swift|screenshot|wkwebview | 10,342 | <p>The standard snapshot technique is <a href="https://developer.apple.com/documentation/uikit/uiview/1622589-drawhierarchy" rel="noreferrer"><code>drawHierarchy(in:afterScreenUpdates:)</code></a>, drawing that to an image context. In iOS 10 and later, you can use <a href="https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer" rel="noreferrer"><code>UIGraphicsImageRenderer</code></a>:</p>
<pre><code>extension UIView {
/// Create image snapshot of view.
///
/// - Parameters:
/// - rect: The coordinates (in the view's own coordinate space) to be captured. If omitted, the entire `bounds` will be captured.
/// - afterScreenUpdates: A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes. Defaults to `true`.
///
/// - Returns: The `UIImage` snapshot.
func snapshot(of rect: CGRect? = nil, afterScreenUpdates: Bool = true) -> UIImage {
return UIGraphicsImageRenderer(bounds: rect ?? bounds).image { _ in
drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
}
}
}
</code></pre>
<p>And you’d use that like so:</p>
<pre><code>let image = webView.snapshot(of: rect)
</code></pre>
<hr>
<p>Prior to iOS 10, you would to get portion of an image, you can use <code>CGImage</code> method <a href="https://developer.apple.com/documentation/coregraphics/cgimage/1454683-cropping" rel="noreferrer"><code>cropping(to:)</code></a>. E.g.:</p>
<pre><code>extension UIView {
/// Create snapshot
///
/// - Parameters:
/// - rect: The coordinates (in the view's own coordinate space) to be captured. If omitted, the entire `bounds` will be captured.
/// - afterScreenUpdates: A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes. Defaults to `true`.
///
/// - Returns: Returns `UIImage` of the specified portion of the view.
func snapshot(of rect: CGRect? = nil, afterScreenUpdates: Bool = true) -> UIImage? {
// snapshot entire view
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// if no `rect` provided, return image of whole view
guard let image = wholeImage, let rect = rect else { return wholeImage }
// otherwise, grab specified `rect` of image
guard let cgImage = image.cgImage?.cropping(to: rect * image.scale) else { return nil }
return UIImage(cgImage: cgImage, scale: image.scale, orientation: .up)
}
}
</code></pre>
<p>Which uses this little convenient operator:</p>
<pre><code>extension CGRect {
static func * (lhs: CGRect, rhs: CGFloat) -> CGRect {
return CGRect(x: lhs.minX * rhs, y: lhs.minY * rhs, width: lhs.width * rhs, height: lhs.height * rhs)
}
}
</code></pre>
<p>And to use it, you can do:</p>
<pre><code>if let image = webView.snapshot(of: rect) {
// do something with `image` here
}
</code></pre>
<hr>
<p>For Swift 2 rendition, see <a href="https://stackoverflow.com/revisions/39299100/4">previous revision of this answer</a>.</p> |
46,227,462 | How to use code that relies on ThreadLocal with Kotlin coroutines | <p>Some JVM frameworks use <code>ThreadLocal</code> to store the call context of a application, like the <a href="https://logback.qos.ch/manual/mdc.html" rel="noreferrer">SLF4j MDC</a>, transaction managers, security managers, and others.</p>
<p>However, Kotlin coroutines are dispatched on different threads, so how it can be made to work? </p>
<p>(The question is inspired by <a href="https://github.com/Kotlin/kotlinx.coroutines/issues/119" rel="noreferrer">GitHub issue</a>)</p> | 46,227,463 | 2 | 0 | null | 2017-09-14 20:08:43.6 UTC | 14 | 2022-08-10 13:05:42.923 UTC | 2019-03-19 07:47:56.677 UTC | null | 1,103,872 | null | 1,051,598 | null | 1 | 39 | kotlin|coroutine|kotlin-coroutines | 12,641 | <p>Coroutine's analog to <code>ThreadLocal</code> is <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/" rel="noreferrer"><code>CoroutineContext</code></a>.</p>
<p>To interoperate with <code>ThreadLocal</code>-using libraries you need to implement a custom <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-continuation-interceptor/index.html" rel="noreferrer"><code>ContinuationInterceptor</code></a> that supports framework-specific thread-locals.</p>
<p>Here is an example. Let us assume that we use some framework that relies on a specific <code>ThreadLocal</code> to store some application-specific data (<code>MyData</code> in this example):</p>
<pre><code>val myThreadLocal = ThreadLocal<MyData>()
</code></pre>
<p>To use it with coroutines, you'll need to implement a context that keeps the current value of <code>MyData</code> and puts it into the corresponding <code>ThreadLocal</code> every time the coroutine is resumed on a thread. The code should look like this:</p>
<pre><code>class MyContext(
private var myData: MyData,
private val dispatcher: ContinuationInterceptor
) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
dispatcher.interceptContinuation(Wrapper(continuation))
inner class Wrapper<T>(private val continuation: Continuation<T>): Continuation<T> {
private inline fun wrap(block: () -> Unit) {
try {
myThreadLocal.set(myData)
block()
} finally {
myData = myThreadLocal.get()
}
}
override val context: CoroutineContext get() = continuation.context
override fun resume(value: T) = wrap { continuation.resume(value) }
override fun resumeWithException(exception: Throwable) = wrap { continuation.resumeWithException(exception) }
}
}
</code></pre>
<p>To use it in your coroutines, you wrap the dispatcher that you want to use with <code>MyContext</code> and give it the initial value of your data. This value will be put into the thread-local on the thread where the coroutine is resumed.</p>
<pre><code>launch(MyContext(MyData(), CommonPool)) {
// do something...
}
</code></pre>
<p>The implementation above would also track any changes to the thread-local that was done and store it in this context, so this way multiple invocation can share "thread-local" data via context.</p>
<p><strong>UPDATE</strong>: Starting with <code>kotlinx.corutines</code> version <code>0.25.0</code> there is direct support for representing Java <code>ThreadLocal</code> instances as coroutine context elements. See <a href="https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#thread-local-data" rel="noreferrer">this documentation</a> for details. There is also out-of-the-box support for SLF4J MDC via <code>kotlinx-coroutines-slf4j</code> integration module.</p> |
21,260,542 | Cannot uninstall MySQL Connector/Net 6.3 or higher | <p>I cannot install MySQL Connector/Net due MS Web Platform because of that error.</p>
<blockquote>
<p>MSI (s) (E4:D8) [12:15:40:237]: Doing action: LaunchConditions Action
ended 12:15:40: SetHLMPath. Return value 1. Action start 12:15:40:
LaunchConditions. MSI (s) (E4:D8) [12:15:40:238]: Product: MySQL
Connector Net 6.5.4 -- A previous version of Connector/Net 6.3 or
higher is already installed. Please uninstall that version first.</p>
<p>Action ended 12:15:40: LaunchConditions. Return value 3. Action ended
12:15:40: INSTALL. Return value 3. MSI (s) (E4:D8) [12:15:40:239]:
Note: 1: 1708 MSI (s) (E4:D8) [12:15:40:239]: Product: MySQL
Connector Net 6.5.4 -- Installation failed.</p>
<p>MSI (s) (E4:D8) [12:15:40:239]: Windows Installer installed the
product. Product Name: MySQL Connector Net 6.5.4. Product Version:
6.5.4. Product Language: 1033. Manufacturer: Oracle. Installation success or error status: 1603.</p>
</blockquote>
<p>I don't have connector installed under <code>Program Files/MySQL</code> folder as well as I cannot find any key in <code>windows registry</code> with <code>Connector/Net</code></p>
<p>Any clue how I can fix it?</p> | 21,263,907 | 9 | 0 | null | 2014-01-21 14:12:34.277 UTC | 3 | 2020-06-02 15:14:52.527 UTC | 2014-01-21 14:29:08.18 UTC | null | 196,919 | null | 196,919 | null | 1 | 5 | .net|windows|uninstallation|mysql-connector | 51,752 | <p>I just found 100% working solution and could install MySQL Connector/Net via Web Platform.</p>
<p>What you have to do is just open Windows registry and look up for keys, values, data using
<code>MySQL Connector Net</code> keyword.</p>
<p>Delete all things you will find. That is it!</p> |
37,277,738 | Can I create nested collections in Jekyll? | <p>I would like to use Jekyll to create a manual that contains several chapters, each of which contains several sections, and store each section in a separate Markdown file. I want <code>index.md</code> to look something like this:</p>
<pre><code><ol>
{% for chapter in site.chapters %}
<li>
<a href="{{chapter.url}}">{{chapter.title}}</a>
<ol>
{% for section in chapter.sections %}
<li><a href="{{section.url}}">{{section.title}}</a></li>
{% endfor %}
</ol>
</li>
{% endfor %}
<ol>
</code></pre>
<p>If each chapter is a Markdown file in <code>_chapters</code>, and I add the right lines to <code>_config.yml</code>, I can iterate over the chapters, pull out the title field from the YAML header, etc. Is there a way to nest this? I've tried creating sub-directories under <code>_chapters</code> with various names, but (a) Jekyll doesn't pick them up as sub-collections and (b) there's no obvious place to store chapter-level information (like the chapter's overall title).</p>
<p>(Note: I think I can do this by explicitly enumerating chapters and sections in a block of YAML in <code>_config.yml</code>, or by creating a separate YAML file in <code>_data</code>, but I don't want to have to worry about keeping that enumeration in sync with the actual chapters and sections: I'd like Jekyll to pick up changes automatically.)</p> | 37,770,419 | 2 | 0 | null | 2016-05-17 13:35:04.46 UTC | 11 | 2018-06-24 00:59:54.683 UTC | null | null | null | null | 1,403,470 | null | 1 | 20 | jekyll | 7,000 | <p>So the best way I know how to do this is to invert your thinking.</p>
<p>You're not writing <em>chapters</em>, you're writing <em>sections</em> and organising them <em>into</em> chapters.</p>
<p>Assume you have a setup like this:</p>
<ul>
<li>_sections
<ul>
<li>section01.md</li>
<li>section02.md</li>
<li>section03.md</li>
<li>section04.md</li>
</ul></li>
</ul>
<p>But you want it output like this:</p>
<ul>
<li>_site
<ul>
<li>chapters
<ul>
<li>chapter1.html (contains <code>section01.md</code> followed by <code>section03.md</code>)</li>
<li>chapter2.html (contains <code>section02.md</code> followed by <code>section04.md</code>)</li>
</ul></li>
</ul></li>
</ul>
<p>If that's the case, you can do so using collections. Set the <code>chapter</code> property in the frontmatter of <code>section01.md</code> and <code>section03.md</code> to <code>01</code> and the <code>chapter</code> property in the frontmatter of <code>section02.md</code> and <code>section04.md</code> to <code>02</code>.</p>
<p>The problem is generating the pages for the chapters. You <em>do</em> need to make a page for each chapter, but it's not bad if you use a layout.</p>
<p>Here's the layout I used (in <code>_layouts/chapter.html</code>):</p>
<pre><code>---
layout: default
---
<h1>Chapter {{ page.chapter }}</h1>
{% for section in site.sections %}
{% if section.chapter == page.chapter %}
{{ section.output }}
{% endif %}
{% endfor %}
</code></pre>
<p>Then in <code>_chapters</code>, I have <code>chapter01.md</code>, which looks like this:</p>
<pre><code>---
chapter: 01
layout: chapter
---
</code></pre>
<p>Just copy that to <code>chapter02.md</code> and set the <code>chapter</code> property to <code>02</code>, and now you have Chapter 2.</p>
<p>The only other thing required to make this work is updating your config:</p>
<pre><code>collections:
sections:
output: false
chapters:
output: true
</code></pre>
<p>When you run <code>jekyll build</code>, you'll now have <code>_site/chapters/chapter01.html</code> and <code>_site/chapters/chapter02.html</code>. As new sections get created, they'll be added to whatever chapter is in their frontmatter.</p>
<p>This is all really confusing, so I set up a sample at <a href="http://paddycarver.github.io/jekyll-nested-collections-example/" rel="noreferrer">http://paddycarver.github.io/jekyll-nested-collections-example/</a> with source code at <a href="https://github.com/paddycarver/jekyll-nested-collections-example" rel="noreferrer">https://github.com/paddycarver/jekyll-nested-collections-example</a>.</p> |
41,732,819 | Why StatefulSets? Can't a stateless Pod use persistent volumes? | <p>I am trying to understand <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="noreferrer">Stateful Sets</a>. How does their use differ from the use of "stateless" Pods with Persistent Volumes? That is, assuming that a "normal" Pod may lay claim to persistent storage, what obvious thing am I missing that requires this new construct (with ordered start/stop and so on)?</p> | 41,733,207 | 2 | 0 | null | 2017-01-19 02:37:27.18 UTC | 34 | 2022-03-01 05:18:41.563 UTC | 2020-03-18 15:19:21.047 UTC | null | 558,825 | null | 208,288 | null | 1 | 105 | kubernetes|kubernetes-statefulset | 18,200 | <p>Yes, a regular pod can use a persistent volume. However, sometimes you have multiple pods that logically form a "group". Examples of this would be database replicas, ZooKeeper hosts, Kafka nodes, etc. In all of these cases there's a bunch of servers and they work together and talk to each other. What's special about them is that each individual in the group has an identity. For example, for a database cluster one is the master and two are followers and each of the followers communicates with the master letting it know what it has and has not synced. So the followers know that "db-x-0" is the master and the master knows that "db-x-2" is a follower and has all the data up to a certain point but still needs data beyond that.</p>
<p>In such situations you need a few things you can't easily get from a regular pod:</p>
<ol>
<li>A predictable name: you want to start your pods telling them where to find each other so they can form a cluster, elect a leader, etc. but you need to know their names in advance to do that. Normal pod names are random so you can't know them in advance.</li>
<li>A stable address/DNS name: you want whatever names were available in step (1) to stay the same. If a normal pod restarts (you redeploy, the host where it was running dies, etc.) on another host it'll get a new name and a new IP address. </li>
<li>A persistent <strong>link</strong> between an individual in the group and their persistent volume: if the host where one of your database master was running dies it'll get moved to a new host but should connect to the <strong>same</strong> persistent volume as there's one and only 1 volume that contains the right data for that "individual". So, for example, if you redeploy your group of 3 database hosts you want the same individual (by DNS name and IP address) to get the same persistent volume so the master is still the master and still has the same data, replica1 gets it's data, etc.</li>
</ol>
<p>StatefulSets solve these issues because they provide (quoting from <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="noreferrer">https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/</a>):</p>
<ol>
<li>Stable, unique network identifiers.</li>
<li>Stable, persistent storage.</li>
<li>Ordered, graceful deployment and scaling.</li>
<li>Ordered, graceful deletion and termination.</li>
</ol>
<p>I didn't really talk about (3) and (4) but that can also help with clusters as you can tell the first one to deploy to become the master and the next one find the first and treat it as master, etc.</p>
<p>As some have noted, you can indeed can <strong>some</strong> of the same benefits by using regular pods and services, but its much more work. For example, if you wanted 3 database instances you could manually create 3 deployments and 3 services. Note that you must manually create <strong>3 deployments</strong> as you can't have a service point to a single pod in a deployment. Then, to scale up you'd manually create another deployment and another service. This does work and was somewhat common practice before PetSet/PersistentSet came along. Note that it is missing some of the benefits listed above (persistent volume mapping & fixed start order for example).</p> |
51,523,225 | Can I use multiple NavHostFragments in Navigation Component? | <p>Please look at the flowchart I made if you have difficulty in understanding the following paragraph.</p>
<p>I'm currently making a notes app with 3 top level destinations. One of the top-level destinations(NotesList) displays a list of notes created by the user. NotesList has a filter button which brings up a bottom modal sheet with FilterMenu destination. FilterMenu has a search button, which on clicking, replaces the contents of the sheet with a Search destination and a button named tags which on clicking, replaces the contents of the sheet with a fragment containing list of the tags associated with all the notes(TagList destination).</p>
<p><a href="https://i.stack.imgur.com/MwAEh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MwAEh.png" alt="enter image description here"></a></p>
<p>Everything in blue is a top level destination. Everything in purple is present in the modal sheet.</p>
<p>The FilterMenu, Search and the TagList are displayed in a modal sheet. Which means that the NotesList <strong><em>contains</em></strong> these fragments and is not replaced by them. They exist in a region of screen smaller than the NotesList. If I use navigation, the fragments will replace each other.</p>
<p>Can I use two NavHosts? One for the top-level destinations and one for the stuff in the modal sheet? If so, how would I implement it? If not, what's the recommended thing to do in this case?</p> | 56,620,939 | 2 | 0 | null | 2018-07-25 15:58:26.64 UTC | 11 | 2019-06-20 05:32:58.497 UTC | 2018-07-25 16:19:27.223 UTC | null | 8,204,374 | null | 8,204,374 | null | 1 | 23 | android|android-architecture-components|android-architecture-navigation | 5,445 | <p>You can create two navigation graphs to achieve the behavior you want. One for the top level destinations and a second one for the modal sheet. They need to be independent and do not have any links between each other. You can't use only one nav graph as the "navigation surface" is a different one. For the main navigation it's the activity and for the modal bottom sheet it's the bottom sheets window (which is in case of a BottomSheetDialogFragment actually a different window).</p>
<p>In theory this can be achieved very easily:</p>
<ul>
<li><code>main_nav.xml</code> holds <code>Settings</code>, <code>NoteList</code> and <code>Trash</code> </li>
<li><code>filter_nav.xml</code> holds the <code>FilterMenu</code>, <code>Search</code>, and <code>TagList</code></li>
</ul>
<p>If you don't want back navigation on the top level you can even do the top level without a navigation controller using fragment transactions.</p>
<p>So basically you need a <code>(BottomSheet)DialogFragment</code> which needs an seperate <code>NavHost</code> independent from the main/other <code>NavHost</code>. You can achieve this with following class:</p>
<p>dialog_fragment_modal_bottom_sheet.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/filterNavHost"/>
</code></pre>
<p>ModalBottomSheetDialogFragment .kt</p>
<pre><code>class ModalBottomSheetDialogFragment : BottomSheetDialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.dialog_fragment_modal_bottom_sheet, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// We can't inflate the NavHostFragment from XML because it will crash the 2nd time the dialog is opened
val navHost = NavHostFragment()
childFragmentManager.beginTransaction().replace(R.id.filterNavHost, navHost).commitNow()
navHost.navController.setGraph(R.navigation.filter_nav)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
// Normally the dialog would close on back press. We override this behaviour and check if we can navigate back
// If we can't navigate back we return false triggering the default implementation closing the dialog
setOnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
view?.findNavController()?.popBackStack() == true
} else {
false
}
}
}
}
}
</code></pre>
<p>We do two tricks here:</p>
<ol>
<li><p>We need to manually create the <code>NavHost</code> fragment. If we directly put it into XML, it will crash the second time the dialog is opened as the ID is already used</p></li>
<li><p>We need to overwrite the dialog's back navigation. A dialog is a separate window on top of your activity, so the <code>Activity</code>'s <code>onBackPressed()</code> gets not called. Instead, we add a <code>OnKeyListener</code> and when the back button is released (<code>ACTION_UP</code>) we check with the <code>NavController</code> whether it can pop the back stack (go back) or not. If it can pop the back stack we return true and thus consume the back event. The dialog stays open and the <code>NavController</code> goes one step back. If it is already at the starting point, the dialog will close as we return false.</p></li>
</ol>
<p>You can now create a nested graph inside the dialog and not care about the outer graph. To show the dialog with the nested graph use:</p>
<pre><code>val dialog = ModalBottomSheetDialogFragment()
dialog.show(childFragmentManager, "filter-menu")
</code></pre>
<p>You could also add the <code>ModalBottomSheetDialogFragment</code> as <code><dialog></code> destination in <code>main_nav</code>, I did not test this though. This feature is currently still in alpha and was introduced in navigation 2.1.0-alpha03. Because this is still in alpha, the API might change and I'd personally use the code above to show the dialog. As soon as this is out of alpha/beta, using a destination in <code>main_nav.xml</code> should be the preferred way. The different way to show the dialog makes no difference from a user's perspective.</p>
<p>I create a sample application with your navigation structure <a href="https://github.com/crysxd/NestedNavHostsExample" rel="noreferrer">here on GitHub</a>. It has working back navigation on both levels with the two independent graphs. You can see it working <a href="https://youtu.be/lnyDB7DH9KM" rel="noreferrer">here on Youtube</a>. I used a bottom bar for the main navigation, but you can replace it with a drawer instead.</p> |
28,812,851 | Why is this printing 'None' in the output? | <p>I have defined a function as follows:</p>
<pre><code>def lyrics():
print "The very first line"
print lyrics()
</code></pre>
<p>However why does the output return <code>None</code>: </p>
<pre><code>The very first line
None
</code></pre> | 28,812,876 | 2 | 0 | null | 2015-03-02 14:59:04.353 UTC | 22 | 2022-04-07 15:39:01.487 UTC | 2018-06-07 15:15:52.137 UTC | null | 355,230 | null | 4,623,860 | null | 1 | 55 | python|nonetype | 199,242 | <p>Because there are <strong>two print statements</strong>. First is inside function and second is outside function. When a function doesn't return anything, it implicitly returns <code>None</code>.</p>
<p>Use <code>return</code> statement at end of function to return value.</p>
<p>e.g.:</p>
<p>Return <code>None</code>.</p>
<pre><code>>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
</code></pre>
<p>Use return statement</p>
<pre><code>>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
</code></pre> |
18,504,835 | PIL decoder jpeg not available on ubuntu x64, | <p>I know that this question looks like a duplicate but I've followed many online instructions on how to properly install PIL and none have worked.</p>
<p>I've tried everything in: <a href="https://stackoverflow.com/questions/8915296/decoder-jpeg-not-available-pil">Python Image Library fails with message "decoder JPEG not available" - PIL</a> with no success.</p>
<p>When I run sudo pip install pil, worst of all, there is a misleading error. Jpeg, Freetyle, etc support is all listed as available. But when running some python code using PIL, the
notorious IOError of "decoder jpeg not available' comes up. </p>
<p>Even after symlinking into /usr/lib for the .so libjpeg files, nothing has worked.</p>
<p>Any ideas? Thank you.</p> | 20,091,508 | 1 | 0 | null | 2013-08-29 07:33:52.507 UTC | 8 | 2015-07-16 06:28:54.273 UTC | 2017-05-23 12:33:28.577 UTC | null | -1 | null | 1,660,802 | null | 1 | 10 | python|jpeg|python-imaging-library | 14,400 | <p>You can try this:<br></p>
<p><strong>1. clear PIL packages</strong></p>
<pre><code>rm -rf /usr/lib/python2.7/site-packages/PIL
rm -rf /usr/lib/python2.7/site-packages/PIL.pth
</code></pre>
<p><strong>2. install required packages</strong></p>
<pre><code>ubuntu:
apt-get install libjpeg-dev libfreetype6-dev zlib1g-dev libpng12-dev
centos:
yum install zlib zlib-devel
yum install libjpeg libjpeg-devel
yum install freetype freetype-devel
</code></pre>
<p><strong>3.download Image and install</strong></p>
<pre><code>wget http://effbot.org/downloads/Imaging-1.1.7.tar.gz
tar xzvf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# if the sys is x64, you must also do this: edit the setup.py file and set:
# centOS:
TCL_ROOT = '/usr/lib64'
JPEG_ROOT = '/usr/lib64'
ZLIB_ROOT = '/usr/lib64'
TIFF_ROOT = '/usr/lib64'
FREETYPE_ROOT = '/usr/lib64'
LCMS_ROOT = '/usr/lib64'
# Ubuntu:
TCL_ROOT = '/usr/lib/x86_64-linux-gnu'
JPEG_ROOT = '/usr/lib/x86_64-linux-gnu'
ZLIB_ROOT = '/usr/lib/x86_64-linux-gnu'
TIFF_ROOT = '/usr/lib/x86_64-linux-gnu'
FREETYPE_ROOT = '/usr/lib/x86_64-linux-gnu'
LCMS_ROOT = '/usr/lib/x86_64-linux-gnu'
#then install it use:
python2.7 setup.py install
</code></pre>
<p><strong>4. check if it works</strong></p>
<pre><code># before this command you should run `mv PIL PIL2`
python2.7 selftest.py
</code></pre>
<p>If the result is:</p>
<pre><code>--- PIL CORE support ok
--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
*** LITTLECMS support not installed
--------------------------------------------------------------------
Running selftest:
--- 57 tests passed.
</code></pre>
<p>Congratulation!!</p> |
23,701,450 | Find recent object changes in SQL Server Database | <p>I've <strong>added</strong> and <strong>modified</strong> several (new and existing resp.) <strong>tables</strong> and <strong>stored procs</strong>, for a particular <strong>database</strong> and <strong>server</strong>, in <strong>last 3 months</strong>. </p>
<p>I was thinking if there's any SQL query by which I can determine all those changes.</p>
<p>Thanks.</p> | 23,702,332 | 3 | 0 | null | 2014-05-16 17:39:38.273 UTC | 11 | 2017-05-12 23:32:44.217 UTC | 2014-05-16 19:11:18.513 UTC | null | 609,736 | null | 609,736 | null | 1 | 18 | sql-server-2008|tsql | 97,083 | <p>Query the <code>sys.objects</code> table to find the objects that changed and filter by <code>modify_date</code> and <code>type</code>; U = User table, P = Stored procedure. </p>
<pre><code>select *
from sys.objects
where (type = 'U' or type = 'P')
and modify_date > dateadd(m, -3, getdate())
</code></pre>
<p>This approach will tell you what objects have changed, but not the specific changes.</p> |
23,469,784 | com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field | <p>i got a deserialization problem: </p>
<p>This is my class:</p>
<pre><code>public class Response {
private Object ResObj;
private int ResInt;
public Object getResObj() {
return ResObj;
}
public int getResInt() {
return ResInt;
}
}
</code></pre>
<p>the JSON i want to deserialize is:</p>
<pre><code>{"ResObj":{"ClientNum":"12345","ServerNum":"78945","IdNum":"020252"},"ResInt":0}
</code></pre>
<p>I get this exception:</p>
<pre><code>Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResObj" , not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader@1f758500; line: 1, column: 20] (through reference chain: ["ResObj"])
</code></pre>
<p>I don't want to add:</p>
<pre><code>@JsonIgnoreProperties(ignoreUnknown = true)
</code></pre>
<p>because I want to get the ResObj...</p>
<p>if I add the annotation, it pass but it will set it as null .. which I don't want.</p> | 26,371,693 | 7 | 0 | null | 2014-05-05 10:03:13.51 UTC | 7 | 2021-12-08 17:29:39.423 UTC | 2014-05-05 10:07:22.843 UTC | null | 3,489,260 | null | 2,212,726 | null | 1 | 31 | java|json|jackson | 105,822 | <p>If you don't want to have a setter in your bean and only use fields and getters, you can use the visibility checker of <code>ObjectMapper</code> to allow field visibility.<br>
Something like following:</p>
<pre><code>ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
</code></pre> |
59,291,371 | Migrating from Springfox Swagger 2 to Springdoc Open API | <p>I try to follow these:</p>
<p><a href="https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/" rel="noreferrer">https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/</a></p>
<p>How do I deal with annotations like:</p>
<ul>
<li><code>@ApiModel(value = "Response container")</code></li>
<li><code>@ApiModelProperty(value = "Iventory response", required = true)</code></li>
</ul> | 59,995,027 | 2 | 1 | null | 2019-12-11 17:46:02.03 UTC | 26 | 2021-10-18 16:46:45.797 UTC | 2021-10-18 16:46:45.797 UTC | null | 5,277,820 | null | 255,139 | null | 1 | 52 | swagger-2.0|openapi|springdoc | 45,688 | <h1><a href="https://springdoc.org/#migrating-from-springfox" rel="noreferrer">Migrating from SpringFox</a></h1>
<ul>
<li>Remove springfox and swagger 2 dependencies. Add <code>springdoc-openapi-ui</code> dependency instead.</li>
</ul>
<pre class="lang-xml prettyprint-override"><code> <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>@springdoc.version@</version>
</dependency>
</code></pre>
<ul>
<li><p>Replace swagger 2 annotations with swagger 3 annotations (it is already included with <code>springdoc-openapi-ui</code> dependency).
Package for swagger 3 annotations is <code>io.swagger.v3.oas.annotations</code>.</p>
<ul>
<li><code>@ApiParam</code> -> <code>@Parameter</code></li>
<li><code>@ApiOperation</code> -> <code>@Operation</code></li>
<li><code>@Api</code> -> <code>@Tag</code></li>
<li><code>@ApiImplicitParams</code> -> <code>@Parameters</code></li>
<li><code>@ApiImplicitParam</code> -> <code>@Parameter</code></li>
<li><code>@ApiIgnore</code> -> <code>@Parameter(hidden = true)</code> or <code>@Operation(hidden = true)</code> or <code>@Hidden</code></li>
<li><code>@ApiModel</code> -> <code>@Schema</code></li>
<li><code>@ApiModelProperty</code> -> <code>@Schema</code></li>
</ul>
</li>
<li><p>This step is optional: Only if you have <strong>multiple</strong> <code>Docket</code> beans replace them with <code>GroupedOpenApi</code> beans.</p>
<p>Before:</p>
<pre class="lang-java prettyprint-override"><code> @Bean
public Docket publicApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.public"))
.paths(PathSelectors.regex("/public.*"))
.build()
.groupName("springshop-public")
.apiInfo(apiInfo());
}
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.admin"))
.paths(PathSelectors.regex("/admin.*"))
.build()
.groupName("springshop-admin")
.apiInfo(apiInfo());
}
</code></pre>
<p>Now:</p>
<pre class="lang-java prettyprint-override"><code> @Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.setGroup("springshop-public")
.pathsToMatch("/public/**")
.build();
}
@Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.setGroup("springshop-admin")
.pathsToMatch("/admin/**")
.build();
}
</code></pre>
<p>If you have <strong>only one</strong> <code>Docket</code> -- remove it and instead add properties to your <code>application.properties</code>:</p>
<pre><code>springdoc.packagesToScan=package1, package2
springdoc.pathsToMatch=/v1, /api/balance/**
</code></pre>
</li>
<li><p>Add bean of <code>OpenAPI</code> type. See example:</p>
<pre class="lang-java prettyprint-override"><code> @Bean
public OpenAPI springShopOpenAPI() {
return new OpenAPI()
.info(new Info().title("SpringShop API")
.description("Spring shop sample application")
.version("v0.0.1")
.license(new License().name("Apache 2.0").url("http://springdoc.org")))
.externalDocs(new ExternalDocumentation()
.description("SpringShop Wiki Documentation")
.url("https://springshop.wiki.github.org/docs"));
}
</code></pre>
</li>
<li><p>If the swagger-ui is served behind a proxy:</p>
<ul>
<li><a href="https://springdoc.org/faq.html#how-can-i-deploy-springdoc-openapi-ui-behind-a-reverse-proxy" rel="noreferrer">https://springdoc.org/faq.html#how-can-i-deploy-the-doploy-springdoc-openapi-ui-behind-a-reverse-proxy</a>.</li>
</ul>
</li>
<li><p>To customise the Swagger UI</p>
<ul>
<li><a href="https://springdoc.org/faq.html#how-can-i-configure-swagger-ui" rel="noreferrer">https://springdoc.org/faq.html#how-can-i-configure-swagger-ui</a>.</li>
</ul>
</li>
<li><p>To hide an operation or a controller from documentation</p>
<ul>
<li><a href="https://springdoc.org/faq.html#how-can-i-hide-an-operation-or-a-controller-from-documentation-" rel="noreferrer">https://springdoc.org/faq.html#how-can-i-hide-an-operation-or-a-controller-from-documentation-</a>.</li>
</ul>
</li>
</ul> |
21,045,951 | Slide 2 items in OWL Carousel | <p>I am using an <a href="http://www.owlgraphic.com/owlcarousel/" rel="noreferrer">OWL Carousel</a> for my slider.</p>
<p>What I am trying to do is slide 2 items when next previous is clicked.</p>
<p>So its sliding to every second item still showing the second item during the transmission.</p>
<p>I have tried to work it out with CSS but no success.</p>
<p>Here is my basic setup</p>
<pre><code>$("#owl-demo").owlCarousel({
navigation : true, // Show next and prev buttons
slideSpeed : 600,
paginationSpeed : 400,
singleItem:true,
// "singleItem:true" is a shortcut for:
// items : 2
// itemsDesktop : false,
// itemsDesktopSmall : false,
// itemsTablet: false,
// itemsMobile : false
</code></pre>
<p>});</p>
<p>Any help much appreciated.</p>
<p>Thanks in advance.</p> | 21,947,609 | 8 | 0 | null | 2014-01-10 13:45:22.797 UTC | 1 | 2018-11-29 03:21:19.407 UTC | 2014-05-06 15:36:28.953 UTC | null | 1,281,433 | null | 177,435 | null | 1 | 12 | javascript|jquery|css|carousel|owl-carousel | 73,684 | <p>In the current version of Owl Carousel (1.3.2), find the "owl.carousel.js" file and scroll to line #558. The line will read:</p>
<pre><code>base.currentItem += base.options.scrollPerPage === true ? base.options.items : 1;
</code></pre>
<p>Change the last number to "2" so that it reads: </p>
<pre><code>base.currentItem += base.options.scrollPerPage === true ? base.options.items : 2;
</code></pre>
<p>Save the file, and that should make the slider move by two items. </p> |
34,662,574 | Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC | <p>I just installed <code>Node.js</code> on my <code>Ubuntu 14.04</code> operating system for the first time. I also installed <code>npm</code>. The next step in my installation process was installing <code>nodemon</code>. This all worked out fine. </p>
<hr>
<p><strong><em>But, when I run <code>nodemon</code> by typing <code>nodemon app.js</code> in my command line, I get the following error...</em></strong> </p>
<p><code>[nodemon] 1.8.1
[nodemon] to restart at any time, enter</code>rs<code>
[nodemon] watching: *.*
[nodemon] starting</code>node app.js<code>
[nodemon] Internal watch failed: watch ENOSPC
</code></p>
<p><strong><em>In the command line below the error...</em></strong></p>
<pre><code>alopex@Alopex:~/Desktop/coding_dojo/week-9/javascript/node/testing_node$ Hello World
</code></pre>
<p>Why is this happening? Is this normal behavior for nodemon? If not, how can I fix it? </p>
<hr>
<p><strong><em>Side notes...</em></strong></p>
<p>1) <code>app.js</code> is a <code>Javascript</code> file with <code>console.log(111)</code> inside of it.<br>
2) <code>node</code> version is <code>v0.10.25</code><br>
3) <code>npm</code> version is <code>1.3.10</code><br>
4) <code>nodemon</code> version is <code>1.8.1</code><br>
5) <code>ubuntu</code> version is...<br></p>
<pre><code>Distributor ID: Ubuntu
Description: Ubuntu 14.04.3 LTS
Release: 14.04
Codename: trusty
</code></pre> | 34,664,097 | 11 | 1 | null | 2016-01-07 18:31:37.407 UTC | 55 | 2021-07-08 11:58:06.177 UTC | null | null | null | null | 5,182,047 | null | 1 | 179 | javascript|node.js | 165,655 | <p>It appears that my max ports weren't configured correctly. I ran the following code and it worked... </p>
<pre><code>echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
</code></pre>
<p>What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When <code>nodemon</code> tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.</p>
<p>You could also solve this problem by:</p>
<pre><code>sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p
</code></pre>
<p>But the way it was written first will make this change permanent.</p> |
47,924,501 | Add strong typing for react navigation props | <p>I'm using typescript in my react-native project(expo).</p>
<p>The project uses react-navigation, so on my screens I can set <code>navigationOptions</code> and I have access to the prop <code>navigation</code>.</p>
<p>Now I'm trying to strongly type these so I get hints for what properties are available to set.</p>
<pre><code>interface NavStateParams {
someValue: string
}
interface Props extends NavigationScreenProps<NavStateParams> {
color: string
}
class Screen extends React.Component<Props, any> {
// This works fine
static navigationOptions: NavigationStackScreenOptions = {
title: 'ScreenTitle'
}
// Does not work
static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
title: navigation.state.params.someValue
})
}
</code></pre>
<p>What would be the best way to handle react-navigation as props for components.</p> | 48,858,643 | 12 | 0 | null | 2017-12-21 11:57:04.717 UTC | 11 | 2022-03-09 07:55:51.12 UTC | null | null | null | null | 2,280,574 | null | 1 | 46 | typescript|react-native|react-navigation | 51,170 | <p>Just add NavigationType to your Props, like this:</p>
<pre><code> import { StackNavigator, NavigationScreenProp } from 'react-navigation';
export interface HomeScreenProps {
navigation: NavigationScreenProp<any,any>
};
export class HomeScreen extends React.Component<HomeScreenProps, object> {
render() {
return (
<View style={styles.container}>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
</code></pre> |
41,936,524 | Validation of form input fields in React | <pre><code><div className="form-group">
<label className="col-sm-0 control-label"> Name : &nbsp; </label>
<input
type="text"
value={this.state.UserName}
onChange={this.handleChangeUserName}
placeholder="Name"
pattern="[A-Za-z]{3}"
className="form-control"
/>
</div>
</code></pre>
<p>Hi, I am trying to validate a form input field in React using pattern validation. But it's not working. I am using validation as simple as <code>pattern="[A-Za-z]{3}"</code>.</p>
<p>Kindly let me know how to work this out. Putting validation in React Bootstrap component.</p> | 41,936,774 | 3 | 0 | null | 2017-01-30 12:58:00.75 UTC | 3 | 2019-04-15 10:11:18.907 UTC | 2018-07-30 17:08:32.583 UTC | null | 990,356 | null | 6,786,855 | null | 1 | 8 | twitter-bootstrap|validation|reactjs | 62,148 | <p>You are using the value property (means controlled component) of <code>input</code> element and updating the state in <code>onChange</code> method, So you can easily test this regex in <code>onChange</code> and update the state only when the input will be valid. </p>
<p>Like this:</p>
<pre><code>handleChangeUserName(e){
if(e.target.value.match("^[a-zA-Z ]*$") != null){
this.setState({UserName: e.target.value});
}
}
</code></pre>
<p>Check the working code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class HelloWidget extends React.Component {
constructor(){
super();
this.state={UserName:''}
this.handleChangeUserName = this.handleChangeUserName.bind(this);
}
handleChangeUserName(e){
if(e.target.value.match("^[a-zA-Z ]*$")!=null) {
this.setState({UserName: e.target.value});
}
}
render(){
return(
<div className="form-group">
<label className="col-sm-0 control-label" htmlFor="textinput"> Name : &nbsp; </label>
<input type="text" value={this.state.UserName} onChange={this.handleChangeUserName} placeholder="Name" className="form-control"></input>
</div>
)
}
}
ReactDOM.render(<HelloWidget/>, document.getElementById('container'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container' /></code></pre>
</div>
</div>
</p>
<p>Check the <code>jsfiddle</code> for working example: <a href="https://jsfiddle.net/uL4fj4qL/11/" rel="noreferrer">https://jsfiddle.net/uL4fj4qL/11/</a></p>
<p>Check this <code>jsfiddle</code>, <code>Material-Ui snackbar</code> added to show the error, if user tries to enter the wrong value: <a href="https://jsfiddle.net/4zqwq1fj/" rel="noreferrer">https://jsfiddle.net/4zqwq1fj/</a> </p> |
24,579,608 | Android Resource Qualifiers -sw#dp vs -w#dp | <p>Say I'm developing a different layout for devices with screen size equal to or greater than 600dp.
I want to use the post android 3.2 resource qualifiers. I created a folder named <code>layout-sw600dp</code> and put my layout there, but at the same time I could have created a folder named <code>layout-w600dp</code> and put the layout xml file there.
I'm trying to figure out what is the difference between <code>-sw600dp</code> and <code>-w600dp</code>? After all they are both meant to use the layout for device of width >= 600dp.</p> | 24,579,622 | 1 | 0 | null | 2014-07-04 18:53:47.393 UTC | 5 | 2021-03-25 14:45:40.997 UTC | 2021-03-25 14:45:40.997 UTC | null | 1,000,551 | null | 1,409,534 | null | 1 | 36 | android|android-layout|android-resource-qualifiers | 9,440 | <p><code>sw</code> is "<em>smallest</em> width". It doesn't change if the device is rotated.</p>
<p><code>w</code>, on the other hand, is available (i.e. <em>current</em>) width.</p>
<p>See <a href="http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources">Providing Alternative Resources</a>:</p>
<blockquote>
<p><strong>smallestWidth - <code>sw<N>dp</code></strong> - The smallestWidth is a fixed screen size characteristic of the device;
the device's smallestWidth does not change when the screen's
orientation changes.</p>
<p><strong>Available width - <code>w<N>dp</code></strong> - This configuration value will change when the orientation changes between landscape and portrait to match
the current actual width.</p>
</blockquote>
<p>Example. Say that you have a device that is 600dp x 400dp.</p>
<ul>
<li>If you have a w600dp resource, it will be used in landscape, but not in portrait.</li>
<li>If you have a sw600dp resource, it will not be used for any orientation (smallest is 400).</li>
</ul> |
3,138,946 | Mocking The PDO Object using PHPUnit | <p>I'm having difficulty mocking the PDO object with PHPUnit.</p>
<p>There doesn't seem to be much information on the web about my problem but from what I can gather:</p>
<ol>
<li>PDO has 'final' __wakeup and
__sleep methods that prevent it from being serialised. </li>
<li>PHPunit's mock object implementation serialises the object at some point.</li>
<li>The unit tests then fail with a PHP error generated by PDO when this occurs.</li>
</ol>
<p>There is a feature meant to prevent this behavior, by adding the following line to your unit test:</p>
<pre><code>class MyTest extends PHPUnit_Framework_TestCase
{
protected $backupGlobals = FALSE;
// ...
}
</code></pre>
<p>Source: <a href="http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html" rel="noreferrer">http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html</a> </p>
<p>This isnt working for me, my test still produces an error. </p>
<p>Full test code:</p>
<pre><code>class MyTest extends PHPUnit_Framework_TestCase
{
/**
* @var MyTest
*/
private $MyTestr;
protected $backupGlobals = FALSE;
/**
* Prepares the environment before running a test.
*/
protected function setUp()
{
parent::setUp();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown()
{
parent::tearDown();
}
public function __construct()
{
$this->backupGlobals = false;
parent::__construct();
}
/**
* Tests MyTest->__construct()
*/
public function test__construct()
{
$pdoMock = $this->getMock('PDO', array('prepare'), array(), '', false);
$classToTest = new MyTest($pdoMock);
// Assert stuff here!
}
// More test code.......
</code></pre>
<p>Any PHPUnit pro's give me a hand? </p>
<p>Thanks,</p>
<p>Ben</p> | 4,082,629 | 3 | 1 | null | 2010-06-29 08:19:04.97 UTC | 9 | 2013-09-18 05:42:35.553 UTC | 2012-06-24 18:53:23.907 UTC | null | 7,894 | null | 127,477 | null | 1 | 33 | php|unit-testing|pdo|phpunit | 10,617 | <p>$backupGlobals does not help you, because this error comes from elsewhere. PHPUnit 3.5.2 (possibly earlier versions as well) has the following code in PHPUnit/Framework/MockObject/Generator.php</p>
<pre><code> if ($callOriginalConstructor &&
!interface_exists($originalClassName, $callAutoload)) {
if (count($arguments) == 0) {
$mockObject = new $mock['mockClassName'];
} else {
$mockClass = new ReflectionClass($mock['mockClassName']);
$mockObject = $mockClass->newInstanceArgs($arguments);
}
} else {
// Use a trick to create a new object of a class
// without invoking its constructor.
$mockObject = unserialize(
sprintf(
'O:%d:"%s":0:{}',
strlen($mock['mockClassName']), $mock['mockClassName']
)
);
}
</code></pre>
<p>This "trick" with unserialize is used when you ask getMock to not execute the original constructor and it will promptly fail with PDO.</p>
<p>So, how do work around it?</p>
<p>One option is to create a test helper like this</p>
<pre><code>class mockPDO extends PDO
{
public function __construct ()
{}
}
</code></pre>
<p>The goal here is to get rid of the original PDO constructor, which you do not need. Then, change your test code to this:</p>
<pre><code>$pdoMock = $this->getMock('mockPDO', array('prepare'));
</code></pre>
<p>Creating mock like this <em>will</em> execute original constructor, but since it is now harmless thanks to mockPDO test helper, you can continue testing.</p> |
3,185,975 | Remove items from IEnumerable<T> | <p>I have 2 IEnumerable collections.</p>
<pre><code>IEnumerable<MyClass> objectsToExcept
</code></pre>
<p>and </p>
<pre><code>IEnumerable<MyClass> allObjects.
</code></pre>
<p><code>objectsToExcept</code> may contain objects from <code>allObjects</code>.</p>
<p>I need to remove from <code>allObjects</code> objects in <code>objectsToExcept</code>. For example:</p>
<pre><code>foreach (var myClass in objectsToExcept)
{
allObjects.Remove(myClass);
}
</code></pre>
<p>Or</p>
<pre><code>allObject.Except(objectsToExcept)
</code></pre>
<p>But it doesn't work. The count after the methods have execute indicate that no items have been removed.</p> | 3,185,995 | 4 | 0 | null | 2010-07-06 12:01:25.77 UTC | 10 | 2016-05-12 21:31:21.643 UTC | 2013-10-30 16:31:09.227 UTC | null | 1,823,494 | null | 136,188 | null | 1 | 46 | c#|linq|ienumerable | 87,140 | <p>I don't see how the first version would compile, and the second version won't do anything unless you use the result. It doesn't remove anything from the existing collection - indeed, there may not even <em>be</em> an in-memory collection backing it. It just returns a sequence which, when iterated over, will return the appropriate values.</p>
<p>If you <em>are</em> using the result, e.g.</p>
<pre><code>IEnumerable<MyClass> others = allObjects.Except(objectsToExcept);
foreach (MyClass x in others)
{
...
}
</code></pre>
<p>then it should be fine <em>if</em> you've overridden <code>GetHashCode</code> and <code>Equals</code> <em>or</em> if you're happy to use reference equality. Are you trying to remove logically-equal values, or do the same <em>references</em> occur in both sequences? Have you overridden <code>GetHashCode</code> and <code>Equals</code>, and if so, are you sure those implementations work?</p>
<p>Basically it should be fine - I suggest you try to create a short but complete program that demonstrates the problem; I suspect that while doing so, you'll find out what's wrong.</p> |
2,416,803 | jQuery :contains selector to search for multiple strings | <p>Assuming i have:</p>
<pre><code><li id="1">Mary</li>
<li id="2">John, Mary, Dave</li>
<li id="3">John, Dave, Mary</li>
<li id="4">John</li>
</code></pre>
<p>If i need to find all <li> Elements which contain "John" and "Mary", how would i construct the jQuery?</p>
<p>A search for a single string seems easy:</p>
<pre><code>$('li:contains("John")').text()
</code></pre>
<p>I am looking for something like the following pseudo code:</p>
<pre><code>$('li:contains("John")' && 'li:contains("Mary")').text()
</code></pre>
<p>Thanks!</p> | 2,417,076 | 4 | 0 | null | 2010-03-10 12:29:30.263 UTC | 25 | 2018-12-26 02:33:58.973 UTC | 2010-03-13 12:47:35.15 UTC | null | 2,115,830 | null | 2,115,830 | null | 1 | 74 | jquery|jquery-selectors|css-selectors|contains | 64,443 | <h3>Answer</h3>
<p>To find <code>li</code>'s that have text containing BOTH Mary <strong>AND</strong> John:</p>
<pre><code>$('li:contains("Mary"):contains("John")')
</code></pre>
<p>To find <code>li</code>'s that have text containing EITHER Mary <strong>OR</strong> John:</p>
<pre><code>$('li:contains("Mary"), li:contains("John")')
</code></pre>
<h3>Explanation</h3>
<p>Just think of the <code>:contains</code> as if it was a class declaration, like <code>.class</code>:</p>
<pre><code>$('li.one.two'). // Find <li>'s with classes of BOTH one AND two
$('li.one, li.two'). // Find <li>'s with a class of EITHER one OR two
</code></pre>
<p>It's the same with <code>:contains</code>:</p>
<pre><code>$('li:contains("Mary"):contains("John")'). // Both Mary AND John
$('li:contains("Mary"), li:contains("John")'). // Either Mary OR John
</code></pre>
<h3>Demo</h3>
<p><a href="http://jsbin.com/ejuzi/edit" rel="noreferrer">http://jsbin.com/ejuzi/edit</a></p> |
49,249,862 | React Native done button above keyboard | <p>I want to add a "Done" button above the keyboard, that will hide the keyboard when clicked.</p>
<p>Here's an image demonstrating the desired button:</p>
<p><img src="https://i.stack.imgur.com/XI3r1.jpg" alt="An image demonstrating the desired button" /></p>
<p>Is there any existing method or library for that? (I already found <a href="https://www.npmjs.com/package/react-native-keyboard-done-button" rel="nofollow noreferrer">this library</a> but it doesn't work).</p> | 49,250,692 | 5 | 0 | null | 2018-03-13 06:46:18.883 UTC | 5 | 2022-01-13 23:35:21.793 UTC | 2022-01-13 23:35:21.793 UTC | null | 14,070,872 | null | 9,328,497 | null | 1 | 22 | react-native | 47,335 | <p><strong>For numeric and number-pad :</strong></p>
<p>and seems that you don't need any library
<code>returnKeyType='done' works with "number-pad" and "numeric" on v0.47.1</code></p>
<p><strong>for normal keyboard you may look at this :</strong> </p>
<p><a href="https://github.com/ardaogulcan/react-native-keyboard-accessory" rel="noreferrer">https://github.com/ardaogulcan/react-native-keyboard-accessory</a></p>
<p>and</p>
<p><a href="https://github.com/douglasjunior/react-native-keyboard-manager" rel="noreferrer">https://github.com/douglasjunior/react-native-keyboard-manager</a></p>
<p><strong>Github thread you need to take a look at :</strong> </p>
<p><a href="https://github.com/facebook/react-native/issues/1190" rel="noreferrer">https://github.com/facebook/react-native/issues/1190</a></p>
<p>and </p>
<p><a href="https://github.com/facebook/react-native/issues/641" rel="noreferrer">https://github.com/facebook/react-native/issues/641</a></p>
<p>Hope it helps </p> |
38,409,074 | Xcode-beta 8. Can't create core data | <p>I have been trying to add core data.
And every time I got the same error: </p>
<pre><code>error: filename "EntityName +CoreDataClass.swift" used twice: '/Users/userName/Desktop/Development/MyApp/AppName/EntityName +CoreDataClass.swift' and '/Users/userName/Library/Developer/Xcode/DerivedData/AppName-dgwzrmxsetzvtedibxrazuutjwnh/Build/Intermediates/AppName.build/Debug-iphoneos/AppName.build/DerivedSources/CoreDataGenerated/Model/EntityName +CoreDataClass.swift'
</code></pre>
<p>I add core data using the following steps:<br>
1.New file/ DataModel; save it in the root dir of my project<br>
select Model.xcdatamodeld and add entity, add several attributes, save,
editor/create NSManagedObjectClass Subclass.</p>
<p>As a result I observe 4 new files in navigator:
Model.xcdatamodeld, EntityName+CoreDataProperties.swift, EntityName +CoreDataClass.swift, <strong>_COREDATA_DATAMODELNAME_</strong>+CoreDataModel.swift</p>
<p>their content:
<strong>_COREDATA_DATAMODELNAME_</strong>+CoreDataModel.swift: </p>
<pre><code>import Foundation
import CoreData
___COREDATA_DATAMODEL_MANAGEDOBJECTCLASSES_IMPLEMENTATIONS___
</code></pre>
<p>EntityName +CoreDataClass.swift: </p>
<pre><code>import Foundation
import CoreData
class EntityName: NSManagedObject {
}
</code></pre>
<p>EntityName+CoreDataProperties.swift: </p>
<pre><code>import Foundation
import CoreData
extension EntityName {
@nonobjc class func fetchRequest() -> NSFetchRequest< EntityName > {
return NSFetchRequest< EntityName >(entityName: "EntityName");
}
@NSManaged var str: String?
}
</code></pre>
<p>What I have tried:<br>
1. Clean build, remove DerivedData, delete content of var/folders, restart<br>
2. Delete generated files, displayed in navigator</p>
<p>All my efforts were out of luck.<br>
What I am doing wrong?</p> | 38,413,941 | 9 | 0 | null | 2016-07-16 07:55:01.447 UTC | 11 | 2018-12-10 12:15:46.787 UTC | 2016-07-16 21:21:42.113 UTC | null | 1,280,794 | null | 1,280,794 | null | 1 | 40 | ios|swift|core-data|xcode8 | 16,771 | <p>Xcode 8 includes automatic <code>NSManagedObject</code> class generation when the model file uses the Xcode 8 file format. If you create your own subclass files, you're creating duplicates. The second file in the error message, in <code>DerivedSources</code>, is the one that Xcode created automatically.</p>
<p>If the automatically generated files do what you need, just stop creating your own and you'll be OK.</p>
<p>If you want to create your own subclasses instead, you can either</p>
<ul>
<li>Set the "tools version" for the model file to be Xcode 7.3 or earlier to disable all code generation (this doesn't seem to change anything meaningful about the actual file contents), or</li>
<li>Disable automatic generation for each entity individually by setting the "Codegen" setting to "Manual/None" for the entity.</li>
</ul> |
38,103,920 | How to use javascript functions in an Angular 2 component from a different file | <p>I have a javascript file that contains some data manipulation functions (No DOM manipulation at all) such as float rounding, mathematical operations, ...etc</p>
<p>my js file called <strong><em>myexample.js</em></strong> looks like that</p>
<pre><code>function example(input) {
return input * 2
}
module.exports = { example: example }
</code></pre>
<p>and then I have my angular component <strong><em>example.component.ts</em></strong></p>
<p>for example: </p>
<pre><code>import { Component, EventEmitter} from '@angular/core';
@Component({
selector: 'input-number',
template: `<input
type='text'
[(value)]='value'
(blur)='runExample()'
/>`,
inputs: ['value'],
outputs: ['valueChange']
})
export class Example {
value: string;
valueChange = new EventEmitter;
runExample() {
let val = parseFloat(this.value);
// here i need to call example(input) from myexample.js
// and assign the return to val
this.valueChange.emit(val);
}
</code></pre>
<p>I have been searching for quite a while now and tried multiple things but unfortunately with no luck at all. </p>
<p>I would be really grateful if someone can help.</p> | 38,814,299 | 4 | 0 | null | 2016-06-29 15:25:37.153 UTC | 5 | 2018-05-03 11:29:25.67 UTC | null | null | null | null | 6,076,645 | null | 1 | 17 | typescript|angular | 44,999 | <p>I finally found out the answer; it was to basically make a typings file and add it to the project.</p>
<p>The problem was related to TypeScript not Angular2. In typeScript you can't simply use any JS file without having a definition (typing) file that declares the types of the vars, the params of the functions, as well as the returns. check <a href="https://peter.grman.at/how-to-write-typescript-definition-files/" rel="nofollow noreferrer">this link</a> to know how to create one. </p> |
38,175,086 | Facebook login in react-native & firebase 3.1 | <p>Recently firebase team have released their new version 3.1 of firebase which is compatible with react-native. I'm trying to use the new firebase api with facebook. </p>
<p>Since firebase doesn't support popup or redirect in react-native, i'm using <a href="https://github.com/facebook/react-native-fbsdk">react-native-fbsdk</a> to get the access token but when I'm trying to use auth.signInWithCredential, the sign in fail on </p>
<blockquote>
<p>code: "auth/app-not-authorized",<br>
message: "This app, identified by
the domain where it's hosted, is not authorized to use Firebase
Authentication with the provided API key. Review your key
configuration in the Google API console."</p>
</blockquote>
<p>This is my code. any help would be very much appreciated.</p>
<pre><code>import { LoginManager, AccessToken} from 'react-native-fbsdk';
import firebase from '../Services/firebase';
const auth = firebase.auth();
const provider = firebase.auth.FacebookAuthProvider;
LoginManager.logInWithReadPermissions(['public_profile'])
.then(loginResult => {
if (loginResult.isCancelled) {
console.log('user canceled');
return;
}
AccessToken.getCurrentAccessToken()
.then(accessTokenData => {
const credential = provider.credential(accessTokenData.accessToken);
return auth.signInWithCredential(credential);
})
.then(credData => {
console.log(credData);
})
.catch(err => {
console.log(err);
});
});
</code></pre> | 38,192,291 | 1 | 0 | null | 2016-07-03 23:03:04.497 UTC | 15 | 2016-12-24 16:51:33.59 UTC | null | null | null | null | 1,861,047 | null | 1 | 18 | facebook|firebase|react-native|firebase-authentication | 5,885 | <p>We managed to find the problem. It seems that the credentials firebase gave us were obsolete for some reason.<br>
From google <a href="https://console.developers.google.com/apis/credentials" rel="nofollow noreferrer">console</a> we found out, a new apiKey was somehow generated (maybe during the upgrade to firebase 3?) and the firebase key was marked as Previous key.<br>
Once we updated the new apiKey in our application, everything started working.</p> |
758,050 | Automatic Hibernate Transaction Management with Spring? | <p>How far does the spring framework go with transaction handling? My reading of the book "Spring In Action" suggestions with its examples that you create DAO methods that don't worry about Session and Transaction management fairly simply by setting up a session factory and transaction template in XML and then wiring them into your DAO. SpringSource.org's documentation, on the other hand, suggests that need tons of XML and/or annotation to make this happen.</p>
<p>What is the truth here, what is the simplest way I can take code along the lines of</p>
<pre><code>get session from sessionfactory
open transaction
preform database actions
commit transaction with error handling
</code></pre>
<p>and make it just</p>
<pre><code>preform database actions
</code></pre>
<p>reducing the amount of boiler plate transactional code that I have across my methods to a minimum?</p> | 760,662 | 2 | 0 | null | 2009-04-16 21:06:27.023 UTC | 9 | 2009-04-17 15:37:50.143 UTC | 2009-04-17 15:37:50.143 UTC | null | 20,774 | null | 20,774 | null | 1 | 11 | hibernate|spring|transactions|dao | 29,705 | <p>Spring provides at least 3 ways of transaction demarcation:</p>
<p>1) Programmatic handling, via TransactionTemplate or PlatformTransactionManager - light on config, but invasive </p>
<p>2) Declarative via XML - verbose XML, but non-invasive</p>
<p>3) Declarative via annotations - light on XML, not invasive</p>
<p>Which one you pick depends on which one best suits your needs, Spring doesn't make that choice for you. From your question, it sounds like the annotation approach is what you're after.</p>
<p>I suggest reading the Spring reference manual, the section of annotation-driven transaction handling. It's clear and concise. </p>
<p>I always consult the ref docs first, and only consult a book if it's not in the docs.</p> |
46,571 | cfqueryparam with like operator in ColdFusion | <p>I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <code><cfqueryparam</code>> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?</p>
<p>If my query looks like this:</p>
<pre><code>select * from Foo where name like '%Bob%'
</code></pre>
<p>what should my <code><cfqueryparam</code>> tag look like?</p> | 47,197 | 2 | 0 | null | 2008-09-05 19:00:58.793 UTC | 3 | 2013-05-16 14:09:10.663 UTC | 2013-03-08 14:36:53.163 UTC | null | 1,430,996 | Doug R | 3,271 | null | 1 | 28 | coldfusion|railo|cfml|openbd | 10,111 | <p>@Joel, I have to disagree.</p>
<pre><code>select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" />
</code></pre>
<ol>
<li><p>Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!)</p></li>
<li><p>The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.</p></li>
<li><p>When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.</p></li>
</ol> |
3,062,804 | Scala Unit type | <p>I use opencsv to parse csv files, and my code is</p>
<pre><code>while( (line = reader.readNext()) != null ) { .... }
</code></pre>
<p>I got a compiler warning saying:</p>
<pre><code> comparing values of types Unit and Null using `!=' will always yield true
[warn] while( (aLine = reader.readNext()) != null ) {
</code></pre>
<p>How should I do the while loop?</p> | 3,062,939 | 5 | 0 | null | 2010-06-17 14:55:26.34 UTC | 9 | 2010-06-25 11:02:34.99 UTC | null | null | null | null | 115,988 | null | 1 | 33 | scala|while-loop | 19,615 | <p>In your case (line = reader.readNext()) is a functional literal that returns type Unit. You may rewrite the code as follows:</p>
<pre><code>while( {line = reader.readNext(); line!= null} ) { .... }
</code></pre> |
2,925,944 | Can I use HTML5 Now to create a website | <p>After all the latest news and talk about HTML5, I would like to know whether I can use HTML5 to create a website as of now. I mean, some features are supported by few browsers, while few features are not yet supported. So is it possible to create a full-fledged website at the current state?</p> | 2,925,966 | 6 | 0 | null | 2010-05-28 00:26:20.033 UTC | 9 | 2010-06-02 13:21:51.007 UTC | 2010-05-28 00:27:29.457 UTC | null | 37,971 | null | 88,898 | null | 1 | 9 | css|html | 1,360 | <p>I built a site in 100% semantic HTML5, tested only in Firefox, Chrome and Safari. When I was done, I added these three scripts and loaded it up in IE6 and IE7 - <strike>looked pixel-perfect!</strike> ok, perfect is an exaggeration. It doesn't look exactly the same, but it looks fine e.g. no broken layout parts, everything is legible and functional. </p>
<ul>
<li><a href="http://code.google.com/p/html5shiv/" rel="nofollow noreferrer"><strong>HTML5 Shiv script</strong></a> - Add HTML5 element support</li>
<li><a href="http://code.google.com/p/explorercanvas/" rel="nofollow noreferrer"><strong>ExplorerCanvas</strong></a> - Add <code><canvas></code> support</li>
<li><a href="http://www.twinhelix.com/css/iepngfix/" rel="nofollow noreferrer"><strong>IE PNG Fix (IE6 only)</strong></a> - Add transparent PNG support</li>
</ul>
<p>YMMV but these will almost certainly get you at least 90% of the way.</p> |
3,135,524 | Comparing passwords with crypt() in PHP | <p>I need to get the basics of this function. The php.net documentation states, for the blowfish algorithm, that: </p>
<blockquote>
<p>Blowfish hashing with a salt as follows: "$2a$", a two digit cost parameter, "$", and 22 base 64 digits from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt <em>will cause crypt() to return a zero-length string</em></p>
</blockquote>
<p>So this, by definition, should not work:</p>
<pre><code>echo crypt('rasmuslerdorf', '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringforsalt$');
</code></pre>
<p>However, it spits out:</p>
<pre><code>$2a$07$usesomadasdsadsadsadaeMTUHlZEItvtV00u0.kb7qhDlC0Kou9e
</code></pre>
<p>Where it seems that crypt() has cut the salt itself to a length of 22. Could somebody please explain this?</p>
<p>Another aspect of this function I can't get my head around is when they use crypt() to compare passwords. <a href="http://php.net/manual/en/function.crypt.php" rel="noreferrer">http://php.net/manual/en/function.crypt.php</a> (look at ex. #1). Does this mean that if I use the same salt for all encrypting all my passwords, I have to crypt it first? ie:</p>
<pre><code>$salt = "usesomadasdsadsadsadae";
$salt_crypt = crypt($salt);
if (crypt($user_input, $salt) == $password) {
// FAIL WONT WORK
}
if (crypt($user_input, $salt_crypt) == $password) {
// I HAVE TO DO THIS?
}
</code></pre>
<p>Thanks for your time</p> | 3,136,186 | 6 | 1 | null | 2010-06-28 19:31:30.913 UTC | 10 | 2014-08-20 10:28:41.11 UTC | null | null | null | null | 281,434 | null | 1 | 17 | php|encryption|bcrypt | 36,547 | <p>Following code example may answer your questions.</p>
<p>To generate hashed password using Blowfish, you first need to generate a salt, which starts with $2a$ followed by iteration count and 22 characters of Base64 string. </p>
<pre><code>$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';
$digest = crypt('rasmuslerdorf', $salt);
</code></pre>
<p>Store the whole $digest in database, it has both the salt and digest.</p>
<p>When comparing password, just do this,</p>
<pre><code> if (crypt($user_input, $digest) == $digest)
</code></pre>
<p>You are reusing the digest as salt. crypt knows how long is the salt from the algorithm identifier.</p> |
2,382,464 | Win32: full-screen and hiding taskbar | <p>I have a window, which I <code>SetWindowPos(window, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED);</code></p>
<p>It covers the whole screen, ok, but it takes a while (0.5 sec) to cover the taskbar as well.</p>
<p>Is there a way to come over the taskbar immediately? I found that setting <code>HWND_TOPMOST</code> does it immediately, but it stays above all the other windows, even if I switch the app - this is something I don't want. Also, if I first hide the window and then show it, it somehow forces the window to redraw and covers the taskbar immediately, but it flickers (because of the hiding). Is there another way?</p> | 5,299,718 | 6 | 0 | null | 2010-03-04 20:23:38.503 UTC | 31 | 2020-07-22 22:08:18.09 UTC | null | null | null | null | 269,886 | null | 1 | 38 | winapi|fullscreen|taskbar | 63,515 | <p><strong>Edit 2</strong>. There is even a better way for doing fullscreen, the chromium way, source taken from here:</p>
<p><a href="http://src.chromium.org/viewvc/chrome/trunk/src/ui/views/win/fullscreen_handler.cc?revision=HEAD&view=markup" rel="noreferrer">http://src.chromium.org/viewvc/chrome/trunk/src/ui/views/win/fullscreen_handler.cc?revision=HEAD&view=markup</a></p>
<pre><code>void FullscreenHandler::SetFullscreenImpl(bool fullscreen, bool for_metro) {
ScopedFullscreenVisibility visibility(hwnd_);
// Save current window state if not already fullscreen.
if (!fullscreen_) {
// Save current window information. We force the window into restored mode
// before going fullscreen because Windows doesn't seem to hide the
// taskbar if the window is in the maximized state.
saved_window_info_.maximized = !!::IsZoomed(hwnd_);
if (saved_window_info_.maximized)
::SendMessage(hwnd_, WM_SYSCOMMAND, SC_RESTORE, 0);
saved_window_info_.style = GetWindowLong(hwnd_, GWL_STYLE);
saved_window_info_.ex_style = GetWindowLong(hwnd_, GWL_EXSTYLE);
GetWindowRect(hwnd_, &saved_window_info_.window_rect);
}
fullscreen_ = fullscreen;
if (fullscreen_) {
// Set new window style and size.
SetWindowLong(hwnd_, GWL_STYLE,
saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME));
SetWindowLong(hwnd_, GWL_EXSTYLE,
saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME |
WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));
// On expand, if we're given a window_rect, grow to it, otherwise do
// not resize.
if (!for_metro) {
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST),
&monitor_info);
gfx::Rect window_rect(monitor_info.rcMonitor);
SetWindowPos(hwnd_, NULL, window_rect.x(), window_rect.y(),
window_rect.width(), window_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
} else {
// Reset original window style and size. The multiple window size/moves
// here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be
// repainted. Better-looking methods welcome.
SetWindowLong(hwnd_, GWL_STYLE, saved_window_info_.style);
SetWindowLong(hwnd_, GWL_EXSTYLE, saved_window_info_.ex_style);
if (!for_metro) {
// On restore, resize to the previous saved rect size.
gfx::Rect new_rect(saved_window_info_.window_rect);
SetWindowPos(hwnd_, NULL, new_rect.x(), new_rect.y(),
new_rect.width(), new_rect.height(),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
if (saved_window_info_.maximized)
::SendMessage(hwnd_, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
}
}
</code></pre>
<p><strong>Edit</strong>.
It is probably better to create a fullscreen window as BrendanMcK pointed it out in a comment to this answer, see this link: <a href="http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx" rel="noreferrer">http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx</a> ("How do I cover the taskbar with a fullscreen window?")</p>
<p>The new code using the link above would be:</p>
<pre><code>HWND CreateFullscreenWindow(HWND hwnd)
{
HMONITOR hmon = MonitorFromWindow(hwnd,
MONITOR_DEFAULTTONEAREST);
MONITORINFO mi = { sizeof(mi) };
if (!GetMonitorInfo(hmon, &mi)) return NULL;
return CreateWindow(TEXT("static"),
TEXT("something interesting might go here"),
WS_POPUP | WS_VISIBLE,
mi.rcMonitor.left,
mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
hwnd, NULL, g_hinst, 0);
}
</code></pre>
<hr>
<p><strong>Old answer below - do not use it, stays only for the record on how NOT to do this.</strong></p>
<p>You have to hide taskbar and menubar to see fullscreen immediately.</p>
<p>Here is the code (uses WTL), call SetFullScreen(true) to go into full screen mode:</p>
<pre><code>template <class T, bool t_bHasSip = true>
class CFullScreenFrame
{
public:
bool m_fullscreen;
LONG m_windowstyles;
WINDOWPLACEMENT m_windowplacement;
CFullScreenFrame()
:
m_fullscreen(false),
m_windowstyles(0)
{ }
void SetFullScreen(bool fullscreen)
{
ShowTaskBar(!fullscreen);
T* pT = static_cast<T*>(this);
if (fullscreen) {
if (!m_fullscreen) {
m_windowstyles = pT->GetWindowLongW(GWL_STYLE);
pT->GetWindowPlacement(&m_windowplacement);
}
}
// SM_CXSCREEN gives primary monitor, for multiple monitors use SM_CXVIRTUALSCREEN.
RECT fullrect = { 0 };
SetRect(&fullrect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
WINDOWPLACEMENT newplacement = m_windowplacement;
newplacement.showCmd = SW_SHOWNORMAL;
newplacement.rcNormalPosition = fullrect;
if (fullscreen) {
pT->SetWindowPlacement(&newplacement);
pT->SetWindowLongW(GWL_STYLE, WS_VISIBLE);
pT->UpdateWindow();
} else {
if (m_fullscreen) {
pT->SetWindowPlacement(&m_windowplacement);
pT->SetWindowLongW(GWL_STYLE, m_windowstyles);
pT->UpdateWindow();
}
}
m_fullscreen = fullscreen;
}
void ShowTaskBar(bool show)
{
HWND taskbar = FindWindow(_T("Shell_TrayWnd"), NULL);
HWND start = FindWindow(_T("Button"), NULL);
if (taskbar != NULL) {
ShowWindow(taskbar, show ? SW_SHOW : SW_HIDE);
UpdateWindow(taskbar);
}
if (start != NULL) {
// Vista
ShowWindow(start, show ? SW_SHOW : SW_HIDE);
UpdateWindow(start);
}
}
};
</code></pre>
<p>You also have to add some code to WM_CLOSE message:</p>
<pre><code>case WM_CLOSE:
ShowTaskBar(true);
</code></pre>
<p>There is one caveat with this solution, if your application crashes or is killed through task manager, then user losses taskbar on his system permanently! (unless he runs your application again, goes into fullscreen and exits, then he will see the taskbar again).</p>
<p>Earlier in my answer I pointed to "atlwince.h" but that function worked only on Windows CE, the one I pasted above works fine with XP, Vista and 7.</p> |
2,643,798 | how to access the $(this) inside ajax success callback function | <p>It seems that i cannot access $(this) inside jquery ajax success function. please see below code.</p>
<pre><code> $.ajax({
type: 'post',
url: '<?php echo site_url('user/accept_deny_friendship_request')?>',
data: 'action='+$action+'&user_id='+$user_id,
success: function(response){
//cannot access $(this) here $(this).parent().remove();
}
});
</code></pre> | 2,643,819 | 6 | 0 | null | 2010-04-15 08:38:28.367 UTC | 11 | 2021-12-17 00:27:05.72 UTC | 2021-05-28 06:10:15.56 UTC | null | 266,598 | null | 266,598 | null | 1 | 38 | jquery|ajax | 29,153 | <p>What should <code>$(this)</code> be? If you have a reference to it outside that function, you can just store it into a variable.</p>
<pre><code>$('#someLink').click(function() {
var $t = $(this);
$.ajax( ... , function() {
$t.parent().remove();
});
}
</code></pre> |
2,969,222 | Make GNU make use a different compiler | <p>How can I make GNU Make use a different compiler without manually editing the makefile?</p> | 2,969,244 | 6 | 0 | null | 2010-06-03 19:44:45.863 UTC | 9 | 2022-06-03 13:50:40.697 UTC | null | null | null | null | 105,760 | null | 1 | 59 | c++|c|makefile | 74,463 | <p>You should be able to do something like this:</p>
<pre><code>make CC=my_compiler
</code></pre>
<p>This is assuming whoever wrote the Makefile used the variable CC.</p> |
2,883,355 | How to render PDF in Android | <p>In my application I will receive a byte stream and convert it to a pdf file in the phone memory. How do I render that to a pdf? And show it on an activity?</p> | 2,885,744 | 6 | 1 | null | 2010-05-21 15:21:00.74 UTC | 46 | 2020-07-12 13:31:11.56 UTC | 2010-10-11 11:34:10.473 UTC | null | 114,066 | null | 279,560 | null | 1 | 83 | java|android|pdf | 86,650 | <p>Some phones (like the Nexus One) come with a version of <a href="http://www.quickoffice.com/quickoffice_android/" rel="noreferrer">Quickoffice</a> pre-installed so it may be as easy as sending the appropriate Intent once you've saved the file to the SD card.</p>
<pre><code>public class OpenPdf extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File("/sdcard/example.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
</code></pre> |
2,963,819 | Why use your application-level cache if database already provides caching? | <p>Modern database provide caching support. Most of the ORM frameworks cache retrieved data too. Why this duplication is necessary?</p> | 2,963,850 | 9 | 1 | null | 2010-06-03 06:49:17.923 UTC | 13 | 2021-10-12 14:00:27.163 UTC | 2010-06-03 07:09:55.12 UTC | null | 3,966 | null | 315,129 | null | 1 | 29 | java|database|hibernate|caching|second-level-cache | 11,012 | <p>Because to get the data from the database's cache, you still have to:</p>
<ol>
<li>Generate the SQL from the ORM's "native" query format</li>
<li>Do a network round-trip to the database server</li>
<li>Parse the SQL</li>
<li>Fetch the data from the cache</li>
<li>Serialise the data to the database's over-the-wire format</li>
<li>Deserialize the data into the database client library's format</li>
<li>Convert the database client librarie's format into language-level objects (i.e. a collection of whatevers)</li>
</ol>
<p>By caching at the application level, you don't have to do any of that. Typically, it's a simple lookup of an in-memory hashtable. Sometimes (if caching with memcache) there's still a network round-trip, but all of the other stuff no longer happens.</p> |
2,454,956 | Create normal zip file programmatically | <p>I have seen many tutorials on how to compress a single file in c#. But I need to be able to create a normal *.zip file out of more than just one file. Is there anything in .NET that can do this? What would you suggest (baring in mind I'm under strict rules and cannot use other libraries)</p>
<p>Thank you</p> | 2,454,987 | 12 | 1 | null | 2010-03-16 14:07:29.11 UTC | 13 | 2022-06-13 17:43:46.047 UTC | null | null | null | anon271334 | null | null | 1 | 51 | c#|.net|winforms|compression|zip | 133,077 | <p>Edit: if you're using .Net 4.5 or later this is <a href="http://stackoverflow.com/a/19613011/444991">built-in to the framework</a></p>
<p>For earlier versions or for more control you can use Windows' shell functions as outlined <a href="http://www.codeproject.com/KB/cs/compresswithwinshellapics.aspx" rel="noreferrer">here on CodeProject by Gerald Gibson Jr</a>.</p>
<p>I have copied the article text below as written (original license: <a href="https://creativecommons.org/licenses/publicdomain/" rel="noreferrer">public domain</a>)</p>
<blockquote>
<h2>Compress Zip files with Windows Shell API and C</h2>
<p><a href="https://i.stack.imgur.com/9JPIg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9JPIg.png" alt="enter image description here" /></a></p>
<h3>Introduction</h3>
<p>This is a follow up article to the one that I wrote about decompressing Zip files. With this code you can use the Windows Shell API in C# to compress Zip files and do so without having to show the Copy Progress window shown above. Normally when you use the Shell API to compress a Zip file, it will show a Copy Progress window even when you set the options to tell Windows not to show it. To get around this, you move the Shell API code to a separate executable and then launch that executable using the .NET Process class being sure to set the process window style to 'Hidden'.</p>
<h3>Background</h3>
<p>Ever needed to compress Zip files and needed a better Zip than what comes with many of the free compression libraries out there? I.e. you needed to compress folders and subfolders as well as files. Windows Zipping can compress more than just individual files. All you need is a way to programmatically get Windows to silently compress these Zip files. Of course you could spend $300 on one of the commercial Zip components, but it's hard to beat free if all you need is to compress folder hierarchies.</p>
<h3>Using the code</h3>
<p>The following code shows how to use the Windows Shell API to compress a Zip file. First you create an empty Zip file. To do this create a properly constructed byte array and then save that array as a file with a '.zip' extension. How did I know what bytes to put into the array? Well I just used Windows to create a Zip file with a single file compressed inside. Then I opened the Zip with Windows and deleted the compressed file. That left me with an empty Zip. Next I opened the empty Zip file in a hex editor (Visual Studio) and looked at the hex byte values and converted them to decimal with Windows Calc and copied those decimal values into my byte array code. The source folder points to a folder you want to compress. The destination folder points to the empty Zip file you just created. This code as is will compress the Zip file, however it will also show the Copy Progress window. To make this code work, you will also need to set a reference to a COM library. In the References window, go to the COM tab and select the library labeled 'Microsoft Shell Controls and Automation'.</p>
</blockquote>
<pre><code>//Create an empty zip file
byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(args[1]);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;
//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
Shell32.Folder DestFlder = sc.NameSpace(args[1]);
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);
//Ziping a file using the Windows Shell API
//creates another thread where the zipping is executed.
//This means that it is possible that this console app
//would end before the zipping thread
//starts to execute which would cause the zip to never
//occur and you will end up with just
//an empty zip file. So wait a second and give
//the zipping thread time to get started
System.Threading.Thread.Sleep(1000);
</code></pre>
<blockquote>
<p>The sample solution included with this article shows how to put this code into a console application and then launch this console app to compress the Zip without showing the Copy Progress window.</p>
<p>The code below shows a button click event handler that contains the code used to launch the console application so that there is no UI during the compress:</p>
</blockquote>
<pre><code>private void btnUnzip_Click(object sender, System.EventArgs e)
{
//Test to see if the user entered a zip file name
if(txtZipFileName.Text.Trim() == "")
{
MessageBox.Show("You must enter what" +
" you want the name of the zip file to be");
//Change the background color to cue the user to what needs fixed
txtZipFileName.BackColor = Color.Yellow;
return;
}
else
{
//Reset the background color
txtZipFileName.BackColor = Color.White;
}
//Launch the zip.exe console app to do the actual zipping
System.Diagnostics.ProcessStartInfo i =
new System.Diagnostics.ProcessStartInfo(
AppDomain.CurrentDomain.BaseDirectory + "zip.exe");
i.CreateNoWindow = true;
string args = "";
if(txtSource.Text.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += "\"" + txtSource.Text + "\"";
}
else
{
args += txtSource.Text;
}
string dest = txtDestination.Text;
if(dest.EndsWith(@"\") == false)
{
dest += @"\";
}
//Make sure the zip file name ends with a zip extension
if(txtZipFileName.Text.ToUpper().EndsWith(".ZIP") == false)
{
txtZipFileName.Text += ".zip";
}
dest += txtZipFileName.Text;
if(dest.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += " " + "\"" + dest + "\"";
}
else
{
args += " " + dest;
}
i.Arguments = args;
//Mark the process window as hidden so
//that the progress copy window doesn't show
i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(i);
p.WaitForExit();
MessageBox.Show("Complete");
}
</code></pre> |
25,201,430 | De-activate a maven profile from command line | <p>I have a profile <strong>activated by default</strong> in my maven setting file <strong>~/.m2/settings.xml</strong>.</p>
<p>Is it possible to deactivate it from the command line by doing something like this:</p>
<pre><code>mvn -P!profileActivatedByDefault
</code></pre> | 25,201,551 | 3 | 0 | null | 2014-08-08 10:30:41.423 UTC | 15 | 2020-12-30 06:52:48.64 UTC | 2014-08-08 10:35:22.557 UTC | null | 2,316,112 | null | 3,463,201 | null | 1 | 92 | java|maven|command-line-interface | 40,921 | <p>Yes indeed, you have the right way.
From <a href="http://maven.apache.org/guides/introduction/introduction-to-profiles.html#Deactivating_a_profile" rel="noreferrer">maven profiles user guide</a></p>
<blockquote>
<p><strong>Deactivating a profile</strong></p>
<p>Starting with Maven 2.0.10, one or more profiles can be deactivated using the command line by prefixing their identifier with either the character '!' or '-' as shown below:</p>
<p><code>mvn groupId:artifactId:goal -P !profile-1,!profile-2</code></p>
<p>This can be used to deactivate profiles marked as activeByDefault or profiles that would otherwise be activated through their activation config.</p>
</blockquote>
<p>As noted by @Calfater in the comments, the exclamation mark needs to be escaped in most shells (bash, zsh, and others on Linux and MacOS), though not on the windows command line.</p>
<p>The escape mechanisms are shell-dependant, but usually you can do :</p>
<pre><code>mvn groupId:artifactId:goal -P \!profile-1
</code></pre>
<p>Or</p>
<pre><code>mvn groupId:artifactId:goal -P '!profile-1'
</code></pre>
<p>Or, as <a href="https://stackoverflow.com/a/30129339/537554">Shaun Morris suggested below</a>, use <code>-</code> instead of <code>!</code>, but <strong>without whitespace</strong> between <code>-P</code> and the profiles:</p>
<pre><code>mvn groupId:artifactId:goal -P-profile-1,-profile2
</code></pre> |
33,850,804 | In Git how can you check which repo in Github you are pushing to from the command line? | <p>I have several projects I am working on. I am constantly pulling and pushing. Recently I made some changes to one of my files, added and committed and decided to push my project A, however it pushed into my Github Project B. I then did git pull for kicks and it this happened.</p>
<ul>
<li>branch master -> FETCH_HEAD
Already up-to-date.</li>
</ul>
<p>It did not pull none of my files from Project B. I then did git status and it showed every single file/folders in my directory as needing to be committed. How would I know which "init" I am on? How can I switch out of this state and how can I disregard these blind commits without losing my files?</p> | 33,850,834 | 3 | 1 | null | 2015-11-22 01:56:54.633 UTC | 9 | 2021-05-29 03:56:54.993 UTC | null | null | null | null | 5,590,605 | null | 1 | 47 | git|github|git-bash | 145,365 | <p>I think you need to reconfig git <code>remote</code></p>
<p>type <code>git remote -v</code> and see if there's a mismatch or not.<br>
If there is, follow this instruction from github: <a href="https://help.github.com/articles/changing-a-remote-s-url/">https://help.github.com/articles/changing-a-remote-s-url/</a></p> |
45,419,702 | Laravel 5.2: The Process class relies on proc_open, which is not available on your PHP installation | <p>I use cron job to do some CRUD operation using laravel Task Scheduling. On localhost and on my Share-Hosting server it worked fine for months until recently I keep getting this error when I run cron job on my Share-Hosting server. I did not make any changes to the code on my Share-Hosting server.</p>
<pre><code>[2017-07-14 09:16:02] production.ERROR: exception 'Symfony\Component\Process\Exception\RuntimeException' with message 'The Process class relies on proc_open, which is not available on your PHP installation.' in /home/xxx/xx/vendor/symfony/process/Process.php:144
Stack trace:
</code></pre>
<p>But on localhost it works fine. Based on my finding online I have tried the following.</p>
<ol>
<li>Contacted my hosting company to remove proc_open form disable PHP functions. </li>
<li>Hosting company provided custom php.ini file. I remove all disable_functions</li>
<li>Share-Hosting Server was restarted and cache was cleared</li>
</ol>
<p><strong>None of this fixed the issue</strong>. I am not sure of what next to try because the same project works fine on different Share-Hosting Server.</p> | 45,419,955 | 5 | 0 | null | 2017-07-31 15:21:41.37 UTC | 5 | 2021-11-19 17:11:40.863 UTC | 2020-03-05 14:29:24.26 UTC | null | 6,569,224 | null | 3,904,066 | null | 1 | 15 | php|laravel|cron|cpanel | 40,687 | <p>After many weeks of trying to resolve this error. The following fixes worked</p>
<ol>
<li>Upgrade project from Laravel 5.2 to 5.4</li>
<li>On CPanel using "Select Php version" set <strong>PHP version to 7</strong></li>
<li>Or on CPanel using "MultiPHP Manager" set PHP version to <strong><em>ea-php70</em></strong></li>
</ol>
<p>Now, cron job runs smoothly. I hope this helps someone.</p> |
42,521,005 | How the number of parameters associated with BatchNormalization layer is 2048? | <p>I have the following code.</p>
<pre><code>x = keras.layers.Input(batch_shape = (None, 4096))
hidden = keras.layers.Dense(512, activation = 'relu')(x)
hidden = keras.layers.BatchNormalization()(hidden)
hidden = keras.layers.Dropout(0.5)(hidden)
predictions = keras.layers.Dense(80, activation = 'sigmoid')(hidden)
mlp_model = keras.models.Model(input = [x], output = [predictions])
mlp_model.summary()
</code></pre>
<p>And this is the model summary:</p>
<pre><code>____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_3 (InputLayer) (None, 4096) 0
____________________________________________________________________________________________________
dense_1 (Dense) (None, 512) 2097664 input_3[0][0]
____________________________________________________________________________________________________
batchnormalization_1 (BatchNorma (None, 512) 2048 dense_1[0][0]
____________________________________________________________________________________________________
dropout_1 (Dropout) (None, 512) 0 batchnormalization_1[0][0]
____________________________________________________________________________________________________
dense_2 (Dense) (None, 80) 41040 dropout_1[0][0]
====================================================================================================
Total params: 2,140,752
Trainable params: 2,139,728
Non-trainable params: 1,024
____________________________________________________________________________________________________
</code></pre>
<p>The size of the input for the BatchNormalization (BN) layer is 512. According to <a href="https://keras.io/layers/normalization/" rel="noreferrer">Keras documentation</a>, shape of the output for BN layer is same as input which is 512.</p>
<p>Then how the number of parameters associated with BN layer is 2048?</p> | 42,524,528 | 2 | 0 | null | 2017-03-01 00:09:45.373 UTC | 14 | 2019-08-03 16:06:46.573 UTC | null | null | null | null | 5,352,399 | null | 1 | 29 | keras|batch-normalization | 17,052 | <p>The batch normalization in Keras implements <a href="http://jmlr.org/proceedings/papers/v37/ioffe15.pdf" rel="noreferrer">this paper</a>. </p>
<p>As you can read there, in order to make the batch normalization work during training, they need to keep track of the distributions of each normalized dimensions. To do so, since you are in <code>mode=0</code>by default, they compute 4 parameters per feature on the previous layer. Those parameters are making sure that you properly propagate and backpropagate the information. </p>
<p>So <code>4*512 = 2048</code>, this should answer your question. </p> |
42,510,921 | Convert Unix Timestamp to Carbon Object | <p>I have unix timestamp in table, wants to show to user using Carbon. How can I achieve ?</p>
<p>e.g.
<pre>
<b>1487663764.99256</b></pre> To <br/></p>
<pre><b>2017-02-24 23:23:14.654621</b>
</pre> | 42,511,044 | 3 | 0 | null | 2017-02-28 14:08:27.713 UTC | 11 | 2021-11-18 21:34:45.567 UTC | 2017-09-12 09:11:19.68 UTC | null | 5,808,894 | null | 1,578,380 | null | 1 | 98 | laravel|php-carbon | 107,724 | <p>Did you check the carbon docs? I think this is what youre looking for:</p>
<pre><code>Carbon::createFromTimestamp(-1)->toDateTimeString();
</code></pre>
<p>Checkout <a href="http://carbon.nesbot.com/docs/#api-instantiation" rel="noreferrer">http://carbon.nesbot.com/docs/#api-instantiation</a></p> |
40,126,729 | Angular 2 Testing - Async function call - when to use | <p>When do you use the async function in the <strong>TestBed</strong> when testing in Angular 2?</p>
<p>When do you use this?</p>
<pre><code> beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
});
</code></pre>
<p>And when do you use this?</p>
<pre><code>beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
}));
</code></pre>
<p>Can anyone enlighten me on this ?</p> | 40,127,164 | 2 | 0 | null | 2016-10-19 09:01:15.99 UTC | 16 | 2020-02-26 22:08:03.207 UTC | 2018-10-18 01:37:07.22 UTC | null | 5,377,805 | null | 5,459,440 | null | 1 | 96 | angular|unit-testing|karma-jasmine|angular2-testing|angular-test | 36,767 | <p><code>async</code> will not allow the next test to start until the <code>async</code> finishes all its tasks. What <code>async</code> does is wrap the callback in a Zone, where all asynchronous tasks (e.g. <code>setTimeout</code>) are tracked. Once all the asynchronous tasks are complete, then the <code>async</code> completes.</p>
<p>If you have ever worked with Jasmine outside out Angular, you may have seen <code>done</code> being passed to the callback</p>
<pre><code>it('..', function(done) {
someAsyncAction().then(() => {
expect(something).toBe(something);
done();
});
});
</code></pre>
<p>Here, this is native Jasmine, where we tell Jasmine that this test should delay completion until we call <code>done()</code>. If we didn't call <code>done()</code> and instead did this:</p>
<pre><code>it('..', function() {
someAsyncAction().then(() => {
expect(something).toBe(something);
});
});
</code></pre>
<p>The test would complete even before the expectation, because the promise resolves <em>after</em> the test is finished executing the synchronous tasks.</p>
<p>With Angular (in a Jasmine environment), Angular will actually call <code>done</code> behind the scenes when we use <code>async</code>. It will keep track of all the asynchronous tasks in the Zone, and when they are all finished, <code>done</code> will be called behind the scenes.</p>
<p>In your particular case with the <code>TestBed</code> configuration, you would use this generally when you want to <code>compileComponents</code>. I rarely run into a situation in which I would have to call it otherwise</p>
<pre><code>beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponent().then(() => {
fixture = TestBed.createComponent(TestComponent);
});
}));
</code></pre>
<p>When testing a component that uses <code>templateUrl</code> (if you are not using webpack), then Angular needs to make an XHR request to get the template, so the compilation of the component would be asynchronous. So we should wait until it resolves before continuing testing.</p> |
10,735,922 | How to stop a requestAnimationFrame recursion/loop? | <p>I'm using Three.js with the WebGL renderer to make a game which fullscreens when a <code>play</code> link is clicked. For animation, I use <code>requestAnimationFrame</code>.</p>
<p>I initiate it like this:</p>
<pre><code>self.animate = function()
{
self.camera.lookAt(self.scene.position);
self.renderer.render(self.scene, self.camera);
if (self.willAnimate)
window.requestAnimationFrame(self.animate, self.renderer.domElement);
}
self.startAnimating = function()
{
self.willAnimate = true;
self.animate();
}
self.stopAnimating = function()
{
self.willAnimate = false;
}
</code></pre>
<p>When I want to, I call the <code>startAnimating</code> method, and yes, it does work as intended. But, when I call the <code>stopAnimating</code> function, things break! There are no reported errors, though...</p>
<p>The setup is basically like this:</p>
<ul>
<li>There is a <code>play</code> link on the page</li>
<li>Once the user clicks the link, a renderer's <code>domElement</code> should fullscreen, and it does</li>
<li>The <code>startAnimating</code> method is called and the renderer starts rendering stuff</li>
<li>Once escape is clicked, I register an <code>fullscreenchange</code> event and execute the <code>stopAnimating</code> method</li>
<li>The page tries to exit fullscreen, it does, but the entire document is completely blank</li>
</ul>
<p>I'm pretty sure my other code is OK, and that I'm somehow stopping <code>requestAnimationFrame</code> in a wrong way. My explanation probably sucked, so I uploaded the code to my website, you can see it happening here: <a href="http://banehq.com/Placeholdername/main.html">http://banehq.com/Placeholdername/main.html</a>.</p>
<p>Here is the version where I don't try to call the animation methods, and fullscreening in and out works: <a href="http://banehq.com/Correct/Placeholdername/main.html">http://banehq.com/Correct/Placeholdername/main.html</a>.</p>
<p>Once <code>play</code> is clicked the first time, the game initializes and it's <code>start</code> method is executed. Once the fullscreen exits, the game's <code>stop</code> method is executed. Every other time that <code>play</code> has been clicked, the game only executes it's <code>start</code> method, because there is no need for it to be initialized again.</p>
<p>Here's how it looks:</p>
<pre><code>var playLinkHasBeenClicked = function()
{
if (!started)
{
started = true;
game = new Game(container); //"container" is an empty div
}
game.start();
}
</code></pre>
<p>And here's how the <code>start</code> and <code>stop</code> methods look like:</p>
<pre><code>self.start = function()
{
self.container.appendChild(game.renderer.domElement); //Add the renderer's domElement to an empty div
THREEx.FullScreen.request(self.container); //Request fullscreen on the div
self.renderer.setSize(screen.width, screen.height); //Adjust screensize
self.startAnimating();
}
self.stop = function()
{
self.container.removeChild(game.renderer.domElement); //Remove the renderer from the div
self.renderer.setSize(0, 0); //I guess this isn't needed, but welp
self.stopAnimating();
}
</code></pre>
<p>The only difference between this and the working version is that <code>startAnimating</code> and <code>stopAnimating</code> method <strong>calls</strong> in <code>start</code> and <code>stop</code> methods are commented out.</p> | 10,745,418 | 6 | 0 | null | 2012-05-24 10:44:37.42 UTC | 20 | 2021-08-15 03:35:00.68 UTC | null | null | null | null | 924,313 | null | 1 | 76 | javascript|html|fullscreen|webgl|three.js | 88,980 | <p>So, after doing some more testing, I've found out that it was, indeed, my other code that posed a problem, not the animation stopping (it was a simple recursion after all). The problem was in dynamically adding and removing the renderer's domElement from the page. After I've stopped doing that, for there was really no reason to do so, and included it once where the initialization was happening, everything started working fine.</p> |
5,974,595 | Download all the links(related documents) on a webpage using Python | <p>I have to download a lot of documents from a webpage. They are wmv files, PDF, BMP etc. Of course, all of them have links to them. So each time, I have to RMC a file, select 'Save Link As' Then save then as type All Files. Is it possible to do this in Python? I search the SO DB and folks have answered question of how to get the links from the webpage. I want to download the actual files. Thanks in advance. (This is not a HW question :)).</p> | 5,976,423 | 2 | 0 | null | 2011-05-12 07:17:06.503 UTC | 11 | 2017-03-04 05:32:14.507 UTC | null | null | null | null | 418,832 | null | 1 | 13 | python | 27,799 | <p>Here is an example of how you could download some chosen files from <a href="http://pypi.python.org/pypi/xlwt" rel="noreferrer">http://pypi.python.org/pypi/xlwt</a></p>
<p>you will need to install mechanize first: <a href="http://wwwsearch.sourceforge.net/mechanize/download.html" rel="noreferrer">http://wwwsearch.sourceforge.net/mechanize/download.html</a></p>
<pre><code>import mechanize
from time import sleep
#Make a Browser (think of this as chrome or firefox etc)
br = mechanize.Browser()
#visit http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/
#for more ways to set up your br browser object e.g. so it look like mozilla
#and if you need to fill out forms with passwords.
# Open your site
br.open('http://pypi.python.org/pypi/xlwt')
f=open("source.html","w")
f.write(br.response().read()) #can be helpful for debugging maybe
filetypes=[".zip",".exe",".tar.gz"] #you will need to do some kind of pattern matching on your files
myfiles=[]
for l in br.links(): #you can also iterate through br.forms() to print forms on the page!
for t in filetypes:
if t in str(l): #check if this link has the file extension we want (you may choose to use reg expressions or something)
myfiles.append(l)
def downloadlink(l):
f=open(l.text,"w") #perhaps you should open in a better way & ensure that file doesn't already exist.
br.click_link(l)
f.write(br.response().read())
print l.text," has been downloaded"
#br.back()
for l in myfiles:
sleep(1) #throttle so you dont hammer the site
downloadlink(l)
</code></pre>
<p>Note: In some cases you may wish to replace <code>br.click_link(l)</code> with <code>br.follow_link(l)</code>. The difference is that click_link returns a Request object whereas follow_link will directly open the link. See <a href="https://stackoverflow.com/questions/13204781/mechanize-difference-between-br-click-link-and-br-follow-link">Mechanize difference between br.click_link() and br.follow_link()</a></p> |
60,676,210 | How to find user by their id in discord.js | <p>I want my bot to be able to give specific roles to specific users declared with their id.
I tried:</p>
<pre class="lang-js prettyprint-override"><code>const user = bot.users.cache.get(args[2]);
user.roles.add("[role ID]");
</code></pre> | 60,676,801 | 2 | 0 | null | 2020-03-13 19:26:52.557 UTC | 0 | 2022-05-21 16:40:34.257 UTC | 2022-05-01 17:33:41.77 UTC | null | 4,561,047 | null | 12,618,447 | null | 1 | 7 | discord.js | 44,686 | <p>The problem you have here is you are getting a <a href="https://discord.js.org/#/docs/main/stable/class/User" rel="noreferrer">User</a> object instead of a <a href="https://discord.js.org/#/docs/main/stable/class/GuildMember" rel="noreferrer">GuildMember</a> object. Users are not associated with a guild and therefore cannot have roles. You typically want to use a user when it doesn't involve guild specific actions (like Direct Messaging).</p>
<p>You cannot get a Member from the Client object directly, however you can get <code>Client.guilds.cache</code> and then retrieve the guild, followed by the member from the Guild object using <code>Guild.members.cache</code>.</p>
<p>However, most implementations of permission systems like this require some higher permission user to run a command to grant a permission to a new user. This means you can use the <code>Message.guild.members.cache.get()</code> straight from the Message object that invoked your bot command.</p> |
19,510,220 | Single Session Login in Laravel | <p>I'm trying to implement a user policy whereby only one user can login at a time. I'm trying to build this on top of Laravel's Auth driver.</p>
<p>I've thought of using the Session driver to store the sessions in the database and make the keys constant for each username. This is probably a terrible implementation because of session fixation.</p>
<p>What would the implementation be like? What methods in the Auth driver should I be editing? Where would the common session key be stored?</p> | 19,510,428 | 6 | 0 | null | 2013-10-22 06:10:36.583 UTC | 10 | 2020-11-02 00:58:33.337 UTC | null | null | null | null | 805,792 | null | 1 | 19 | php|security|authentication|laravel | 30,425 | <p>I recently did this. </p>
<p>My solution was to set the session value when a user logs in. Then I had a small class checking if the session ID stored is the same as the current user who is logged in. </p>
<p>If the user logs in from somewhere else the session ID in the DB will update and the "older" user will be logged out. </p>
<p>I didn't alter the Auth driver or anything, just put it on top when the user logs in. Below happens when login is successful:</p>
<pre><code>$user->last_session = session_id();
$user->save();
</code></pre>
<p>To check if the session is valid I used below</p>
<pre><code>if(session_id() != Auth::user()->last_session){
Auth::logout();
return true;
}
</code></pre>
<p>As you can see I added a column in the users table called <code>last_session</code></p> |
32,986,228 | Difference between using requests.get() and requests.session().get()? | <p>Sometimes I see people invoke web API using requests.Session object:</p>
<pre><code>client = requests.session()
resp = client.get(url='...')
</code></pre>
<p>But sometimes they don't:</p>
<pre><code>resp = requests.get(url='...')
</code></pre>
<p>Can somebody explain when should we use <code>Session</code> and when we don't need them?</p> | 32,986,316 | 2 | 0 | null | 2015-10-07 07:29:27.467 UTC | 12 | 2020-03-04 21:33:32.963 UTC | 2017-05-15 09:18:57.937 UTC | null | 100,297 | null | 4,790,051 | null | 1 | 45 | python|python-requests | 20,362 | <p>Under the hood, <code>requests.get()</code> creates a new <code>Session</code> object for each request made.</p>
<p>By creating a session object up front, you get to <em>reuse</em> the session; this lets you persist cookies, for example, and lets you re-use settings to be used for all connections such as headers and query parameters. To top this all off, sessions let you take advantage of connection pooling; reusing connections to the same host.</p>
<p>See the <a href="https://requests.readthedocs.io/en/latest/user/advanced/#session-objects" rel="noreferrer"><em>Sessions</em> documentation</a>:</p>
<blockquote>
<p>The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3‘s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see <a href="https://en.wikipedia.org/wiki/HTTP_persistent_connection" rel="noreferrer">HTTP persistent connection</a>).</p>
</blockquote> |
20,938,934 | Controlling Application's Volume: By Process-ID | <p>I need to control the volume level of the audio produced by a specific application.
I have found Simon's simple & neat answer for a similar question <a href="https://stackoverflow.com/questions/14306048/controling-volume-mixer">here</a>, but it enumerates audio-generating applications by Display-Name, which for some applications - is empty, and hence cannot be used to detect the target application (whose volume is to be controlled).</p>
<p>Hence, I'm looking for a very similar solution, enumerating audio-playing applications' <em>process IDs</em>, through which I could detect applications' actual names (process names & main window titles).</p>
<p><em>I'm using VB.Net 2010, for Windows 7.</em></p> | 20,982,715 | 4 | 1 | null | 2014-01-05 20:44:47.503 UTC | 10 | 2022-01-22 16:59:11.197 UTC | 2017-05-23 12:18:33.24 UTC | null | -1 | null | 1,117,614 | null | 1 | 7 | .net|vb.net|winforms | 13,202 | <p>Here is a set of utility C# classes that allow you to get information on audio devices and audio session, including process information. They use the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd316599.aspx" rel="nofollow noreferrer">Windows Core Audio Library</a>, and only work on Windows 7 or higher:</p>
<pre><code>// sample program
class Program
{
static void Main(string[] args)
{
// dump all audio devices
foreach (AudioDevice device in AudioUtilities.GetAllDevices())
{
Console.WriteLine(device.FriendlyName);
}
// dump all audio sessions
foreach (AudioSession session in AudioUtilities.GetAllSessions())
{
if (session.Process != null)
{
// only the one associated with a defined process
Console.WriteLine(session.Process.ProcessName);
}
}
}
}
// audio utilities
public static class AudioUtilities
{
private static IAudioSessionManager2 GetAudioSessionManager()
{
IMMDevice speakers = GetSpeakers();
if (speakers == null)
return null;
// win7+ only
object o;
if (speakers.Activate(typeof(IAudioSessionManager2).GUID, CLSCTX.CLSCTX_ALL, IntPtr.Zero, out o) != 0 || o == null)
return null;
return o as IAudioSessionManager2;
}
public static AudioDevice GetSpeakersDevice()
{
return CreateDevice(GetSpeakers());
}
private static AudioDevice CreateDevice(IMMDevice dev)
{
if (dev == null)
return null;
string id;
dev.GetId(out id);
DEVICE_STATE state;
dev.GetState(out state);
Dictionary<string, object> properties = new Dictionary<string, object>();
IPropertyStore store;
dev.OpenPropertyStore(STGM.STGM_READ, out store);
if (store != null)
{
int propCount;
store.GetCount(out propCount);
for (int j = 0; j < propCount; j++)
{
PROPERTYKEY pk;
if (store.GetAt(j, out pk) == 0)
{
PROPVARIANT value = new PROPVARIANT();
int hr = store.GetValue(ref pk, ref value);
object v = value.GetValue();
try
{
if (value.vt != VARTYPE.VT_BLOB) // for some reason, this fails?
{
PropVariantClear(ref value);
}
}
catch
{
}
string name = pk.ToString();
properties[name] = v;
}
}
}
return new AudioDevice(id, (AudioDeviceState)state, properties);
}
public static IList<AudioDevice> GetAllDevices()
{
List<AudioDevice> list = new List<AudioDevice>();
IMMDeviceEnumerator deviceEnumerator = null;
try
{
deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
}
catch
{
}
if (deviceEnumerator == null)
return list;
IMMDeviceCollection collection;
deviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE.MASK_ALL, out collection);
if (collection == null)
return list;
int count;
collection.GetCount(out count);
for (int i = 0; i < count; i++)
{
IMMDevice dev;
collection.Item(i, out dev);
if (dev != null)
{
list.Add(CreateDevice(dev));
}
}
return list;
}
private static IMMDevice GetSpeakers()
{
// get the speakers (1st render + multimedia) device
try
{
IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator());
IMMDevice speakers;
deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers);
return speakers;
}
catch
{
return null;
}
}
public static IList<AudioSession> GetAllSessions()
{
List<AudioSession> list = new List<AudioSession>();
IAudioSessionManager2 mgr = GetAudioSessionManager();
if (mgr == null)
return list;
IAudioSessionEnumerator sessionEnumerator;
mgr.GetSessionEnumerator(out sessionEnumerator);
int count;
sessionEnumerator.GetCount(out count);
for (int i = 0; i < count; i++)
{
IAudioSessionControl ctl;
sessionEnumerator.GetSession(i, out ctl);
if (ctl == null)
continue;
IAudioSessionControl2 ctl2 = ctl as IAudioSessionControl2;
if (ctl2 != null)
{
list.Add(new AudioSession(ctl2));
}
}
Marshal.ReleaseComObject(sessionEnumerator);
Marshal.ReleaseComObject(mgr);
return list;
}
public static AudioSession GetProcessSession()
{
int id = Process.GetCurrentProcess().Id;
foreach (AudioSession session in GetAllSessions())
{
if (session.ProcessId == id)
return session;
session.Dispose();
}
return null;
}
[DllImport("ole32.dll")]
private static extern int PropVariantClear(ref PROPVARIANT pvar);
[ComImport]
[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
private class MMDeviceEnumerator
{
}
[Flags]
private enum CLSCTX
{
CLSCTX_INPROC_SERVER = 0x1,
CLSCTX_INPROC_HANDLER = 0x2,
CLSCTX_LOCAL_SERVER = 0x4,
CLSCTX_REMOTE_SERVER = 0x10,
CLSCTX_ALL = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
}
private enum STGM
{
STGM_READ = 0x00000000,
}
private enum EDataFlow
{
eRender,
eCapture,
eAll,
}
private enum ERole
{
eConsole,
eMultimedia,
eCommunications,
}
private enum DEVICE_STATE
{
ACTIVE = 0x00000001,
DISABLED = 0x00000002,
NOTPRESENT = 0x00000004,
UNPLUGGED = 0x00000008,
MASK_ALL = 0x0000000F
}
[StructLayout(LayoutKind.Sequential)]
private struct PROPERTYKEY
{
public Guid fmtid;
public int pid;
public override string ToString()
{
return fmtid.ToString("B") + " " + pid;
}
}
// NOTE: we only define what we handle
[Flags]
private enum VARTYPE : short
{
VT_I4 = 3,
VT_BOOL = 11,
VT_UI4 = 19,
VT_LPWSTR = 31,
VT_BLOB = 65,
VT_CLSID = 72,
}
[StructLayout(LayoutKind.Sequential)]
private struct PROPVARIANT
{
public VARTYPE vt;
public ushort wReserved1;
public ushort wReserved2;
public ushort wReserved3;
public PROPVARIANTunion union;
public object GetValue()
{
switch (vt)
{
case VARTYPE.VT_BOOL:
return union.boolVal != 0;
case VARTYPE.VT_LPWSTR:
return Marshal.PtrToStringUni(union.pwszVal);
case VARTYPE.VT_UI4:
return union.lVal;
case VARTYPE.VT_CLSID:
return (Guid)Marshal.PtrToStructure(union.puuid, typeof(Guid));
default:
return vt.ToString() + ":?";
}
}
}
[StructLayout(LayoutKind.Explicit)]
private struct PROPVARIANTunion
{
[FieldOffset(0)]
public int lVal;
[FieldOffset(0)]
public ulong uhVal;
[FieldOffset(0)]
public short boolVal;
[FieldOffset(0)]
public IntPtr pwszVal;
[FieldOffset(0)]
public IntPtr puuid;
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceEnumerator
{
[PreserveSig]
int EnumAudioEndpoints(EDataFlow dataFlow, DEVICE_STATE dwStateMask, out IMMDeviceCollection ppDevices);
[PreserveSig]
int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppEndpoint);
[PreserveSig]
int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string pwstrId, out IMMDevice ppDevice);
[PreserveSig]
int RegisterEndpointNotificationCallback(IMMNotificationClient pClient);
[PreserveSig]
int UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
}
[Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMNotificationClient
{
void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, DEVICE_STATE dwNewState);
void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId);
void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId);
void OnDefaultDeviceChanged(EDataFlow flow, ERole role, string pwstrDefaultDeviceId);
void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PROPERTYKEY key);
}
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceCollection
{
[PreserveSig]
int GetCount(out int pcDevices);
[PreserveSig]
int Item(int nDevice, out IMMDevice ppDevice);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDevice
{
[PreserveSig]
int Activate([MarshalAs(UnmanagedType.LPStruct)] Guid riid, CLSCTX dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
[PreserveSig]
int OpenPropertyStore(STGM stgmAccess, out IPropertyStore ppProperties);
[PreserveSig]
int GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId);
[PreserveSig]
int GetState(out DEVICE_STATE pdwState);
}
[Guid("6f79d558-3e96-4549-a1d1-7d75d2288814"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPropertyDescription
{
[PreserveSig]
int GetPropertyKey(out PROPERTYKEY pkey);
[PreserveSig]
int GetCanonicalName(out IntPtr ppszName);
[PreserveSig]
int GetPropertyType(out short pvartype);
[PreserveSig]
int GetDisplayName(out IntPtr ppszName);
// WARNING: the rest is undefined. you *can't* implement it, only use it.
}
[Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPropertyStore
{
[PreserveSig]
int GetCount(out int cProps);
[PreserveSig]
int GetAt(int iProp, out PROPERTYKEY pkey);
[PreserveSig]
int GetValue(ref PROPERTYKEY key, ref PROPVARIANT pv);
[PreserveSig]
int SetValue(ref PROPERTYKEY key, ref PROPVARIANT propvar);
[PreserveSig]
int Commit();
}
[Guid("BFA971F1-4D5E-40BB-935E-967039BFBEE4"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioSessionManager
{
[PreserveSig]
int GetAudioSessionControl([MarshalAs(UnmanagedType.LPStruct)] Guid AudioSessionGuid, int StreamFlags, out IAudioSessionControl SessionControl);
[PreserveSig]
int GetSimpleAudioVolume([MarshalAs(UnmanagedType.LPStruct)] Guid AudioSessionGuid, int StreamFlags, ISimpleAudioVolume AudioVolume);
}
[Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioSessionManager2
{
[PreserveSig]
int GetAudioSessionControl([MarshalAs(UnmanagedType.LPStruct)] Guid AudioSessionGuid, int StreamFlags, out IAudioSessionControl SessionControl);
[PreserveSig]
int GetSimpleAudioVolume([MarshalAs(UnmanagedType.LPStruct)] Guid AudioSessionGuid, int StreamFlags, ISimpleAudioVolume AudioVolume);
[PreserveSig]
int GetSessionEnumerator(out IAudioSessionEnumerator SessionEnum);
[PreserveSig]
int RegisterSessionNotification(IAudioSessionNotification SessionNotification);
[PreserveSig]
int UnregisterSessionNotification(IAudioSessionNotification SessionNotification);
int RegisterDuckNotificationNotImpl();
int UnregisterDuckNotificationNotImpl();
}
[Guid("641DD20B-4D41-49CC-ABA3-174B9477BB08"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioSessionNotification
{
void OnSessionCreated(IAudioSessionControl NewSession);
}
[Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioSessionEnumerator
{
[PreserveSig]
int GetCount(out int SessionCount);
[PreserveSig]
int GetSession(int SessionCount, out IAudioSessionControl Session);
}
[Guid("bfb7ff88-7239-4fc9-8fa2-07c950be9c6d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionControl2
{
// IAudioSessionControl
[PreserveSig]
int GetState(out AudioSessionState pRetVal);
[PreserveSig]
int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetGroupingParam(out Guid pRetVal);
[PreserveSig]
int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int RegisterAudioSessionNotification(IAudioSessionEvents NewNotifications);
[PreserveSig]
int UnregisterAudioSessionNotification(IAudioSessionEvents NewNotifications);
// IAudioSessionControl2
[PreserveSig]
int GetSessionIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int GetSessionInstanceIdentifier([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int GetProcessId(out int pRetVal);
[PreserveSig]
int IsSystemSoundsSession();
[PreserveSig]
int SetDuckingPreference(bool optOut);
}
[Guid("F4B1A599-7266-4319-A8CA-E70ACB11E8CD"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionControl
{
[PreserveSig]
int GetState(out AudioSessionState pRetVal);
[PreserveSig]
int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig]
int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetGroupingParam(out Guid pRetVal);
[PreserveSig]
int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int RegisterAudioSessionNotification(IAudioSessionEvents NewNotifications);
[PreserveSig]
int UnregisterAudioSessionNotification(IAudioSessionEvents NewNotifications);
}
[Guid("24918ACC-64B3-37C1-8CA9-74A66E9957A8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IAudioSessionEvents
{
void OnDisplayNameChanged([MarshalAs(UnmanagedType.LPWStr)] string NewDisplayName, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
void OnIconPathChanged([MarshalAs(UnmanagedType.LPWStr)] string NewIconPath, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
void OnSimpleVolumeChanged(float NewVolume, bool NewMute, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
void OnChannelVolumeChanged(int ChannelCount, IntPtr NewChannelVolumeArray, int ChangedChannel, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
void OnGroupingParamChanged([MarshalAs(UnmanagedType.LPStruct)] Guid NewGroupingParam, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
void OnStateChanged(AudioSessionState NewState);
void OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason);
}
[Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface ISimpleAudioVolume
{
[PreserveSig]
int SetMasterVolume(float fLevel, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetMasterVolume(out float pfLevel);
[PreserveSig]
int SetMute(bool bMute, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext);
[PreserveSig]
int GetMute(out bool pbMute);
}
}
public sealed class AudioSession : IDisposable
{
private AudioUtilities.IAudioSessionControl2 _ctl;
private Process _process;
internal AudioSession(AudioUtilities.IAudioSessionControl2 ctl)
{
_ctl = ctl;
}
public Process Process
{
get
{
if (_process == null && ProcessId != 0)
{
try
{
_process = Process.GetProcessById(ProcessId);
}
catch
{
// do nothing
}
}
return _process;
}
}
public int ProcessId
{
get
{
CheckDisposed();
int i;
_ctl.GetProcessId(out i);
return i;
}
}
public string Identifier
{
get
{
CheckDisposed();
string s;
_ctl.GetSessionIdentifier(out s);
return s;
}
}
public string InstanceIdentifier
{
get
{
CheckDisposed();
string s;
_ctl.GetSessionInstanceIdentifier(out s);
return s;
}
}
public AudioSessionState State
{
get
{
CheckDisposed();
AudioSessionState s;
_ctl.GetState(out s);
return s;
}
}
public Guid GroupingParam
{
get
{
CheckDisposed();
Guid g;
_ctl.GetGroupingParam(out g);
return g;
}
set
{
CheckDisposed();
_ctl.SetGroupingParam(value, Guid.Empty);
}
}
public string DisplayName
{
get
{
CheckDisposed();
string s;
_ctl.GetDisplayName(out s);
return s;
}
set
{
CheckDisposed();
string s;
_ctl.GetDisplayName(out s);
if (s != value)
{
_ctl.SetDisplayName(value, Guid.Empty);
}
}
}
public string IconPath
{
get
{
CheckDisposed();
string s;
_ctl.GetIconPath(out s);
return s;
}
set
{
CheckDisposed();
string s;
_ctl.GetIconPath(out s);
if (s != value)
{
_ctl.SetIconPath(value, Guid.Empty);
}
}
}
private void CheckDisposed()
{
if (_ctl == null)
throw new ObjectDisposedException("Control");
}
public override string ToString()
{
string s = DisplayName;
if (!string.IsNullOrEmpty(s))
return "DisplayName: " + s;
if (Process != null)
return "Process: " + Process.ProcessName;
return "Pid: " + ProcessId;
}
public void Dispose()
{
if (_ctl != null)
{
Marshal.ReleaseComObject(_ctl);
_ctl = null;
}
}
}
public sealed class AudioDevice
{
internal AudioDevice(string id, AudioDeviceState state, IDictionary<string, object> properties)
{
Id = id;
State = state;
Properties = properties;
}
public string Id { get; private set; }
public AudioDeviceState State { get; private set; }
public IDictionary<string, object> Properties { get; private set; }
public string Description
{
get
{
const string PKEY_Device_DeviceDesc = "{a45c254e-df1c-4efd-8020-67d146a850e0} 2";
object value;
Properties.TryGetValue(PKEY_Device_DeviceDesc, out value);
return string.Format("{0}", value);
}
}
public string ContainerId
{
get
{
const string PKEY_Devices_ContainerId = "{8c7ed206-3f8a-4827-b3ab-ae9e1faefc6c} 2";
object value;
Properties.TryGetValue(PKEY_Devices_ContainerId, out value);
return string.Format("{0}", value);
}
}
public string EnumeratorName
{
get
{
const string PKEY_Device_EnumeratorName = "{a45c254e-df1c-4efd-8020-67d146a850e0} 24";
object value;
Properties.TryGetValue(PKEY_Device_EnumeratorName, out value);
return string.Format("{0}", value);
}
}
public string InterfaceFriendlyName
{
get
{
const string DEVPKEY_DeviceInterface_FriendlyName = "{026e516e-b814-414b-83cd-856d6fef4822} 2";
object value;
Properties.TryGetValue(DEVPKEY_DeviceInterface_FriendlyName, out value);
return string.Format("{0}", value);
}
}
public string FriendlyName
{
get
{
const string DEVPKEY_Device_FriendlyName = "{a45c254e-df1c-4efd-8020-67d146a850e0} 14";
object value;
Properties.TryGetValue(DEVPKEY_Device_FriendlyName, out value);
return string.Format("{0}", value);
}
}
public string IconPath
{
get
{
const string DEVPKEY_DeviceClass_IconPath = "{259abffc-50a7-47ce-af08-68c9a7d73366} 12";
object value;
Properties.TryGetValue(DEVPKEY_DeviceClass_IconPath, out value);
return string.Format("{0}", value);
}
}
public override string ToString()
{
return FriendlyName;
}
}
public enum AudioSessionState
{
Inactive = 0,
Active = 1,
Expired = 2
}
public enum AudioDeviceState
{
Active = 0x1,
Disabled = 0x2,
NotPresent = 0x4,
Unplugged = 0x8,
}
public enum AudioSessionDisconnectReason
{
DisconnectReasonDeviceRemoval = 0,
DisconnectReasonServerShutdown = 1,
DisconnectReasonFormatChanged = 2,
DisconnectReasonSessionLogoff = 3,
DisconnectReasonSessionDisconnected = 4,
DisconnectReasonExclusiveModeOverride = 5
}
</code></pre> |
36,871,188 | How to access pandas DataFrame datetime index using strings | <p>This is a very simple and practical question. I have the feeling that it must be a silly detail and that there should be similar questions. I wasn't able to find them tho. If someone does I'll happily delete this one.</p>
<p>The closest I found were these:
<a href="https://stackoverflow.com/questions/27501694/pandas-iterating-over-dataframe-index-with-loc/27527628#27527628">pandas: iterating over DataFrame index with loc</a></p>
<p><a href="https://stackoverflow.com/questions/13221218/how-to-select-rows-within-a-pandas-dataframe-based-on-time-only-when-index-is-da">How to select rows within a pandas dataframe based on time only when index is date and time</a></p>
<p>anyway, the thing is, I have a datetime indexed panda dataframe as follows:</p>
<pre><code>In[81]: y
Out[81]:
PETR4 CSNA3 VALE5
2008-01-01 0.0 0.0 0.0
2008-01-02 1.0 1.0 1.0
2008-01-03 7.0 7.0 7.0
In[82]: y.index
Out[82]: DatetimeIndex(['2008-01-01', '2008-01-02', '2008-01-03'], dtype='datetime64[ns]', freq=None)
</code></pre>
<p>Oddly enough, I can't access its values using none of the following methods:</p>
<pre><code>In[83]: y[datetime.datetime(2008,1,1)]
In[84]: y['2008-1-1']
In[85]: y['1/1/2008']
</code></pre>
<p>I get the <code>KeyError</code> error.</p>
<p>Even more weird is that the following methods DO work:</p>
<pre><code>In[86]: y['2008']
Out[86]:
PETR4 CSNA3 VALE5
2008-01-01 0.0 0.0 0.0
2008-01-02 1.0 1.0 1.0
2008-01-03 7.0 7.0 7.0
In[87]: y['2008-1']
Out[87]:
PETR4 CSNA3 VALE5
2008-01-01 0.0 0.0 0.0
2008-01-02 1.0 1.0 1.0
2008-01-03 7.0 7.0 7.0
</code></pre>
<p>I'm fairly new to pandas so maybe I'm missing something here?</p> | 36,871,559 | 3 | 0 | null | 2016-04-26 16:56:44.927 UTC | 11 | 2018-01-02 01:36:09.723 UTC | 2017-05-23 12:34:31.41 UTC | null | -1 | null | 2,789,717 | null | 1 | 40 | python|pandas | 94,185 | <p>pandas is taking what's inside the <code>[]</code> and deciding what it should do. If it's a subset of column names, it'll return a DataFrame with those columns. If it's a range of index values, it'll return a subset of those rows. What is does not handle is taking a single index value.</p>
<h3>Solution</h3>
<p>Two work around's</p>
<p>1.Turn the argument into something pandas interprets as a range.</p>
<pre><code>df['2008-01-01':'2008-01-01']
</code></pre>
<p>2.Use the method designed to give you this result. <code>loc[]</code></p>
<pre><code>df.loc['2008-01-01']
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer">Link to the documentation</a></p> |
46,724,078 | How to remove specific commits from Git? | <p>I want to remove few commits from my remote repository. I have few commits like this in my repo:</p>
<pre><code>commits messages
abcd123 some message
xyze456 another commit message
98y65r4 this commit is not required
987xcrt this commit is not required
bl8976t initial commit
</code></pre>
<p>I want to remove commit <code>98y65r4</code> and <code>987xcrt</code> from my repo. How to achieve it?</p> | 46,724,280 | 1 | 0 | null | 2017-10-13 06:51:58.12 UTC | 18 | 2019-05-20 19:47:46.987 UTC | 2019-05-20 19:47:46.987 UTC | null | 4,621,513 | null | 7,156,080 | null | 1 | 60 | git | 91,839 | <p>There are two alternatives to this: the safe one that leaves you with a dirty git history, or the unsafe one that leaves you with a clean git history. You pick:</p>
<h1>Option 1: Revert</h1>
<p>You can tell git to "Revert a commit". This means it will introduce a change that reverts each change you made in a commit. You would need to execute it twice (once per commit):</p>
<pre><code>git revert 98y65r4
git revert 987xcrt
</code></pre>
<p>This solution will leave your git history like this (you can execute <code>gitk --all</code> to see a graphical representation of the state of your repo):</p>
<pre><code>2222222 revert of 987xcrt: this commit is not required
1111111 revert of 98y65r4: this commit is not required
abcd123 some message
xyze456 another commit message
98y65r4 this commit is not required
987xcrt this commit is not required
bl8976t initial commit
</code></pre>
<p>Then you can push the new 2 commits to your remote repo:</p>
<pre><code>git push
</code></pre>
<p>This solution is safe because it does not make destructive operations on your remote repo.</p>
<h1>Option 2: Interactive rebase</h1>
<p>You also can use an interactive rebase for that. The command is:</p>
<pre><code>git rebase -i bl8976t
</code></pre>
<p>In it, you are telling git to let you select which commits you want to mix together, reorder or <em>remove</em>.</p>
<p>When you execute the command an editor will open with a text similar to this:</p>
<pre><code>pick bl8976t initial commit
pick 987xcrt this commit is not required
pick 98y65r4 this commit is not required
pick xyze456 another commit message
pick abcd123 some message
</code></pre>
<p>Just go on and delete the lines you don't want, like this:</p>
<pre><code>pick bl8976t initial commit
pick xyze456 another commit message
pick abcd123 some message
</code></pre>
<p>Save the file and close the editor.</p>
<p>So far, this has only modified the local copy of your repository (you can see the tree of commits with <code>gitk --all</code>).</p>
<p>Now you need to push your changes to your repo, which is done with a "push force", but before you execute the command bear in mind that <strong>push force is a destructive operation, it will overwrite the history of your remote repository and can cause merge troubles to other people working on it</strong>. If you are ok and want to do the push force, the command is:</p>
<pre><code>git push -f
</code></pre> |
46,989,131 | Cannot invoke initializer for type 'Double' with an argument list of type '(String?)' | <p>I have two issues:</p>
<pre><code>let amount:String? = amountTF.text
</code></pre>
<ol>
<li><code>amount?.characters.count <= 0</code></li>
</ol>
<p>It's giving error :</p>
<pre><code>Binary operator '<=' cannot be applied to operands of type 'String.CharacterView.IndexDistance?' (aka 'Optional<Int>') and 'In
</code></pre>
<ol start="2">
<li><code>let am = Double(amount)</code></li>
</ol>
<p>It's giving error:</p>
<pre><code>Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'
</code></pre>
<p>I don't know how to solve this.</p> | 46,989,189 | 3 | 0 | null | 2017-10-28 11:19:41.777 UTC | 2 | 2020-07-18 21:59:55.377 UTC | 2017-10-29 10:35:19.69 UTC | null | 472,495 | null | 5,203,412 | null | 1 | 11 | ios|swift|xcode|int | 39,898 | <p><code>amount?.count <= 0</code> here amount is optional. You have to make sure it not <code>nil</code>.</p>
<pre><code>let amount:String? = amountTF.text
if let amountValue = amount, amountValue.count <= 0 {
}
</code></pre>
<p><code>amountValue.count <= 0</code> will only be called if <code>amount</code> is not nil.</p>
<p>Same issue for this <code>let am = Double(amount)</code>. <code>amount</code> is optional. </p>
<pre><code>if let amountValue = amount, let am = Double(amountValue) {
// am
}
</code></pre> |
25,467,287 | Bind IsEnabled property to Boolean in WPF | <p>I have a <code>TextBox</code> which needs to be enabled / disabled programmatically. I want to achieve this using a binding to a <code>Boolean</code>. Here is the <code>TextBox</code> XAML:</p>
<pre><code><TextBox Height="424" HorizontalAlignment="Left"
Margin="179,57,0,0" Name="textBox2"
VerticalAlignment="Top" Width="777"
TextWrapping="WrapWithOverflow"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
AcceptsReturn="True" AcceptsTab="True"
Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding Path=TextBoxEnabled}"/>
</code></pre>
<p>Notice the Text property is bound as well; it is fully functional, which makes me think it is not a DataContext issue.</p>
<p>However, when I call this code:</p>
<pre><code>private Boolean _textbox_enabled;
public Boolean Textbox_Enabled
{
get { return _textbox_enabled; }
set
{
OnPropertyChanged("TextBoxEnabled");
}
}
</code></pre>
<p>It does not work. To give further information, the TextBox_Enabled property is changed by this method:</p>
<pre><code>public void DisabledTextBox()
{
this.Textbox_Enabled = false;
}
</code></pre>
<p>..which is called when a key combination is pressed.</p> | 25,467,325 | 1 | 0 | null | 2014-08-23 23:28:17.287 UTC | null | 2015-01-03 18:23:22.053 UTC | 2014-08-24 16:49:07.05 UTC | null | 1,870,803 | null | 3,761,858 | null | 1 | 5 | c#|wpf|xaml|binding|isenabled | 53,174 | <p>Here are your little typos!</p>
<pre><code> private Boolean _textbox_enabled;
public Boolean TextboxEnabled // here, underscore typo
{
get { return _textbox_enabled; }
set
{
_textbox_enabled = value; // You miss this line, could be ok to do an equality check here to. :)
OnPropertyChanged("TextboxEnabled"); //
}
}
</code></pre>
<p>Another thing for your xaml to update the text to the vm/datacontext</p>
<pre><code>Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding TextBoxEnabled}"/>
</code></pre> |
25,630,141 | ValidateInput(false) vs AllowHtml | <p>I have a form that is used to create a memo, to do that I am using a rich text editor to provide some styling, this creates html tags in order to apply style. When I post that text, the mvc throws an error to prevent potentially dangerous scripts, so I have to specifically allow it. </p>
<p>I have found 2 ways of doing this, one is to decorate the controller method with <code>[ValidateInput(false)]</code> and the other is to decorate the <code>ViewModel</code> attribute with <code>[AllowHtml]</code>. To me, <code>[AllowHtml]</code> looks much nicer, but I have only found that approach used 1 time and the <code>[ValidateInput(false)]</code> seems to be the preferred way.</p>
<p>Which method should I use and what are the differences between the two?</p> | 30,522,282 | 2 | 0 | null | 2014-09-02 18:41:53.15 UTC | 16 | 2019-08-07 10:39:58.793 UTC | 2018-03-31 23:29:10.817 UTC | null | 745,750 | null | 2,073,489 | null | 1 | 55 | asp.net-mvc-4|viewmodel|richtext | 54,520 | <p><strong>ValidateInput and AllowHTML are directly connected with <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a> security issues</strong>.</p>
<p>So let us first try to understand XSS.</p>
<p>XSS (cross-site scripting) is a security attack where the attacker injects malicious code while doing data entry. Now the good news is that XSS is by default prevented in MVC. So if any one tries to post JavaScript or HTML code he lands with the below error.</p>
<p><img src="https://i.stack.imgur.com/9xQtj.png" alt="Enter image description here"></p>
<p>But in real time there are scenarios where HTML has to be allowed, like HTML editors. So for those kind of scenarios you can decorate your action with the below attribute.</p>
<pre><code>[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
}
</code></pre>
<p>But wait, there is a problem here. The problem is we have allowed HTML on the complete action which can be dangerous. So if we can have more granular control on the field or property level that would really create a neat, tidy and professional solution.</p>
<p>That’s where AllowHTML is useful. You can see in the below code I have decorated “AllowHTML” on the product class property level.</p>
<pre><code>public class Product
{
public string ProductName { get; set; }
[AllowHtml]
public string ProductDescription { get; set; }
}
</code></pre>
<p>So summarizing “ValidateInput” allows scripts and HTML to be posted on action level while “AllowHTML” is on a more granular level.</p>
<p>I would recommend to use “AllowHTML” more until you are very sure that the whole action needs to be naked.</p>
<p>I would recommend you to read the blog post <em><a href="http://www.codeproject.com/Articles/995931/Preventing-XSS-Attacks-in-ASP-NET-MVC-using-Valida">Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML</a></em> which demonstrates step by step about the importance of these two attributes with an example.</p> |
43,288,550 | IOPub data rate exceeded in Jupyter notebook (when viewing image) | <p>I want to view an image in Jupyter notebook. It's a 9.9MB .png file.</p>
<pre><code>from IPython.display import Image
Image(filename='path_to_image/image.png')
</code></pre>
<p>I get the below error:</p>
<pre><code>IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
</code></pre>
<p>A bit surprising and <a href="https://github.com/ioam/holoviews/issues/1181" rel="noreferrer">reported elsewhere</a>.</p>
<p>Is this expected and is there a simple solution? </p>
<p>(Error msg suggests changing limit in <code>--NotebookApp.iopub_data_rate_limit</code>.)</p> | 44,679,222 | 12 | 1 | null | 2017-04-07 23:40:40.037 UTC | 55 | 2022-07-01 05:30:19.25 UTC | 2018-11-01 01:44:35.827 UTC | null | 428,862 | null | 3,422,206 | null | 1 | 158 | jupyter-notebook|ipython|jupyter | 316,218 | <p>Try this:</p>
<pre><code>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
</code></pre>
<p>Or this: </p>
<pre><code>yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
</code></pre> |
8,811,315 | how to get current wifi connection info in android | <p>I'm trying to find if <code>scanResult</code> is the current connected wifi network.</p>
<p>here is my code</p>
<pre><code>public boolean IsCurrentConnectedWifi(ScanResult scanResult)
{
WifiManager mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();
if(currentWifi != null)
{
if(currentWifi.getSSID() != null)
{
if(currentWifi.getSSID() == scanResult.SSID)
return true;
}
}
return false;
}
</code></pre>
<p>I have no problem on getting scanresult.</p>
<p>Always I'm getting currentWifi is null.</p>
<p>Where am I wrong or Is there any alternative method to do this?</p> | 11,075,300 | 3 | 0 | null | 2012-01-10 22:15:32.8 UTC | 6 | 2019-08-09 14:45:47.777 UTC | 2012-01-10 22:38:31.99 UTC | null | 603,127 | null | 603,127 | null | 1 | 36 | android | 69,244 | <p>Most probably you have already found answer: <code>currentWifi.getSSID()</code> is quoted in most cases where <code>scanResult.SSID</code> is not (and of course you must not use <code>==</code> on strings :)).</p>
<p>Try something like this, it returns current <code>SSID</code> or <code>null</code>:</p>
<pre><code>public static String getCurrentSsid(Context context) {
String ssid = null;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) {
ssid = connectionInfo.getSSID();
}
}
return ssid;
}
</code></pre>
<p>also permissions are required:</p>
<pre><code><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code></pre>
<p><code>StringUtil</code> is not a standard Android class, so you can use <code>TextUtils</code> instead. The code then looks like this:</p>
<pre><code>public static String getCurrentSsid(Context context) {
String ssid = null;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
ssid = connectionInfo.getSSID();
}
}
return ssid;
}
</code></pre> |
8,447,913 | Is there a filter for divide for Django Template? | <p>I noticed there is built-in <code>add</code> filter, but I wasn't able to find <code>divide</code>. </p>
<p>I am new to Django and not sure if there is a such filter.</p> | 8,447,990 | 6 | 0 | null | 2011-12-09 15:42:16.62 UTC | 1 | 2020-08-15 14:52:59.207 UTC | null | null | null | null | 995,140 | null | 1 | 46 | python|django | 48,377 | <p>There is not it. But if you are a little hacker....</p>
<p><a href="http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/" rel="noreferrer">http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/</a></p>
<blockquote>
<p>to compute A*B: {% widthratio A 1 B %}</p>
<p>to compute A/B: {% widthratio A B 1 %}</p>
<p>to compute A^2: {% widthratio A 1 A %}</p>
<p>to compute (A+B)^2: {% widthratio A|add:B 1 A|add:B %}</p>
<p>to compute (A+B) * (C+D): {% widthratio A|add:B 1 C|add:D %}</p>
</blockquote>
<p>Also you can create a filter to division in 2 minutes</p> |
48,393,027 | What does flow {| brace pipe |} syntax do? | <p>What does <a href="https://github.com/graphql/graphql-js/blob/bc33f2e5382f454f8576e23e9a604c929d21e013/src/utilities/extendSchema.js#L36" rel="noreferrer">this</a> Flow syntax mean/do?</p>
<pre><code>type Options = {|
assumeValid?: boolean,
commentDescriptions?: boolean,
|};
</code></pre>
<p>I can't seem to find where the <code>{|</code> ... <code>|}</code> syntax is documented.</p> | 48,393,339 | 1 | 0 | null | 2018-01-23 01:55:09.647 UTC | 3 | 2018-02-07 16:59:51.043 UTC | 2018-02-07 16:59:51.043 UTC | null | 147,844 | null | 65,387 | null | 1 | 29 | syntax|flowtype | 4,041 | <p>This is Flowtype's <a href="https://flow.org/en/docs/types/objects/#toc-exact-object-types" rel="noreferrer">Exact Object type</a> syntax.</p> |
6,590,889 | How Emacs determines a unit of work to undo | <p>When you enter the command <kbd>C-/</kbd>, Emacs undoes some part of your recent changes to a buffer. When you enter <kbd>C-/</kbd> again, it undoes another chunk of work.</p>
<p>I have read the <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Undo.html#Undo" rel="noreferrer">Emacs manual entry on Undo</a> but it is vague about exactly how it works. The manual says "Consecutive character insertion commands are usually grouped together into a single undo record" but it does not explain how it decides the number of character insertion commands that constitute a group. The number of characters it puts in a group seems random.</p>
<p>Can anyone explain the algorithm Emacs uses to group characters into undo records?</p> | 6,593,906 | 1 | 0 | null | 2011-07-06 02:17:23.343 UTC | 3 | 2011-07-06 15:20:04.723 UTC | 2011-07-06 15:20:04.723 UTC | null | 6,148 | null | 25,188 | null | 1 | 30 | emacs | 970 | <p>The logic for setting undo boundaries is mostly in <code>self-insert-command</code> which is implemented in <a href="http://bzr.savannah.gnu.org/lh/emacs/trunk/annotate/head:/src/cmds.c"><code>cmds.c</code></a>. You'll have to read the code for the full story, but basically:</p>
<ul>
<li>As long as you are just typing characters, there's an undo boundary every 20 characters you type.</li>
<li>But if you issue a different editing command (you kill a word, for example), this causes an undo boundary to be added immediately, resetting the character count.</li>
<li>Certain "hairy" insertions (as determined by <code>internal_self_insert</code>) cause an an undo boundary to be added immediately, and the character count to be reset. Reading the code, it looks as though these are: (1) in <code>overwrite-mode</code>, if you overwrote a character with one that has a different width, e.g. typing over a tab; (2) if the character you inserted caused an abbreviation to be expanded; (3) if the character you typed caused <code>auto-fill-mode</code> to insert indentation.</li>
<li>In addition, any editing command that decides it would be a good idea to have an undo boundary can request it by calling <code>undo-boundary</code>. This does not cause the character count to be reset.</li>
</ul> |
36,470,782 | OPENJSON does not work in SQL Server? | <p>I want to use JSON functions in SQL Server 2016, but when I try to execute <code>OPENJSON</code> function, I get the following error:</p>
<blockquote>
<p>Msg 208, Level 16, State 1, Line 1<br>
Invalid object name 'openjson'.</p>
</blockquote>
<p>Why it does not work? I have SQL Server 2016 RC version.</p> | 36,471,369 | 1 | 2 | null | 2016-04-07 08:33:09.537 UTC | 11 | 2022-08-19 02:14:45.947 UTC | 2016-04-07 08:37:24.863 UTC | null | 13,302 | null | 3,650,135 | null | 1 | 48 | sql-server|json|sql-server-2016 | 42,955 | <p>Could you check compatibility level on database? OPENJSON is available under compatibility level 130. Could you try to execute:</p>
<pre><code>ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = 130
</code></pre>
<p>Also, if you are using JSON on Azure SQL Database, note that even new databases are created under 120 compatibility level so you should change it if you want to use OPENJSON.
Also, if you are using it in Azure SQL Database, run select @@version to see is this V12 server. You should see something like:</p>
<blockquote>
<p>Microsoft SQL Azure (RTM) - 12.0.2000.8
Mar 25 2016 15:11:30
Copyright (c) Microsoft Corporation</p>
</blockquote>
<p>If you see some lower version (e.g. 11.xxx) you probably have database on old architecture where JSON is not supported.</p>
<p>Regards,</p>
<p>Jovan</p> |
34,907,017 | Homebrew won't brew any more | <p>On my MacMini with El Capitan I can't run brew any more. I get the following Error:</p>
<pre><code>/usr/local/Library/Homebrew/config.rb:34:in `initialize': no implicit conversion of nil into String (TypeError)
from /usr/local/Library/Homebrew/config.rb:34:in `new'
from /usr/local/Library/Homebrew/config.rb:34:in `<top (required)>'
from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /usr/local/Library/Homebrew/global.rb:18:in `<top (required)>'
from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /usr/local/Library/brew.rb:10:in `<main>'
</code></pre>
<p>The permissions of /usr/local are correct.</p>
<p>The config.rb file, which I haven't changed looks like this:</p>
<pre><code>def cache
if ENV["HOMEBREW_CACHE"]
Pathname.new(ENV["HOMEBREW_CACHE"]).expand_path
else
# we do this for historic reasons, however the cache *should* be the same
# directory whichever user is used and whatever instance of brew is executed
home_cache = Pathname.new("~/Library/Caches/Homebrew").expand_path
if home_cache.directory? && home_cache.writable_real?
home_cache
else
Pathname.new("/Library/Caches/Homebrew").extend Module.new {
def mkpath
unless exist?
super
chmod 0775
end
end
}
end
end
end
HOMEBREW_CACHE = cache
undef cache
# Where brews installed via URL are cached
HOMEBREW_CACHE_FORMULA = HOMEBREW_CACHE+"Formula"
unless defined? HOMEBREW_BREW_FILE
HOMEBREW_BREW_FILE = ENV["HOMEBREW_BREW_FILE"] || which("brew").to_s
end
# Where we link under
HOMEBREW_PREFIX = Pathname.new(ENV["HOMEBREW_PREFIX"])
# Where .git is found
HOMEBREW_REPOSITORY = Pathname.new(ENV["HOMEBREW_REPOSITORY"])
HOMEBREW_LIBRARY = Pathname.new(ENV["HOMEBREW_LIBRARY"])
HOMEBREW_CONTRIB = HOMEBREW_REPOSITORY/"Library/Contributions"
# Where we store built products
HOMEBREW_CELLAR = Pathname.new(ENV["HOMEBREW_CELLAR"])
HOMEBREW_LOGS = Pathname.new(ENV["HOMEBREW_LOGS"] || "~/Library/Logs/Homebrew/").expand_path
HOMEBREW_TEMP = Pathname.new(ENV.fetch("HOMEBREW_TEMP", "/tmp"))
unless defined? HOMEBREW_LIBRARY_PATH
HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent.join("Homebrew")
end
HOMEBREW_LOAD_PATH = HOMEBREW_LIBRARY_PATH
</code></pre>
<p>The same error occurs with brew, brew doctor, brew update etc.</p>
<p>Any ideas, what could be wrong?</p> | 34,915,198 | 5 | 1 | null | 2016-01-20 17:47:30.153 UTC | 8 | 2021-01-14 03:29:27.907 UTC | 2016-01-20 18:08:36.033 UTC | null | 231,501 | null | 231,501 | null | 1 | 30 | macos|homebrew|osx-elcapitan | 8,048 | <p>I had the same issue - seemed to be the result of a brew update that could not complete due to permissions issues. </p>
<p>First I reset the repo to the latest head:</p>
<pre><code>cd /usr/local/bin
git reset --hard HEAD
</code></pre>
<p>Then I could run:</p>
<pre><code>brew doctor
</code></pre>
<p>Which found permissions issues. Fixing those permissions as per instructions finally allowed me to run:</p>
<pre><code>brew update
</code></pre> |
20,481,225 | How can I use a local image as the base image with a dockerfile? | <p>I'm working on a dockerfile.
I just realised that I've been using <code>FROM</code> with indexed images all along.</p>
<p>So I wonder:</p>
<ul>
<li>How can I use one of my local (custom) images as my base (<code>FROM</code>) image without <code>pushing</code> it to the index?</li>
</ul> | 20,501,690 | 8 | 0 | null | 2013-12-09 21:30:54.217 UTC | 24 | 2022-05-19 21:09:23.467 UTC | null | null | null | null | 853,934 | null | 1 | 195 | docker | 164,999 | <p>You can use it without doing anything special. If you have a local image called <code>blah</code> you can do <code>FROM blah</code>. If you do <code>FROM blah</code> in your Dockerfile, but <em>don't</em> have a local image called <code>blah</code>, <em>then</em> Docker will try to pull it from the registry.</p>
<p>In other words, if a Dockerfile does <code>FROM ubuntu</code>, but you have a local image called <code>ubuntu</code> different from the official one, your image will override it.</p> |
42,821,560 | how to remove the negative values from a data frame in R | <p>I want to remove the negative values from a dataframe and then I need to calculate the mean of each row separately (mean of positive values for each row)
I wrote this to remove negative values but it didn't work. I have a warning like that : </p>
<blockquote>
<p>Error in <code>[<-.data.frame</code>(<code>*tmp*</code>, i, j, value = NULL) :
replacement has length zero</p>
</blockquote>
<p>How can I fix this problem?</p>
<pre><code>for (i in 1:1000) {
for(j in 1:20){
if (dframe[i,j]<=0) dframe[i,j]<-NULL
j=j+1
}
i=i+1
}
</code></pre> | 42,821,987 | 3 | 2 | null | 2017-03-15 22:05:30.513 UTC | 1 | 2018-12-14 04:45:36.543 UTC | 2017-03-15 22:05:59.85 UTC | null | 2,372,064 | null | 7,717,750 | null | 1 | 7 | r|if-statement|for-loop|dataframe | 41,013 | <p>I want to add that it's not necessary to write a for loop, you can just set:</p>
<pre><code>dframe[dframe < 0] <- NA
</code></pre>
<p>As <code>dframe < 0</code> gives the logical indices TRUE where dframe is less than zero, and can be used to index dframe and replace TRUE values with NA.</p>
<p>@MrFlick explained the use of NA instead of NULL, and how to ignore NA values when calculating means of each row:</p>
<pre><code>rowMeans(dframe, na.rm=TRUE)
</code></pre>
<p>Edited to answer question re: rowMeans producing NaNs and how to remove:</p>
<p>NA is "not available" and is a missing value indicator, while NaN is "not a number" which can be produced when the result of an arithmetic operation can't be defined numerically, e.g. 0/0. I can't see your dframe values, but I would guess that this is the result of taking the row means when all row values are NA, while setting na.rm=TRUE. See the difference between mean(c(NA, NA, NA), na.rm=TRUE) vs. mean(c(NA, NA, NA), na.rm=FALSE). You can leave NaN or decide how to define row means when all row values are negative and have been replaced by NA. </p>
<p>To consider only non-NaN values, you can subset for not NaN using <code>!is.nan</code>, see this example:</p>
<pre><code>mea <- c(2, 4, NaN, 6)
mea
# [1] 2 4 NaN 6
!is.nan(mea) # not NaN, output logical
# [1] TRUE TRUE FALSE TRUE
mea <- mea[!is.nan(mea)]
# [1] 2 4 6
</code></pre>
<p>Or you can replace NaN values with some desired value by setting <code>mea[is.nan(mea)] <- ??</code></p> |
36,197,031 | How to use Moment.JS to check whether the current time is between 2 times | <p>Say the current time is <code>09:34:00</code> (<code>hh:mm:ss</code>), and I have two other times in two variables:</p>
<pre><code>var beforeTime = '08:34:00',
afterTime = '10:34:00';
</code></pre>
<p>How do I use Moment.JS to check whether the current time is between <code>beforeTime</code> and <code>afterTime</code>?</p>
<p>I've seen <a href="http://momentjs.com/docs/#/query/is-between/" rel="noreferrer"><code>isBetween()</code></a>, and I've tried to use it like:</p>
<pre><code>moment().format('hh:mm:ss').isBetween('08:27:00', '10:27:00')
</code></pre>
<p>but that doesn't work because as soon as I format the first (current time) moment into a string, it's no longer a moment object. I've also tried using:</p>
<pre><code>moment('10:34:00', 'hh:mm:ss').isAfter(moment().format('hh:mm:ss')) && moment('08:34:00', 'hh:mm:ss').isBefore(moment().format('hh:mm:ss'))
</code></pre>
<p>but I get <code>false</code>, because again when I format the current time, it's no longer a moment.</p>
<p>How do I get this to work?</p> | 36,197,219 | 4 | 1 | null | 2016-03-24 09:39:14.587 UTC | 6 | 2021-01-08 21:32:16.467 UTC | null | null | null | null | 3,541,881 | null | 1 | 75 | javascript|momentjs | 84,421 | <ul>
<li>You can pass moment instances to <code>isBetween()</code></li>
<li>leave out the <code>format()</code> calls, what you want is to pass parse formats like int the first moment() of your second attempt.</li>
</ul>
<p>That's all:</p>
<pre><code>var format = 'hh:mm:ss'
// var time = moment() gives you current time. no format required.
var time = moment('09:34:00',format),
beforeTime = moment('08:34:00', format),
afterTime = moment('10:34:00', format);
if (time.isBetween(beforeTime, afterTime)) {
console.log('is between')
} else {
console.log('is not between')
}
// prints 'is between'
</code></pre> |
35,939,289 | How to destructure into dynamically named variables in ES6? | <p>Let's suppose I have the following object:</p>
<pre><code>const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
</code></pre>
<p>And that I want only the <code>id</code> and <code>fullName</code>.</p>
<p>I will do the following :</p>
<pre><code>const { id, fullName } = user
</code></pre>
<p>Easy-peasy, right?</p>
<p>Now let's suppose that I want to do the destructuring based on the value of another variable called <code>fields</code>.</p>
<pre><code>const fields = [ 'id', 'fullName' ]
</code></pre>
<p>Now my question is : <strong>How can I do destructuring based on an array of keys?</strong></p>
<p>I shamelessly tried the following without success:</p>
<p><code>let {[{...fields}]} = user</code> and <code>let {[...fields]} = user</code>. Is there any way that this could be done?</p>
<p>Thank you</p> | 39,228,534 | 6 | 2 | null | 2016-03-11 11:36:56.517 UTC | 10 | 2022-07-25 07:30:29.8 UTC | 2016-11-20 02:41:28.87 UTC | user663031 | null | null | 598,416 | null | 1 | 88 | javascript|ecmascript-6 | 38,665 | <p>Short answer: it's impossible and it won't be possible.</p>
<p>Reasoning behind this: it would introduce new dynamically named variables into block scope, effectively being dynamic <code>eval</code>, thus disabling any performance optimization. Dynamic <code>eval</code> that can modify scope in fly was always regarded as extremely dangerous and was removed from ES5 strict mode.</p>
<p>Moreover, it would be a code smell - referencing undefined variables throws <code>ReferenceError</code>, so you would need more boilerplate code to safely handle such dynamic scope.</p> |
19,852,927 | Get Specific Columns Using “With()” Function in Laravel Eloquent | <p>I have two tables, <code>User</code> and <code>Post</code>. One <code>User</code> can have many <code>posts</code> and one <code>post</code> belongs to only one <code>user</code>. </p>
<p>In my <code>User</code> model I have a <code>hasMany</code> relation...</p>
<pre class="lang-php prettyprint-override"><code>public function post(){
return $this->hasmany('post');
}
</code></pre>
<p>And in my <code>post</code> model I have a <code>belongsTo</code> relation...</p>
<pre><code>public function user(){
return $this->belongsTo('user');
}
</code></pre>
<p>Now I want to join these two tables using <code>Eloquent with()</code> but want specific columns from the second table. I know I can use the Query Builder but I don't want to. </p>
<p>When in the <code>Post</code> model I write...</p>
<pre><code>public function getAllPosts() {
return Post::with('user')->get();
}
</code></pre>
<p>It runs the following queries...</p>
<pre><code>select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
</code></pre>
<p>But what I want is...</p>
<pre><code>select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
</code></pre>
<p>When I use...</p>
<pre><code>Post::with('user')->get(array('columns'....));
</code></pre>
<p>It only returns the column from the first table. I want specific columns using <code>with()</code> from the second table. How can I do that?</p> | 19,921,418 | 20 | 0 | null | 2013-11-08 06:30:34.153 UTC | 76 | 2022-09-21 08:57:18.2 UTC | 2018-11-17 16:41:13.96 UTC | null | 633,440 | null | 526,367 | null | 1 | 304 | php|laravel|orm|eloquent|laravel-query-builder | 449,939 | <p>Well I found the solution. It can be done one by passing a <code>closure</code> function in <code>with()</code> as second index of array like</p>
<pre class="lang-php prettyprint-override"><code>Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()
</code></pre>
<p>It will only select <code>id</code> and <code>username</code> from other table. I hope this will help others.</p>
<hr />
<p>Remember that the <strong>primary key (id in this case) needs to be the first param</strong> in the
<code>$query->select()</code> to actually retrieve the necessary results.*</p> |
6,216,653 | how to let tor change ip automatically? | <p>After i click the "Use a New Identify" button on Vidalia, i will get a new proxy ip.
Can tor change ip automatically?</p>
<p>My program needs random proxies, so the server will not block the connection.</p> | 6,405,720 | 3 | 0 | null | 2011-06-02 15:26:19.523 UTC | 13 | 2018-12-30 20:30:55.24 UTC | null | null | null | null | 552,450 | null | 1 | 22 | proxy|tor | 56,550 | <p>You could modify "<strong>/etc/tor/torrc</strong>" or in "path/to/your/torbrowser/<strong>Data/Tor/torrc</strong>" to cycle proxies faster:</p>
<pre><code>MaxCircuitDirtiness NUM
</code></pre>
<p>Feel free to reuse a circuit that was first used at most NUM seconds ago, but never attach a new stream to a circuit that is too old. (Default: 10 minutes)</p> |
6,177,034 | How do I install eclipse PDE? | <p>I have already installed the eclipse IDE for Java developers (Helios Service Release 2) </p>
<p>How do I now install the Plug-in Developers Environment (PDE) on top of that? I thought that it should be possible to install it from an update site, like any other eclipse plug-in. But I can't find the correct update site anywhere.</p> | 6,177,160 | 3 | 1 | null | 2011-05-30 13:38:49.713 UTC | 3 | 2018-12-11 14:06:58.667 UTC | 2018-12-11 14:06:58.667 UTC | null | 9,104,884 | null | 3,306 | null | 1 | 29 | eclipse|installation | 26,492 | <p>Try that in Eclipse:</p>
<p>Help → Install New Software... → Choose <em>The Eclipse Project Updates</em> in field <em>Work With</em> → Filter for <em>RCP Plug-In</em></p>
<p>Then press <kbd>Next</kbd> and follow the instructions!</p> |
2,165,342 | Calling a function from a namespace | <p>I'm trying to alter the functionality of a few commands in a package in R. It's easy enough to see the source of the commands. However the function calls other functions that are in the package namespace. These functions are not exported objects. So how can I access them?</p>
<p>Specific example:</p>
<p>How would I access the asCall() function that is used in copula::rmvdc?</p>
<pre><code>require(copula)
copula::rmvdc
getAnywhere("asCall")
</code></pre>
<p>so <code>as.Call()</code> exists in the copula package, but how do I access it? </p>
<pre><code>> copula::asCall
Error: 'asCall' is not an exported object from 'namespace:copula'
</code></pre> | 2,165,396 | 2 | 0 | null | 2010-01-29 21:39:06.077 UTC | 10 | 2020-03-03 11:32:59.72 UTC | 2020-03-03 11:32:59.72 UTC | null | 680,068 | null | 37,751 | null | 1 | 31 | r|namespaces | 34,721 | <p>Try this:</p>
<pre><code>copula:::asCall
</code></pre>
<p>This was <a href="http://www.mail-archive.com/[email protected]/msg77742.html" rel="noreferrer">previously answered on R-help</a>. That function was not exported in the package namespace, so you need to use the <code>:::</code> operator instead. Typically functions are not exported when they are not intended for general usage (e.g. you don't need to document them in this case).</p> |
1,629,685 | When and how to use GCC's stack protection feature? | <p>I have enabled the <code>-Wstack-protector</code> warning when compiling the project I'm working on (a commercial multi-platform C++ game engine, compiling on Mac OS X 10.6 with GCC 4.2).
This flag warns about functions that will not be protected against stack smashing even though <code>-fstack-protector</code> is enabled.
GCC emits some warnings when building the project:</p>
<blockquote>
<p>not protecting function: no buffer at least 8 bytes long<br>
not protecting local variables: variable length buffer</p>
</blockquote>
<p>For the first warning, I found that it is possible to adjust the minimum size a buffer must have when used in a function, for this function to be protected against stack smashing: <code>--param ssp-buffer-size=X</code> can be used, where X is 8 by default and can be as low as 1.</p>
<p>For the second warning, I can't suppress its occurrences unless I stop using <code>-Wstack-protector</code>.</p>
<ol>
<li>When should <code>-fstack-protector</code> be used? (as in, for instance, all the time during dev, or just when tracking bugs down?) </li>
<li>When should <code>-fstack-protector-all</code> be used? </li>
<li>What is <code>-Wstack-protector</code> telling me? Is it suggesting that I decrease the buffer minimum size? </li>
<li>If so, are there any downsides to putting the size to 1? </li>
<li>It appears that <code>-Wstack-protector</code> is not the kind of flag you want enabled at all times if you want a warning-free build. Is this right?</li>
</ol> | 4,280,418 | 2 | 8 | null | 2009-10-27 09:40:06.007 UTC | 33 | 2022-05-24 15:16:56.547 UTC | 2022-05-24 15:16:56.547 UTC | null | 4,294,399 | null | 123,183 | null | 1 | 69 | c++|gcc|stack | 81,495 | <p>Stack-protection is a hardening strategy, not a debugging strategy. If your game is network-aware or otherwise has data coming from an uncontrolled source, turn it on. If it doesn't have data coming from somewhere uncontrolled, don't turn it on.</p>
<p>Here's how it plays out: If you have a bug and make a buffer change based on something an attacker can control, that attacker can overwrite the return address or similar portions of the stack to cause it to execute their code instead of your code. Stack protection will abort your program if it detects this happening. Your users won't be happy, but they won't be hacked either. This isn't the sort of hacking that is about cheating in the game, it's the sort of hacking that is about someone using a vulnerability in your code to create an exploit that potentially infects your user.</p>
<p>For debugging-oriented solutions, look at things like mudflap.</p>
<p>As to your specific questions:</p>
<ol>
<li>Use stack protector if you get data from uncontrolled sources. The answer to this is probably yes. So use it. Even if you don't have data from uncontrolled sources, you probably will eventually or already do and don't realize it.</li>
<li><p>Stack protections for all buffers can be used if you want extra protection in exchange for some performance hit. From <a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html">gcc4.4.2 manual</a>:</p>
<blockquote>
<blockquote>
<blockquote>
<h3>-fstack-protector</h3>
<p>Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call alloca, and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits.<br></p>
<h3>-fstack-protector-all</h3>
<p>Like -fstack-protector except that all functions are protected. </p>
</blockquote>
</blockquote>
</blockquote></li>
<li><p>The warnings tell you what buffers the stack protection can't protect.</p></li>
<li>It is not necessarily suggesting you decrease your minimum buffer size, and at a size of 0/1, it is the same as stack-protector-all. It is only pointing it out to you so that you can, if you decide redesign the code so that buffer is protected.</li>
<li>No, those warnings don't represent issues, they just point out information to you. Don't use them regularly.</li>
</ol> |
29,297,154 | GitHub: invalid username or password | <p>I have a project hosted on GitHub. I fail when trying to push my modifications on the master. I always get the following error message</p>
<pre><code>Password for 'https://[email protected]':
remote: Invalid username or password.
fatal: Authentication failed for 'https://[email protected]/eurydyce/MDANSE.git/'
</code></pre>
<p>However, setting my ssh key to github seems ok. Indeed, when I do a <code>ssh -T [email protected]</code> I get</p>
<pre><code>Hi eurydyce! You've successfully authenticated, but GitHub does not provide shell access.
</code></pre>
<p>Which seems to indicate that everything is OK from that side (eurydyce being my github username). I strictly followed the instructions given on github and the recommendations of many stack discussion but no way. Would you have any idea of what I may have done wrong?</p> | 29,297,250 | 30 | 2 | null | 2015-03-27 09:23:01.563 UTC | 189 | 2022-08-04 00:06:39.93 UTC | 2021-11-10 13:49:55 UTC | null | 1,201,863 | null | 406,014 | null | 1 | 622 | github | 759,332 | <p><a href="https://[email protected]/eurydyce/MDANSE.git" rel="noreferrer">https://[email protected]/eurydyce/MDANSE.git</a> is not an ssh url, it is an https one (which would require your GitHub account name, instead of '<code>git</code>').</p>
<p>Try to use <code>ssh://[email protected]:eurydyce/MDANSE.git</code> or just <code>[email protected]:eurydyce/MDANSE.git</code></p>
<pre><code>git remote set-url origin [email protected]:eurydyce/MDANSE.git
</code></pre>
<p>The <a href="https://stackoverflow.com/users/406014/pellegrini-eric">OP Pellegrini Eric</a> adds:</p>
<blockquote>
<p>That's what I did in my <code>~/.gitconfig</code> file that contains currently the following entries <code>[remote "origin"] [email protected]:eurydyce/MDANSE.git</code> </p>
</blockquote>
<p>This should not be in your global config (the one in <code>~/</code>).<br>
You could check <code>git config -l</code> in your repo: that url should be declared in the <em>local</em> config: <code><yourrepo>/.git/config</code>.</p>
<p>So make sure you are in the repo path when doing the <code>git remote set-url</code> command.</p>
<hr>
<p>As noted in <a href="https://stackoverflow.com/users/101662/oliver">Oliver</a>'s <a href="https://stackoverflow.com/a/34919582/6309">answer</a>, an HTTPS URL would not use username/password if <a href="https://help.github.com/en/github/authenticating-to-github/securing-your-account-with-two-factor-authentication-2fa" rel="noreferrer">two-factor authentication (2FA)</a> is activated.</p>
<p>In that case, the password should be a <a href="https://help.github.com/en/github/authenticating-to-github/accessing-github-using-two-factor-authentication#using-two-factor-authentication-with-the-command-line" rel="noreferrer">PAT (personal access token)</a> as seen in "<a href="https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line#using-a-token-on-the-command-line" rel="noreferrer">Using a token on the command line</a>".</p>
<p>That applies only for HTTPS URLS, SSH is not affected by this limitation.</p> |
6,034,748 | If Singletons are bad then why is a Service Container good? | <p>We all know how <strong>bad Singletons</strong> are because they hide dependencies and for <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/" rel="noreferrer">other reasons</a>.</p>
<p>But in a framework, there could be many objects that need to be instantiated only once and called <strong>from everywhere</strong> (logger, db etc).</p>
<p>To solve this problem I have been told to use a so called "Objects Manager" (or <a href="http://symfony.com/doc/current/book/service_container.html" rel="noreferrer">Service Container</a> like symfony) that internally stores every reference to Services (logger etc).</p>
<p>But why isn't a Service Provider as bad as a pure Singleton? </p>
<p>Service provider hides dependencies too and they just wrap out the creation of the first istance. So I am really struggling to understand why we should use a service provider instead of singletons.</p>
<p>PS. I know that to not hide dependencies I should use DI (as stated by Misko) </p>
<h2>Add</h2>
<p>I would add: These days singletons aren't that evil, the creator of PHPUnit explained it here:</p>
<ul>
<li><a href="http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html" rel="noreferrer">http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html</a></li>
</ul>
<p>DI + Singleton solves the problem:</p>
<pre><code><?php
class Client {
public function doSomething(Singleton $singleton = NULL){
if ($singleton === NULL) {
$singleton = Singleton::getInstance();
}
// ...
}
}
?>
</code></pre>
<p>that's pretty smart even if this doesn't solve at all every problems.</p>
<p>Other than DI and Service Container <strong>are there any good acceptable</strong> solution to access this helper objects?</p> | 6,034,863 | 5 | 10 | null | 2011-05-17 17:30:38.717 UTC | 34 | 2017-03-27 12:32:12.08 UTC | 2014-01-29 11:25:46.38 UTC | null | 260,080 | null | 496,223 | null | 1 | 95 | php|oop|design-patterns|frameworks | 19,906 | <p>Service Locator is just the lesser of two evils so to say. The "lesser" boiling down to these four differences (<em>at least I can't think of any others right now</em>):</p>
<h3>Single Responsibility Principle</h3>
<p>Service Container does not violate Single Responsibility Principle like Singleton does. Singletons mix object creation and business logic, while the Service Container is strictly responsible for managing the object lifecycles of your application. In that regard Service Container is better.</p>
<h3>Coupling</h3>
<p>Singletons are usually hardcoded into your application due to the static method calls, which leads to <a href="http://sebastian-bergmann.de/archives/885-Stubbing-Hard-Coded-Dependencies.html" rel="noreferrer">tight coupled and hard to mock dependencies</a> in your code. The SL on the other hand is just one class and it can be injected. So while all your classed will depend on it, at least it is a loosely coupled dependency. So unless you implemented the ServiceLocator as a Singleton itself, that's somewhat better and also easier to test. </p>
<p>However, all classes using the ServiceLocator will now depend on the ServiceLocator, which is a form of coupling, too. This can be mitigated by using an interface for the ServiceLocator so you are not bound to a concrete ServiceLocator implementation but your classes will depend on the existence of some sort of Locator whereas not using a ServiceLocator at all increases reuse dramatically.</p>
<h3>Hidden Dependencies</h3>
<p>The problem of hiding dependencies very much exists forth though. When you just inject the locator to your consuming classes, you wont know any dependencies. But in contrast to the Singleton, the SL will usually instantiate all the dependencies needed behind the scenes. So when you fetch a Service, you dont end up like <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/" rel="noreferrer">Misko Hevery in the CreditCard example</a>, e.g. you dont have to instantiate all the depedencies of the dependencies by hand.</p>
<p>Fetching the dependencies from inside the instance is also violating <a href="https://en.wikipedia.org/wiki/Law_of_Demeter" rel="noreferrer">Law of Demeter</a>, which states that you should not dig into collaborators. An instance should only talk to its immediate collaborators. This is a problem with both Singleton and ServiceLocator.</p>
<h3>Global State</h3>
<p>The problem of Global State is also somewhat mitigated because when you instantiate a new Service Locator between tests all the previously created instances are deleted as well (unless you made the mistake and saved them in static attributes in the SL). That doesnt hold true for any global state in classes managed by the SL, of course.</p>
<p>Also see Fowler on <a href="http://www.martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection" rel="noreferrer">Service Locator vs Dependency Injection</a> for a much more in-depth discussion.</p>
<hr>
<p>A note on your update and the linked article by <a href="http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html" rel="noreferrer">Sebastian Bergmann on testing code that uses Singletons</a> : Sebastian does, in no way, suggest that the proposed workaround makes using Singleons less of a problem. It is just one way to make code that otherwise would be impossible to test more testable. But it's still problematic code. In fact, he explicitly notes: "Just Because You Can, Does Not Mean You Should".</p> |
6,014,903 | Getting GMT time with Android | <p>I have been digging into the question for a while in StackOverflow
<a href="https://stackoverflow.com/questions/2818086/android-get-current-utc-time">Android get Current UTC time</a>
and
<a href="https://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java">How can I get the current date and time in UTC or GMT in Java?</a></p>
<p>I have tried two ways to get the current time of my phone in GMT. I am in Spain and the difference is GMT+2. So let's see with an example:
1º attemp: I created a format and applied it to System.currentTimeMillis();</p>
<pre><code> DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = dfgmt.format(new Date());
//Using System.currentTimeMillis() is the same as new Date()
Date dPhoneTime = dfgmt.parse(gmtTime);
Long phoneTimeUTC = dPhoneTime.getTime();
</code></pre>
<p>I need to substract that time to another time, that's why i do the cast to Long.</p>
<pre><code> DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date arrivalDate = df.parse(item.getArrivalDate());
//the String comes from JSON and is for example:"UTC_arrival":"2011-05-16 18:00:00"
//which already is in UTC format. So the DateFormat doesnt have the GMT paramater as dfgmt
diff = arrival.getTime() - phoneTimeUTC ;
</code></pre>
<p>I also tried this:</p>
<pre><code> Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()
</code></pre>
<p>And still I dont get the right difference. But if I do this:</p>
<pre><code> Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()-3600000*2;
</code></pre>
<p>It does work OK.</p>
<p>Any ideas?</p>
<p>Thanks a lot,</p>
<p>David.</p> | 6,184,094 | 6 | 0 | null | 2011-05-16 08:43:11.317 UTC | 3 | 2020-03-30 18:10:48.517 UTC | 2017-05-23 12:09:39.29 UTC | null | -1 | null | 588,925 | null | 1 | 16 | android|date-format|gmt | 56,351 | <p>As far as I read the calendar.getTimeInMillis(); returns the UTC time in millis. I used the following code and compared it to the Epoch in this site <a href="http://www.xav.com/time.cgi" rel="noreferrer">http://www.xav.com/time.cgi</a>. </p>
<pre><code>public int GetUnixTime()
{
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
int utc = (int)(now / 1000);
return (utc);
}
</code></pre>
<p>Giora</p> |
5,607,773 | change a functions argument's values? | <p>This may seem like a stupid question, but would this function actually affect the variable <code>bool</code> (there is greater context to how I'm going to use this, but this is basically what I'm unsure about)? (I am asking specifically about java)</p>
<pre><code>void truifier (boolean bool) {
if (bool == false) {
bool = true;
}
}
</code></pre> | 5,607,862 | 7 | 0 | null | 2011-04-09 20:42:16.59 UTC | 5 | 2021-04-07 20:04:36.65 UTC | null | null | null | null | 641,507 | null | 1 | 18 | java|function | 60,019 | <p>Consider a slightly different example:</p>
<pre><code>public class Test {
public static void main(String[] args) {
boolean in = false;
truifier(in);
System.out.println("in is " + in);
}
public static void truifier (boolean bool) {
if (bool == false) {
bool = true;
}
System.out.println("bool is " + bool);
}
}
</code></pre>
<p>The output from running this program would be:</p>
<pre><code>bool is true
in is false
</code></pre>
<p>The <code>bool</code> variable would be changed to true, but as soon as the <code>truifier</code> method returned, that argument variable goes away (this is what people mean when they say that it "falls out of scope"). The <code>in</code> variable that was passed in to the <code>truifier</code> method, however, remains unchanged.</p> |
6,126,066 | Search for highest key/index in an array | <p>How can I get the <strong>highest</strong> <code>key/index</code> in an array with <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a>? I know how to do it for the values.</p>
<p>E.g.: from this array I would like to get <code>10</code> as an <code>integer</code> value:</p>
<pre class="lang-php prettyprint-override"><code>$arr = array(1 => "A", 10 => "B", 5 => "C");
</code></pre>
<p>I know how I could code it but I was asking myself if there is a function for this as well.</p> | 6,126,131 | 7 | 0 | null | 2011-05-25 14:30:26.643 UTC | 15 | 2021-09-21 19:02:49.153 UTC | 2021-07-18 07:19:08.03 UTC | null | 1,998,801 | null | 128,753 | null | 1 | 102 | php|arrays|key|highest | 119,546 | <p>This should work fine </p>
<pre><code>$arr = array( 1 => "A", 10 => "B", 5 => "C" );
max(array_keys($arr));
</code></pre> |
5,603,625 | How to check if a HANDLE is valid or not? | <p>In C++, I have opened a serial port that has a <code>HANDLE</code>. Since the port may close by an external application, how can I verify that the <code>HANDLE</code> is still valid before reading data?</p>
<p>I think it can be done by checking the <code>HANDLE</code> against a suitable API function, but which?
Thank you.</p> | 5,603,845 | 8 | 5 | null | 2011-04-09 07:45:06.517 UTC | 2 | 2021-08-18 10:32:58.063 UTC | 2014-07-03 07:43:08.003 UTC | null | 1,244,630 | null | 434,186 | null | 1 | 20 | c++|c|winapi|port|handle | 60,874 | <p>Checking to see whether a handle is "valid" is a mistake. You need to have a better way of dealing with this.</p>
<p>The problem is that once a handle has been closed, the same handle value can be generated by a new open of something different, and your test might say the handle is valid, but you are not operating on the file you think you are.</p>
<p>For example, consider this sequence:</p>
<ol>
<li>Handle is opened, actual value is 0x1234</li>
<li>Handle is used and the value is passed around</li>
<li>Handle is closed.</li>
<li>Some other part of the program opens a file, gets handle value 0x1234</li>
<li>The original handle value is "checked for validity", and passes.</li>
<li>The handle is used, operating on the wrong file.</li>
</ol>
<p>So, if it is your process, you need to keep track of which handles are valid and which ones are not. If you got the handle from some other process, it will have been put into your process using DuplicateHandle(). In that case, you should manage the lifetime of the handle and the source process shouldn't do that for you. If your handles are being closed from another process, I assume that you are the one doing that, and you need to deal with the book keeping.</p> |
6,113,746 | Naming threads and thread-pools of ExecutorService | <p>Let's say I have an application that utilizes the <code>Executor</code> framework as such</p>
<pre><code>Executors.newSingleThreadExecutor().submit(new Runnable(){
@Override
public void run(){
// do stuff
}
}
</code></pre>
<p>When I run this application in the debugger, a thread is created with the following (default) name: <code>Thread[pool-1-thread-1]</code>. As you can see, this isn't terribly useful and as far as I can tell, the <code>Executor</code> framework does not provide an easy way to name the created threads or thread-pools.</p>
<p>So, how does one go about providing names for the threads/thread-pools? For instance, <code>Thread[FooPool-FooThread]</code>.</p> | 6,113,801 | 20 | 0 | null | 2011-05-24 16:33:46.277 UTC | 61 | 2021-12-01 02:19:32.523 UTC | 2016-02-06 10:02:43.497 UTC | null | 4,999,394 | null | 584,862 | null | 1 | 278 | java|threadpool|runnable|executorservice|managedthreadfactory | 170,148 | <p>You could supply a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html" rel="noreferrer"><code>ThreadFactory</code></a> to <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadScheduledExecutor%28java.util.concurrent.ThreadFactory%29" rel="noreferrer"><code>newSingleThreadScheduledExecutor(ThreadFactory threadFactory)</code></a>. The factory will be responsibe for creating threads, and will be able to name them.</p>
<p>To quote the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">Javadoc</a>:</p>
<blockquote>
<p>Creating new threads</p>
<p>New threads are created using a <code>ThreadFactory</code>. If not otherwise specified, a <code>Executors.defaultThreadFactory()</code> is used, that creates threads to all be in the same <code>ThreadGroup</code> and with the same <code>NORM_PRIORITY</code> priority and non-daemon status. By supplying a different <code>ThreadFactory</code>, you can alter the thread's name, thread group, priority, daemon status, etc. If a <code>ThreadFactory</code> fails to create a thread when asked by returning null from <code>newThread</code>, the executor will continue, but might not be able to execute any tasks</p>
</blockquote> |
46,396,827 | dump() missing 1 required positional argument: 'fp' in python json | <p>I am trying to prettify the json format but i am getting this error:</p>
<pre><code>import requests as tt
from bs4 import BeautifulSoup
import json
get_url=tt.get("https://in.pinterest.com/search/pins/?rs=ac&len=2&q=batman%20motivation&eq=batman%20moti&etslf=5839&term_meta[]=batman%7Cautocomplete%7Cundefined&term_meta[]=motivation%7Cautocomplete%7Cundefined")
soup=BeautifulSoup(get_url.text,"html.parser")
select_css=soup.select("script#jsInit1")[0]
for i in select_css:
print(json.dump(json.loads(i),indent=4,sort_keys=True))
</code></pre>
<p>Basically i want to extract this type of element :</p>
<pre><code>'orig': {'width': 1080, 'url': '', 'height': 1349},
</code></pre>
<p>I know i can do this with </p>
<pre><code>select_css.get('orig').get('url')
</code></pre>
<p>But i am not sure is this json element is nested element under any element ? That's why i am trying to prettify to get idea.</p> | 46,396,854 | 2 | 1 | null | 2017-09-25 02:34:24.88 UTC | 6 | 2021-12-26 19:47:38.527 UTC | null | null | null | null | 5,904,928 | null | 1 | 70 | python|json|python-2.7|python-3.x | 136,309 | <p>Use <code>json.dumps()</code> instead. <code>json.dump()</code> needs a file object and dump JSON to it.</p> |
46,318,714 | How do I generate a python timestamp to a particular format? | <p>In python, how would I generate a timestamp to this specific format?</p>
<p>2010-03-20T10:33:22-07</p>
<p>I've searched high and low, but I couldn't find the correct term that describes generating this specific format.</p> | 46,319,906 | 2 | 1 | null | 2017-09-20 09:48:05.37 UTC | 3 | 2020-12-20 00:22:40.793 UTC | 2020-12-20 00:22:40.793 UTC | null | 1,783,163 | null | 3,768,071 | null | 1 | 36 | python|timestamp | 54,953 | <p>See the following example:</p>
<pre><code>import datetime
now = datetime.datetime.now()
now.strftime('%Y-%m-%dT%H:%M:%S') + ('-%02d' % (now.microsecond / 10000))
</code></pre>
<p>This could result in the following:
'2017-09-20T11:52:32-98'</p> |
39,204,589 | Trying to understand lambdas | <p>Trying to understand lambdas in C++, what I do not understand is this:</p>
<pre><code>int multiplier = 5;
auto timesFive = [multiplier](int a) { return a * multiplier; };
std::cout << timesFive(2) << '\n'; // Prints 10
multiplier = 15;
std::cout << timesFive(2) << '\n'; // Still prints 2*5 == 10 (???) - Should it be 30?
</code></pre>
<p>When the program calls the <code>timesFive()</code> the second time, I expect the result to be 30. But why is the result <code>Still prints 2*5 == 10</code>, not <code>prints 2*15 == 30</code>? Perhaps the lambda function somehow cannot track the value of <code>multiplier</code>, even though we have already tried to capture it?</p>
<p>And what is the way to get the desired result?</p> | 39,204,627 | 2 | 1 | null | 2016-08-29 10:58:25.687 UTC | 4 | 2017-09-26 07:01:05.87 UTC | 2017-09-26 07:01:05.87 UTC | null | 15,168 | user2015064 | null | null | 1 | 57 | c++|lambda | 4,328 | <p>You captured <code>multiplier</code> by value, which means it was copied into the lambda. You need to capture it by reference:</p>
<pre><code>int multiplier = 5;
auto timesFive = [&multiplier](int a) { return a * multiplier; };
std::cout << timesFive(2);
multiplier = 15;
std::cout << timesFive(2);
</code></pre> |
44,602,410 | Angular FormControl valueChanges doesn't work | <p>I want to get one of my forms ("family") value if changed by subscribing but it seems something is wrong because I got nothing on my console's log.</p>
<pre class="lang-ts prettyprint-override"><code>import { Component , AfterViewInit } from '@angular/core';
import {FormGroup,FormBuilder} from '@angular/forms';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'app-root',
template: `<form [formGroup]="frm1">
<input type="text" formControlName="name" >
<input type="text" formControlName="family">
</form>
`,
})
export class AppComponent implements AfterViewInit{
frm1 : FormGroup;
constructor( fb:FormBuilder){
this.frm1 = fb.group({
name : [],
family: []
});
}
ngAfterViewInit(){
var search = this.frm1.controls.family;
search.valueChanges.subscribe( x => console.log(x));
}
}
</code></pre> | 44,602,483 | 3 | 1 | null | 2017-06-17 08:27:51.78 UTC | 2 | 2021-08-18 12:06:07.06 UTC | 2021-03-05 12:09:18.383 UTC | null | 74,089 | null | 8,140,517 | null | 1 | 17 | angular|angular2-forms|angular2-formbuilder | 56,193 | <p>Use <code>get</code> method on form variable <code>frm1</code>. And use <code>ngOnInit()</code> instead of <code>ngAfterViewInit()</code> </p>
<pre><code>ngOnInit() {
this.frm1.get('family').valueChanges.subscribe( x => console.log(x));
}
</code></pre> |
21,921,589 | Where is the extra 75 seconds coming from? | <p>While writing some unit tests on a Julian Day calculator, I found that dates prior to 2nd December 1847 were being initialised incorrectly by NSDate. They appear to have 75 seconds added on. I haven't been able to find anything pointing to that date (which is well after the Gregorian calendar cutoff). Is it a bug or is there a historic calendar adjustment that I've not come across?</p>
<pre><code>int main(int argc, const char * argv[])
{
@autoreleasepool {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dateComps = [NSDateComponents new];
dateComps.year = 1847;
dateComps.month = 12;
dateComps.day = 1;
NSDate *d1 = [cal dateFromComponents:dateComps];
NSLog(@"d1 = %@", d1);
dateComps = [NSDateComponents new];
dateComps.year = 1847;
dateComps.month = 12;
dateComps.day = 2;
NSDate *d2 = [cal dateFromComponents:dateComps];
NSLog(@"d2 = %@", d2);
}
return 0;
}
</code></pre>
<p>Output:</p>
<p>d1 = 1847-12-01 00:01:15 +0000</p>
<p>d2 = 1847-12-02 00:00:00 +0000</p> | 21,921,744 | 4 | 1 | null | 2014-02-20 23:00:06.32 UTC | 5 | 2014-04-18 19:08:12.44 UTC | 2014-02-20 23:02:46.76 UTC | null | 1,226,963 | null | 2,215,831 | null | 1 | 45 | objective-c|nsdate|nsdatecomponents | 5,668 | <p>According to <a href="http://www.timeanddate.com/worldclock/clockchange.html?n=136&year=1847">http://www.timeanddate.com/worldclock/clockchange.html?n=136&year=1847</a> there was a time shift forward of 75 seconds at that time.</p>
<p>In London, when local time was about to reach 12:00:00 AM on Wednesday December 1, 1847, clocks were advanced to Wednesday, December 1, 1847 12:01:15 AM.</p> |
51,254,946 | Cypress does not always executes click on element | <p>I am automating Google Calculator.
And from time to time Cypress is not able to execute click on button.
The tests click on buttons (0 to 9 ) and do some simple math operations.
And in 30% chance it can not click on element and the test will fail. </p>
<p>I also recorded a video when issue appears.</p>
<p><a href="https://vimeo.com/user87137353/review/279153050/bfd1c8ff7a" rel="noreferrer">Video here</a></p>
<p>My Project is located here:
<a href="https://github.com/afiliptsov/test-project" rel="noreferrer">https://github.com/afiliptsov/test-project</a></p>
<pre><code>To run the test run : "npm run test:e2e:functional"
</code></pre>
<p>I tried to use different locator. Initially i was using just ID ex(#cwbt15 ) but after i made more specific locator ( <strong>#cwbt15 > .cwbtpl > .cwbts</strong>) and still having same issue.</p>
<p>Does anyone knows why it happens and how to avoid such behavior? </p>
<p>The project structure is :</p>
<ul>
<li><strong>cypress/PageObject.js</strong> - place where all elements declared.</li>
<li><strong>cypress/support/commands.js</strong> - place where function click created and
verification of value getting updated.</li>
<li><strong>cypress/integration/functional/delete.spec.js</strong> - test which was on the
video</li>
</ul> | 66,371,021 | 10 | 1 | null | 2018-07-09 22:38:15.483 UTC | 4 | 2022-09-02 13:43:13.087 UTC | 2018-07-10 20:18:46.257 UTC | null | 6,865,465 | null | 6,865,465 | null | 1 | 34 | javascript|testing|automated-tests|cypress | 49,108 | <p>2022 here and tested with cypress version: <code>"6.x.x"</code> until <code>"10.x.x"</code></p>
<p>You could use <code>{ force: true }</code> like:</p>
<pre><code>cy.get("YOUR_SELECTOR").click({ force: true });
</code></pre>
<p>but this might not solve it ! <strong>The problem might be more complex</strong>, that's why check below</p>
<p><strong>My solution:</strong></p>
<pre><code>cy.get("YOUR_SELECTOR").trigger("click");
</code></pre>
<p><strong>Explanation:</strong></p>
<p>In my case, I needed to watch a bit deeper what's going on. I started by pin the <code>click</code> action like this:</p>
<p><a href="https://i.stack.imgur.com/laXvy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/laXvy.png" alt="enter image description here" /></a></p>
<p>Then watch the console, and you should see something like:
<a href="https://i.stack.imgur.com/yXfkk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yXfkk.png" alt="enter image description here" /></a></p>
<p>Now click on line <code>Mouse Events</code>, it should display a table:
<a href="https://i.stack.imgur.com/zkMXG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zkMXG.png" alt="enter image description here" /></a></p>
<p>So basically, when Cypress executes the <code>click</code> function, it triggers all those events but somehow my component behave the way that it is detached the moment where <code>click event</code> is triggered.</p>
<p>So I just simplified the click by doing:</p>
<pre><code>cy.get("YOUR_SELECTOR").trigger("click");
</code></pre>
<p>And it worked </p>
<p>Hope this will fix your issue or at least help you debug and understand what's wrong.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.