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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,350,886 | How to iterate through a list of numbers in c++ | <p>How do I iterate through a list of numbers, and how many different ways are there to do it?</p>
<p>What I thought would work:</p>
<pre><code>#include <cstdlib>
#include <iostream>
#include <list>
using namespace std;
int main()
{
int numbers[] = {2, 4, 6, 8};
int i = 0;
for(i=0; i< numbers.size();i++)
cout << "the current number is " << numbers[i];
system("pause");
return 0;
}
</code></pre>
<p>I get an error on the for loop line:</p>
<blockquote>
<p>request for member <code>'size'</code> in <code>'numbers'</code>, which is of non-class type <code>'int[4]'</code></p>
</blockquote> | 14,351,046 | 9 | 3 | null | 2013-01-16 03:24:40.38 UTC | 5 | 2021-10-29 08:14:59.17 UTC | 2016-02-16 13:53:10.84 UTC | null | 476,496 | null | 625,354 | null | 1 | 8 | c++ | 52,924 | <p>Unlike a lot of modern languages plain C++ arrays don't have a <code>.size()</code> function. You have a number of options to iterate through a list depending on the storage type.</p>
<p>Some common options for storage include:</p>
<pre><code>// used for fixed size storage. Requires #include <array>
std::array<type, size> collection;
// used for dynamic sized storage. Requires #include <vector>
std::vector<type> collection;
// Dynamic storage. In general: slower iteration, faster insert
// Requires #include <list>
std::list<type> collection;
// Old style C arrays
int myarray[size];
</code></pre>
<p>Your options for iteration will depend on the type you're using. If you're using a plain old C array you can either store the size somewhere else or calculate the size of the array based on the size of it's types. <a href="https://stackoverflow.com/a/4162948/203133">Calculating the size of an array has a number of drawbacks outlined in this answer by DevSolar</a></p>
<pre><code>// Store the value as a constant
int oldschool[10];
for(int i = 0; i < 10; ++i) {
oldschool[i]; // Get
oldschool[i] = 5; // Set
}
// Calculate the size of the array
int size = sizeof(oldschool)/sizeof(int);
for(int i = 0; i < size; ++i) {
oldschool[i]; // Get
oldschool[i] = 5; // Set
}
</code></pre>
<p>If you're using any type that provides a <code>.begin()</code> and <code>.end()</code> function you can use those to get an iterator which is considered good style in C++ compared to index based iteration:</p>
<pre><code>// Could also be an array, list, or anything with begin()/end()
std::vector<int> newschool;
// Regular iterator, non-C++11
for(std::vector<int>::iterator num = newschool.begin(); num != newschool.end(); ++num) {
int current = *num; // * gets the number out of the iterator
*num = 5; // Sets the number.
}
// Better syntax, use auto! automatically gets the right iterator type (C++11)
for(auto num = newschool.begin(); num != newschool.end(); ++num) {
int current = *num; // As above
*num = 5;
}
// std::for_each also available
std::for_each(newschool.begin(), newschool.end(), function_taking_int);
// std::for_each with lambdas (C++11)
std::for_each(newschool.begin(), newschool.end(), [](int i) {
// Just use i, can't modify though.
});
</code></pre>
<p>Vectors are also special because they are designed to be drop-in replacements for arrays. You can iterate over a vector exactly how you would over an array with a <code>.size()</code> function. However this is considered bad practice in C++ and you should prefer to use iterators where possible:</p>
<pre><code>std::vector<int> badpractice;
for(int i = 0; i < badpractice.size(); ++i) {
badpractice[i]; // Get
badpractice[i] = 5; // Set
}
</code></pre>
<p>C++11 (the new standard) also brings the new and fancy range based for that should work on any type that provides a <code>.begin()</code> and <code>.end()</code>. However: Compiler support can vary for this feature. You can also use <code>begin(type)</code> and <code>end(type)</code> as an alternative.</p>
<pre><code>std::array<int, 10> fancy;
for(int i : fancy) {
// Just use i, can't modify though.
}
// begin/end requires #include <iterator> also included in most container headers.
for(auto num = std::begin(fancy); num != std::end(fancy); ++num) {
int current = *num; // Get
*num = 131; // Set
}
</code></pre>
<p><code>std::begin</code> also has another interesting property: it works on raw arrays. This means you can use the same iteration semantics between arrays and non-arrays (you should still prefer standard types over raw arrays):</p>
<pre><code>int raw[10];
for(auto num = std::begin(raw); num != std::end(raw); ++num) {
int current = *num; // Get
*num = 131; // Set
}
</code></pre>
<p>You also need to be careful if you want to delete items from a collection while in a loop because calling <code>container.erase()</code> makes all existing iterators invalid:</p>
<pre><code>std::vector<int> numbers;
for(auto num = numbers.begin(); num != numbers.end(); /* Intentionally empty */) {
...
if(someDeleteCondition) {
num = numbers.erase(num);
} else {
// No deletition, no problem
++num;
}
}
</code></pre>
<p>This list is far from comprehensive but as you can see there's a lot of ways of iterating over a collection. In general prefer iterators unless you have a good reason to do otherwise.</p> |
14,189,995 | Create an event to watch for a change of variable | <p>Let's just say that I have:</p>
<pre><code>public Boolean booleanValue;
public bool someMethod(string value)
{
// Do some work in here.
return booleanValue = true;
}
</code></pre>
<p>How can I create an event handler that fires up when the booleanValue has changed? Is it possible?</p> | 14,190,043 | 6 | 2 | null | 2013-01-07 04:43:51.617 UTC | 5 | 2013-09-30 19:19:18.8 UTC | 2013-09-30 19:19:18.8 UTC | null | 649,524 | null | 1,401,515 | null | 1 | 11 | c#|.net|event-handling|microsoft-metro|inotifypropertychanged | 38,784 | <p>Avoid using public fields as a rule in general. Try to keep them private as much as you can. Then, you can use a wrapper property firing your event. See the example:</p>
<pre><code>class Foo
{
Boolean _booleanValue;
public bool BooleanValue
{
get { return _booleanValue; }
set
{
_booleanValue = value;
if (ValueChanged != null) ValueChanged(value);
}
}
public event ValueChangedEventHandler ValueChanged;
}
delegate void ValueChangedEventHandler(bool value);
</code></pre>
<p>That is one simple, "native" way to achieve what you need. There are other ways, even offered by the .NET Framework, but the above approach is just an example.</p> |
13,863,087 | Wordpress custom widget image upload | <p>I'm busy with building my own Wordpress Widget. Everything works fine except for the Wordpress media up loader.
I have created eight buttons and eight input text fields which should contain the url of the image that has been uploaded.</p>
<p>The click event is not being fired, probably because Wordpress outputs the HTML twice(Once in the bar of the available widgets and once in the bar currently active widgets).</p>
<p>Does anybody sees what I'm doing wrong?</p>
<p>Below you find my code. </p>
<p>Thanks in advance for the help!</p>
<pre><code><?php
/*
Plugin Name: Home_Rollover_Widget
Plugin URI:
Description: Home Rollover Widget
Version: 1.0
Author:
Author URI:
*/
// Initialize widget
add_action('widgets_init', array('Home_Rollover_Widget', 'register'));
/**
* Home_Rollover_Widget
*
* @package
* @author
* @copyright 2012
* @version $Id$
* @access public
*/
class Home_Rollover_Widget extends WP_Widget
{
/**
* __construct()
*
* @return void
*/
public function __construct()
{
parent::__construct('home-rollover-widget');
}
/**
* control()
*
* @return void
*/
public function control()
{
// Load upload an thickbox script
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
// Load thickbox CSS
wp_enqueue_style('thickbox');
// Load all widget options
$data = get_option('Home_Rollover_Widget');
?>
<!-- Widget title -->
<p><label>Titel<input name="home_rollover_widget_title" type="text" value="<?php echo $data['home_rollover_widget_title']; ?>" /></label></p>
<?php
// If there's a title provided, update it.
if (isset($_POST['home_rollover_widget_title'])){
$data['home_rollover_widget_title'] = attribute_escape($_POST['home_rollover_widget_title']);
}
// Show 8 input groups for image URL and text
for ($i = 1; $i <= 8; ++$i)
{
?>
<p><a href="#" id="upload-button-<?php echo $i; ?>">UPLOAD IMAGE</a></p>
<p><label>IMAGE <?php echo $i; ?><input id="home_rollover_widget_image_url_<?php echo $i; ?>" name="home_rollover_widget_image_url_<?php echo $i; ?>" type="text" value="<?php echo $data['home_rollover_widget_image_url_'.$i]; ?>" /></label></p>
<p><label>TEXT <?php echo $i; ?><input name="home_rollover_widget_text_<?php echo $i; ?>" type="text" value="<?php echo $data['home_rollover_widget_text_'.$i]; ?>" /></label></p>
<?php
// If there's an URL provided, update it.
if (isset($_POST['home_rollover_widget_image_url_'.$i])){
$data['home_rollover_widget_image_url_1'] = attribute_escape($_POST['home_rollover_widget_image_url_'.$i]);
}
// if there's a text provided, update it.
if (isset($_POST['home_rollover_widget_text_'.$i])) {
$data['home_rollover_widget_text_1'] = attribute_escape($_POST['home_rollover_widget_text_'.$i]);
}
?>
<script type="text/javascript">
var formField = '';
var imgUrl ='';
jQuery(document).ready(function() {
jQuery('#upload-button-<?php echo $i; ?>').click(function() {
alert('Clicked on upload button');
formField = jQuery('#upload-button-<?php echo $i; ?>').attr('name');
tb_show('', 'media-upload.php?type=image&amp&TB_iframe=1');
return false;
});
// send url back to plugin editor
window.send_to_editor = function(html) {
imgUrl = jQuery('img',html).attr('src');
alert('Sending image url'+imgUrl+' to text field');
jQuery('#home_rollover_widget_image_url_<?php echo $i; ?>').val(imgUrl);
tb_remove();
}
});
</script>
<hr />
<?php
}
// Update widget data
update_option('Home_Rollover_Widget', $data);
}
/**
* widget()
*
* @param mixed $args
* @return void
*/
function widget($args)
{
// Load all widget options
$data = get_option('Home_Rollover_Widget');
?>
<h4><?php echo $data['home_rollover_widget_title']; ?></h4>
<div id="all">
<?php
// Loop though the widget elements
for ($i = 1; $i <= 8; ++$i)
{
// Find image URL
$imageUrl = $data['home_rollover_widget_image_url_'.$i];
// Check for first slash, if not present, add it.
if (substr($imageUrl, 0, 1) != '/') {
$imageUrl = '/'.$imageUrl;
}
?>
<ul>
<li><a href="#"><img src="<?php echo get_template_directory_uri(); ?><?php echo $imageUrl; ?>" /><h4><?php echo $data['home_rollover_widget_text_'.$i]; ?></h4></a></li>
</ul>
<?php
}
?>
</div>
<?php
}
/**
* register()
*
* @return void
*/
function register()
{
// Register for sidebar
register_sidebar_widget('Home Rollover Widget', array('Home_Rollover_Widget', 'widget'));
// Register for control panel
register_widget_control('Home Rollover Widget', array('Home_Rollover_Widget', 'control'));
}
}
</code></pre> | 13,931,093 | 2 | 3 | null | 2012-12-13 15:27:57.81 UTC | 11 | 2013-11-22 00:19:06.043 UTC | 2012-12-13 15:47:23.27 UTC | null | 2,111,178 | null | 2,111,178 | null | 1 | 15 | javascript|html|wordpress | 25,658 | <p>I have simplified the widget a little for this example, removing the for loop as I think you could just create new instances of the widget. This also allows the added benefit of sorting the items. I moved the js to another file as there's no need to repeat the code.</p>
<p>The widget class</p>
<pre><code>class Home_Rollover_Widget extends WP_Widget
{
public function __construct()
{
parent::__construct(
'home-rollover-widget',
'Home Rollover Widget',
array(
'description' => 'Home rollover widget'
)
);
}
public function widget( $args, $instance )
{
// basic output just for this example
echo '<a href="#">
<img src="'.esc_url($instance['image_uri']).'" />
<h4>'.esc_html($instance['image_uri']).'</h4>
</a>';
}
public function form( $instance )
{
// removed the for loop, you can create new instances of the widget instead
?>
<p>
<label for="<?php echo $this->get_field_id('text'); ?>">Text</label><br />
<input type="text" name="<?php echo $this->get_field_name('text'); ?>" id="<?php echo $this->get_field_id('text'); ?>" value="<?php echo $instance['text']; ?>" class="widefat" />
</p>
<p>
<label for="<?php echo $this->get_field_id('image_uri'); ?>">Image</label><br />
<input type="text" class="img" name="<?php echo $this->get_field_name('image_uri'); ?>" id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php echo $instance['image_uri']; ?>" />
<input type="button" class="select-img" value="Select Image" />
</p>
<?php
}
}
// end class
// init the widget
add_action( 'widgets_init', create_function('', 'return register_widget("Home_Rollover_Widget");') );
// queue up the necessary js
function hrw_enqueue()
{
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
// moved the js to an external file, you may want to change the path
wp_enqueue_script('hrw', '/wp-content/plugins/home-rollover-widget/script.js', null, null, true);
}
add_action('admin_enqueue_scripts', 'hrw_enqueue');
</code></pre>
<p>New js file: use the <code>.on()</code> method instead of <code>.click()</code> to attach the event handler.</p>
<pre><code>var image_field;
jQuery(function($){
$(document).on('click', 'input.select-img', function(evt){
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = $('img', html).attr('src');
image_field.val(imgurl);
tb_remove();
}
});
</code></pre> |
13,985,769 | PL/SQL developer with oracle 32-bit/64-bit client | <p>I have Oracle 64-bit client installed to run with my weblogic application. I learnt that pl-sql developer doesn't work with oracle 64-bit client so now i have both 32-bit and 64-bit clients installed on my machine and my ORACLE_HOME variable points to 64-bit client.</p>
<p>I am not able to start pl/sql developer even i specify the 32-bit client in Tools->Preferences of pl-sql developer version 8.0.4.</p>
<p>I changed my oracle client to 32-bit client then i was able to start pl-sql developer but my application doesn't work.</p>
<p>Is there a way i can run PL/SQL developer whilst pointing ORACLE_HOME to 64-bit oracle client. I am not sure specifying the ORACLE_HOME explicitly in Tools->Preferences of pl sql developer (for user/default as well as system preferences) has any effect as it picks the oracle home from the environment variable i believe.</p>
<p>Thanks,
Adithya.</p> | 15,614,038 | 4 | 0 | null | 2012-12-21 07:06:00.5 UTC | 12 | 2020-06-19 19:23:51.34 UTC | null | null | null | null | 533,463 | null | 1 | 17 | plsqldeveloper|oracleclient | 105,866 | <p>You'll need to install the two clients into separate Oracle Home locations, for example I've gone for <code>C:\OracleHome</code> and <code>C:\OracleHome32</code></p>
<p>Then set up an Environment Variable, called TNS_ADMIN with the folder that contains your default TNSnames.ora file as the value (for me it is <code>C:\OracleHome\network\admin</code>)</p>
<p>Keep your preferences in PL/SQL Developer, and make sure you also specify the OCI library (mine is <code>C:\OracleHome32\oci.dll</code>)</p>
<p>Finally, using regedit.exe, add a second key under ORACLE (<code>HKEY_LOCAL_MACHHINE\SOFTWARE\ORACLE</code>). I've called mine KEY_OraClient11g_home1 and KEY_OraClient11g_home2. Create the same 4 strings in the second key, with the appropriate changes to the data (e.g. ORACLE_HOME should have <code>C:\OracleHome32</code> as it's data field in my example)</p>
<p>Restarting all applications should now let you use PL/SQL Developer seamlessly, whilst also defaulting to the 64-bit Oracle home for your weblogic application.</p> |
14,015,108 | How to set default value of variable in live template in Intellij IDEA? | <p>There could be a little misunterstanding in live templates in Intellij IDEA. I mean default values for variables in templates.</p>
<p>Suppose we have this live template</p>
<p><img src="https://i.stack.imgur.com/fRGs4.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/vznZJ.png" alt="enter image description here"></p>
<p>What I expect here, that when calling this template (type <em>jqon</em> and press <em>TAB</em>) I will see default values already typed which I can change or leave as it is. Like this</p>
<p><img src="https://i.stack.imgur.com/FCfS6.png" alt="enter image description here"></p>
<p>But no. I have empty strings instead of default values</p>
<p><img src="https://i.stack.imgur.com/rsjRF.png" alt="enter image description here"></p>
<p>Why?</p> | 14,015,110 | 2 | 0 | null | 2012-12-23 22:10:44.86 UTC | 3 | 2015-05-23 22:07:30.53 UTC | null | null | null | null | 1,146,469 | null | 1 | 42 | intellij-idea|live-templates | 8,445 | <p>I was wrong about <em>Default value</em> field. I don't need this in my case. I need to fill <em>Expression</em> field. </p>
<p>If I want just paste some string as default value I should put this string in quote in <em>Expression</em>. So now my variable settings look this way</p>
<p><img src="https://i.stack.imgur.com/4PsxF.png" alt="enter image description here"></p>
<p>And everything works how I want!</p> |
13,942,701 | Take a char input from the Scanner | <p>I am trying to find a way to take a <code>char</code> input from the keyboard.</p>
<p>I tried using:</p>
<pre><code>Scanner reader = new Scanner(System.in);
char c = reader.nextChar();
</code></pre>
<p>This method doesn't exist.</p>
<p>I tried taking <code>c</code> as a <code>String</code>. Yet, it would not always work in every case, since the other method I am calling from my method requires a <code>char</code> as an input. Therefore I have to find a way to explicitly take a char as an input.</p>
<p>Any help?</p> | 13,942,707 | 24 | 0 | null | 2012-12-18 22:42:20.907 UTC | 65 | 2021-10-19 07:10:44.333 UTC | 2015-04-06 00:54:25.2 UTC | null | 2,891,664 | null | 1,804,697 | null | 1 | 138 | java|input|char|java.util.scanner | 1,062,533 | <p>You could take the first character from <code>Scanner.next</code>:</p>
<pre><code>char c = reader.next().charAt(0);
</code></pre>
<p>To consume <em>exactly</em> one character you could use:</p>
<pre><code>char c = reader.findInLine(".").charAt(0);
</code></pre>
<p>To consume <em>strictly</em> one character you could use:</p>
<pre><code>char c = reader.next(".").charAt(0);
</code></pre> |
13,872,048 | Bash Script : what does #!/bin/bash mean? | <p>In bash script, what does <code>#!/bin/bash</code> at the 1st line mean ?</p>
<p><strong>UPDATE</strong>: Is there a difference between <code>#!/bin/bash</code> and <code>#!/bin/sh</code> ?</p> | 13,872,064 | 3 | 0 | null | 2012-12-14 03:03:29.317 UTC | 50 | 2016-12-27 16:42:41.517 UTC | null | null | null | null | 188,331 | null | 1 | 147 | bash | 367,495 | <p>That is called a <a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">shebang</a>, it tells the shell what program to interpret the script with, when executed.</p>
<p>In your example, the script is to be interpreted and run by the <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">bash</a> shell.</p>
<p>Some other example shebangs are:</p>
<p>(From Wikipedia)</p>
<pre><code>#!/bin/sh β Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh β Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T β Execute using Perl with the option for taint checks
#!/usr/bin/php β Execute the file using the PHP command line interpreter
#!/usr/bin/python -O β Execute using Python with optimizations to code
#!/usr/bin/ruby β Execute using Ruby
</code></pre>
<p>and a few additional ones I can think off the top of my head, such as:</p>
<pre><code>#!/bin/ksh
#!/bin/awk
#!/bin/expect
</code></pre>
<p>In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.</p>
<p><strong>Response to updated portion:</strong></p>
<p>It depends on what <code>/bin/sh</code> actually points to on your system. Often it is just a symlink to <code>/bin/bash</code>. Sometimes portable scripts are written with <code>#!/bin/sh</code> just to signify that it's a shell script, but it uses whichever shell is referred to by <code>/bin/sh</code> on that particular system (maybe it points to <code>/bin/bash</code>, <code>/bin/ksh</code> or <code>/bin/zsh</code>)</p> |
43,865,079 | Spring JPA - Find By EmbeddedId partially | <p>Below code is for demo purpose only.</p>
<p>My <em>Entity</em> bean looks like this</p>
<pre><code>@Entity
class Employee {
@EmbeddedId
private EmployeeKey employeeKey;
private String firstName;
private String lastName;
// Other fields
// Getter and Setters
}
</code></pre>
<p>The <em>Embeddable</em> class:</p>
<pre><code>@Embeddable
class EmployeeKey implements Serializable {
private int employeeId;
private String branchName;
private String departmentName;
//Getter and Setters
}
</code></pre>
<hr>
<p>I can write <em>JPARepository</em> interface method to find Employees by the EmbeddedId that returns me results as well.</p>
<pre><code>interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey> {
List<Employee> findByEmployeeKey(EmployeeKey employeeKey);
}
</code></pre>
<hr>
<p><strong>Question:</strong>
Suppose, while querying I have <em>employeeId</em> and <em>branchName</em> only, and I don't want to put filter on <em>departmentName</em> </p>
<ul>
<li>In such cases how can I write my Repository method</li>
<li>Does JPA have something in-build for such scenario?</li>
</ul> | 43,882,807 | 2 | 2 | null | 2017-05-09 08:42:07.16 UTC | 5 | 2021-10-20 05:00:31.167 UTC | 2018-02-15 06:51:35.763 UTC | null | 66,686 | null | 7,910,980 | null | 1 | 33 | java|hibernate|jpa|spring-data-jpa | 29,560 | <p>Here is how it worked for me.</p>
<p>@Ketrox's answer is absolutely correct and works fine. But in my real scenario I had 6 fields to search by and which resulted in an 120+ characters long method name. (<em>Something like below</em>)</p>
<pre><code>List<Employee> findByEmployeeKeyField1AndEmployeeKeyField2AndEmployeeKeyField3AndEmployeeKeyField4AndEmployeeKeyField5AndEmployeeKeyField6(String field1, String field2, String field3, String field4, String field5, String field6);
</code></pre>
<p>Which is certainly not good enough to read and more than good enough to make <a href="http://codenarc.sourceforge.net/" rel="noreferrer">codenarc</a> unhappy. </p>
<hr>
<p>Finally I used find by example and that turned out to be really pleasant solution.</p>
<p><strong><em>Repository:</em></strong></p>
<pre><code>//skipped lines
import org.springframework.data.domain.Example
//skipped lines
interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>{
List<Employee> findAll(Example<Employee> employee);
}
</code></pre>
<p><strong><em>Usage:</em></strong></p>
<pre><code>// Prepare Employee key with all available search by keys (6 in my case)
EmplyeeKey key = new EmplyeeKey();
key.setField1("field1_value");
key.setField2("field2_value");
//Setting remaining 4 fields
// Create new Employee ans set the search key
Employee employee = new Employee();
employee.setEmployeeKey(key);
// Call the findAll by passing an Example of above Employee object
List<Employee> result = employeeRepository.findAll(Example.of(employee));
</code></pre>
<p>I have elaborated the search by <a href="http://www.amitph.com/spring-data-jpa-embeddedid-partially/" rel="noreferrer">Spring Data JPA find by @EmbeddedId Partially
</a></p> |
9,408,160 | Prezi HTML5 Editor via impress.js | <p>I recently known that <a href="http://bartaz.github.com/impress.js/">impress.js</a> has been created as a HTML5 version of Prezi. This helps us to move away from the proprietary Flash technology, and instead use an open web standard that will become universal to all platforms.</p>
<p>However, it is annoying to type up the code on a HTML text editor (like writing the translation, rotation, and the scale values for the slide). It becomes difficult to visualize the presentation especially when the code is extended to an unbearable length.</p>
<p>So here is an example I just created. When reading the HTML code below, it is hard to know exactly where the slides are, and how they will be displayed.</p>
<pre><code><div id="impress">
<div class="step" data-x="0" data-y="0">
Slide 1 at origin.
</div>
<div class="step" data-x="100" data-y="100" data-scale="0.5">
Slide 2 has been moved south-eastern side and shrunk by half compared to slide 1.
</div>
<div class="step" data-x="-500" data-y="-405" data-rotate-x="50" data-rotate-y="-34" data-rotate-z="50" data-scale="2.5">
Slide 3 has been rotated in 3D and is 2.5x larger than slide 1.
</div>
</div>
<script type="text/javascript" src="impress.js"></script>
</code></pre>
<p><a href="http://jsfiddle.net/vxYGL/6/">A JS Fiddle Example</a>.</p>
<p>So is there a WYSIWYG HTML5 Prezi editor that I could use? I would want one as it will make it much easier to create presentations based on HTML5, CSS3, and JavaScript.</p> | 10,491,359 | 6 | 1 | null | 2012-02-23 06:22:40.967 UTC | 10 | 2013-09-05 00:08:37.243 UTC | 2012-10-28 05:02:42.6 UTC | null | 824,294 | null | 824,294 | null | 1 | 16 | javascript|flash|html|wysiwyg|prezi | 19,614 | <p>Hey I recently made Strut. Its a presentation editor just for ImpressJS and is currently in alpha but there is a live demo up here:
<a href="http://strut.io" rel="noreferrer">http://strut.io</a></p>
<p>Github repository: <a href="https://github.com/tantaman/Strut" rel="noreferrer">https://github.com/tantaman/Strut</a></p>
<p>and here is a youtube vid about it:
<a href="http://www.youtube.com/watch?v=zA5s8wwme44&feature=share" rel="noreferrer">http://www.youtube.com/watch?v=zA5s8wwme44&feature=share</a></p>
<p>You can add/remove slides, insert images and text boxes, change fonts, save presentations, and modify transitions between slides by moving slides around in the x,y & z directions.</p> |
9,451,298 | What's the difference between WCF Web API and ASP.NET Web API | <p>I've done a bit of work in the past using WCF WebAPI and really liked a lot of its features, I'm just playing with ASP.NET Web API at the moment and it seems completely different (IE completely removed from WCF).</p>
<p>Does anyone know which features of WCF WebAPI are included in ASP.NET 4 Web API?</p> | 9,452,105 | 7 | 1 | null | 2012-02-26 07:22:33.75 UTC | 23 | 2017-10-16 18:14:05.153 UTC | 2017-10-16 18:14:05.153 UTC | null | 1,033,581 | null | 1,070,291 | null | 1 | 40 | c#|wcf|wcf-web-api|asp.net-mvc-4|asp.net-web-api | 34,342 | <p>Ive done a little more reading around this and found a few pages by MS people on this:</p>
<p><a href="http://wcf.codeplex.com/wikipage?title=How%20to%20Migrate%20from%20WCF%20Web%20API%20to%20ASP.NET%20Web%20API" rel="nofollow">http://wcf.codeplex.com/wikipage?title=How%20to%20Migrate%20from%20WCF%20Web%20API%20to%20ASP.NET%20Web%20API</a> :</p>
<p>The WCF Web API abstractions map to ASP.NET Web API roughly as follows</p>
<p><strong><em>WCF Web API -> ASP.NET Web API</em></strong></p>
<ul>
<li>Service -> Web API controller</li>
<li>Operation -> Action</li>
<li>Service contract -> Not applicable</li>
<li>Endpoint -> Not applicable</li>
<li>URI templates -> ASP.NET Routing</li>
<li>Message handlers -> Same</li>
<li>Formatters -> Same</li>
<li>Operation handlers -> Filters, model binders</li>
</ul>
<p>and <a href="http://wcf.codeplex.com/discussions/319671" rel="nofollow">http://wcf.codeplex.com/discussions/319671</a></p>
<p>The integrated stack supports the following features:</p>
<ul>
<li>Modern HTTP programming model</li>
<li>Full support for ASP.NET Routing</li>
<li>Content negotiation and custom formatters</li>
<li>Model binding and validation</li>
<li>Filters</li>
<li>Query composition</li>
<li>Easy to unit test</li>
<li>Improved Inversion of Control (IoC) via DependencyResolver</li>
<li>Code-based configuration</li>
<li>Self-host</li>
</ul> |
32,914,499 | Error: Execution failed for task ':app:clean'. Unable to delete file | <p>I'm trying to rebuild my Android Studio Gradle project (containing mostly Kotlin code), but it started to throw an <code>UnableToDeleteFileException</code> during the cleaning/rebuilding process:</p>
<pre><code>Execution failed for task ':app:clean'.
> Unable to delete file: C:\Users\User\KotlinGameEngine\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.1\jars\classes.jar
</code></pre>
<p>This started happening after I tried to change my project's package structure. Unfortunately, I did it by renaming and moving the source folders rather than refactoring through Android Studio, which was a bad idea.</p>
<p>I've been searching for a solution to this problem all day, and these are the things I have tried to no avail:</p>
<ul>
<li>Doing a Gradle sync;</li>
<li>Reinstalling Java JRE and Java SDK;</li>
<li>Reinstalling the latest version of Android Studio (1.4);</li>
<li>Rolling back to the previous AS version (1.3);</li>
<li>Invalidating the AS cache and restarting;</li>
<li>Deleting the <code>gradle</code> and <code>.gradle</code> directories in the project directory;</li>
<li>Deleting the <code>.gradle</code> directory in my user directory;</li>
<li>Running <code>gradlew clean</code> from the AS terminal;</li>
<li>Manually copying the sources over to a new project (weird that it somehow persists across projects...)</li>
</ul>
<p>Things that I've tried with a little success, but only let me perform one more clean and rebuild before the error occurs again:</p>
<ul>
<li>Closing AS, manually deleting the build files, and opening it again;</li>
<li>Killing the <code>java.exe</code> process while AS is running (this could technically be done every time, but it's tedious and slows down the build process)</li>
</ul>
<p>So it seems that compile the Java process may put a lock on the build files for some reason, but it might also be something to do with Kotlin. I have a (more mature) Java Android project that I'm working on, though I can't reproduce this error when cleaning it. It seems to only happen to my Kotlin project.</p>
<h2>Update:</h2>
<p>I've found that the problem is being caused by the Kotlin Android plugin. The problem disappears when I remove <code>apply plugin: 'kotlin-android'</code> from the module's <code>build.gradle</code> file and comes back when I reinsert it. Feel free to offer any insight into this.</p>
<h2>Update 2:</h2>
<p>The last update isn't the cause. I found that if a project contains a Kotlin file then rebuilding and cleaning fails. It continues to fail, even if all the Kotlin files are removed, until the background Java process is killed, meaning it has some kind of lock on the build files. I submitted a bug here with more details and steps to reproduce the bug: <a href="https://youtrack.jetbrains.com/issue/KT-9440" rel="noreferrer" title="KT-9440">KT-9440</a></p> | 32,924,320 | 42 | 5 | null | 2015-10-02 19:30:11.61 UTC | 29 | 2022-02-16 21:16:29.463 UTC | 2019-05-05 14:47:37.78 UTC | null | 6,296,561 | null | 5,401,587 | null | 1 | 184 | android|android-studio|android-gradle-plugin|kotlin|kotlin-android-extensions | 245,546 | <p>After I posted a bug report to the Kotlin bug tracker, I was notified of <a href="https://code.google.com/p/android/issues/detail?id=61300">Issue 61300</a> on the AOSP tracker. That seems to be the cause. Since there's nothing I can do at the moment, I'll mark this question as answered, and I'll update the answer if the bug is fixed.</p>
<p>In the meantime, if you're running Windows, I believe I've found a workaround. You'll need to download <a href="http://lockhunter.com/index.htm">LockHunter</a> (at your own risk of course), then add the following to your module's <code>gradle.build</code> file, replacing the <code>lockhunter</code> variable with your path to LockHunter.exe:</p>
<pre><code>task clean(type: Exec) {
ext.lockhunter = '\"C:\\LockHunter.exe\"'
def buildDir = file(new File("build"))
commandLine 'cmd', "$lockhunter", '/delete', '/silent', buildDir
}
</code></pre>
<p>This causes LockHunter to forcefully and silently unlock and delete the build files when the app:clean task runs.</p> |
45,726,654 | install apk programmatically in android 8 (API 26) | <p>I wrote a method to install apk in all version of android and it works until android 8 . but it seems android 8 do not response to this method</p>
<pre><code>install_apk(File file) {
try {
if (file.exists()) {
String[] fileNameArray = file.getName().split(Pattern.quote("."));
if (fileNameArray[fileNameArray.length - 1].equals("apk")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri downloaded_apk = getFileUri(context, file);
Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(downloaded_apk,
"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<p>and this method for get uri on api >= 23 </p>
<pre><code>Uri getFileUri(Context context, File file) {
return FileProvider.getUriForFile(context,
context.getApplicationContext().getPackageName() + ".HelperClasses.GenericFileProvider"
, file);
}
</code></pre> | 45,808,643 | 1 | 6 | null | 2017-08-17 04:35:36.287 UTC | 14 | 2017-08-22 03:54:25.177 UTC | null | null | null | null | 4,034,697 | null | 1 | 34 | android|apk | 15,800 | <p>You should be add a new permission.</p>
<pre><code><uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
</code></pre> |
19,726,029 | How can I make pandas dataframe column headers all lowercase? | <p>I want to make all column headers in my pandas data frame lower case</p>
<h2>Example</h2>
<p>If I have:</p>
<pre><code>data =
country country isocode year XRAT tcgdp
0 Canada CAN 2001 1.54876 924909.44207
1 Canada CAN 2002 1.56932 957299.91586
2 Canada CAN 2003 1.40105 1016902.00180
....
</code></pre>
<p>I would like to change XRAT to xrat by doing something like:</p>
<pre><code>data.headers.lowercase()
</code></pre>
<p>So that I get:</p>
<pre><code> country country isocode year xrat tcgdp
0 Canada CAN 2001 1.54876 924909.44207
1 Canada CAN 2002 1.56932 957299.91586
2 Canada CAN 2003 1.40105 1016902.00180
3 Canada CAN 2004 1.30102 1096000.35500
....
</code></pre>
<p>I will not know the names of each column header ahead of time.</p> | 19,726,078 | 7 | 2 | null | 2013-11-01 11:39:26.053 UTC | 30 | 2022-08-29 06:08:15.533 UTC | 2018-04-16 10:29:13.163 UTC | null | 562,769 | null | 2,428,549 | null | 1 | 165 | python|pandas|dataframe | 152,404 | <p>You can do it like this:</p>
<pre><code>data.columns = map(str.lower, data.columns)
</code></pre>
<p>or</p>
<pre><code>data.columns = [x.lower() for x in data.columns]
</code></pre>
<p>example:</p>
<pre><code>>>> data = pd.DataFrame({'A':range(3), 'B':range(3,0,-1), 'C':list('abc')})
>>> data
A B C
0 0 3 a
1 1 2 b
2 2 1 c
>>> data.columns = map(str.lower, data.columns)
>>> data
a b c
0 0 3 a
1 1 2 b
2 2 1 c
</code></pre> |
763,442 | What is the equivalent of 'go' in MySQL? | <p>In TSQL I can state:</p>
<pre><code>insert into myTable (ID) values (5)
GO
select * from myTable
</code></pre>
<p>In MySQL I can't write the same query.</p>
<p>What is the correct way to write this query in MySQL?</p> | 763,445 | 5 | 1 | null | 2009-04-18 13:31:17.257 UTC | 8 | 2022-06-29 18:32:18.77 UTC | 2010-08-23 20:39:35.177 UTC | null | 23,199 | null | 48,865 | null | 1 | 30 | sql|mysql|tsql | 43,416 | <p>Semicolon at the end of the statement.</p>
<pre><code>INSERT INTO myTable (ID) values (5);
</code></pre> |
584,770 | How would I get a cron job to run every 30 minutes? | <p>I'm looking to add a <code>crontab</code> entry to execute a script every 30 minutes, on the hour and 30 minutes past the hour or something close. I have the following, but it doesn't seem to run on 0.</p>
<pre><code>*/30 * * * *
</code></pre>
<p>What string do I need to use?</p>
<p>The cron is running on OSX.</p> | 584,776 | 6 | 6 | null | 2009-02-25 05:06:27.08 UTC | 40 | 2022-06-02 13:05:20.713 UTC | 2011-05-26 16:45:56.813 UTC | Neil N | 5,441 | Darryl Hein | 5,441 | null | 1 | 263 | linux|macos|cron | 340,962 | <p>Do:</p>
<pre><code>0,30 * * * * your_command
</code></pre> |
42,278,134 | Is there a way to load image as bitmap to Glide | <p>Im looking for a way to use bitmap as input to Glide. I am even not sure if its possible. It's for resizing purposes. Glide has a good image enhancement with scale. The problem is that I have resources as bitmap already loaded to memory. The only solution I could find is to store images to temporary file and reload them back to Glide as inputStream/file.. Is there a better way to achieve that ?</p>
<p>Please before answering .. Im not talking about output from Glide.. <code>.asBitmap().get()</code> I know that.I need help with input.</p>
<p>Here is my workaround solution:</p>
<pre><code> Bitmap bitmapNew=null;
try {
//
ContextWrapper cw = new ContextWrapper(ctx);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File file=new File(directory,"temp.jpg");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
//
bitmapNew = Glide
.with(ctx)
.load(file)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into( mActualWidth, mActualHeight - heightText)
.get();
file.delete();
} catch (Exception e) {
Logcat.e( "File not found: " + e.getMessage());
}
</code></pre>
<p>I'd like to avoid writing images to internal and load them again.That is the reason why Im asking if there is way to to have input as bitmap</p>
<p>Thanks</p> | 46,701,647 | 13 | 5 | null | 2017-02-16 15:28:08.107 UTC | 14 | 2022-08-12 13:10:31.23 UTC | 2017-07-07 08:29:10.273 UTC | null | 2,267,723 | null | 2,267,723 | null | 1 | 45 | android|image-resizing|android-glide|image-scaling | 87,076 | <p>For version 4 you have to call <code>asBitmap()</code> before <code>load()</code></p>
<pre><code>GlideApp.with(itemView.getContext())
.asBitmap()
.load(data.getImageUrl())
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {}
});
}
</code></pre>
<p>More info: <a href="http://bumptech.github.io/glide/doc/targets.html" rel="noreferrer">http://bumptech.github.io/glide/doc/targets.html</a></p> |
31,025,048 | npm doesn't work, get always this error -> Error: Cannot find module 'are-we-there-yet' | <p>i tried to install grunt on a mac with Yosemite. node is already installed in the newest version. if i type "node -v" in the terminal i get the line v0.12.5. thats good. but when i want to install something with npm i get only a error... </p>
<p>i tried "sudo npm install -g grunt-cli", "sudo npm install npm -g" and also with "npm -v" i get always this error... </p>
<pre><code>Error: Cannot find module 'are-we-there-yet'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/usr/local/Cellar/node/0.10.22/lib/node_modules/npm/node_modules/npmlog/log.js:2:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
</code></pre>
<p>someone knows what's the problem or better a solution?</p> | 31,034,734 | 11 | 4 | null | 2015-06-24 11:14:50.7 UTC | 25 | 2021-08-23 09:35:45.293 UTC | 2017-02-28 14:41:01.993 UTC | null | 1,033,581 | null | 1,285,492 | null | 1 | 63 | node.js|macos|installation|npm | 53,862 | <p>You have broken <code>npm</code> by removing some of its dependencies.</p>
<p><code>are-we-there-yet</code> is a dependency of <code>npmlog</code> which is a dependency of <code>npm</code> itself, and you somehow deleted it. The usual simple solution for such cases is reinstalling a package, but that doesn't work if <code>npm</code> cannot operate. Fortunately, <code>npm</code> tarball comes prebundled with dependencies and hence <a href="https://docs.npmjs.com/getting-started/installing-node#installing-npm-manually">installing <code>npm</code> from scratch</a> is as simple as unpacking a tarball.</p>
<p>1) Go to the global <code>node_modules</code> directory (what would <code>npm root -g</code> print if you could run it):</p>
<pre><code>$ cd /usr/local/lib/node_modules
</code></pre>
<p>2) Remove the broken <code>npm</code> directory or move it somewhere else (note that you might need to elevate permissions for this and the following steps):</p>
<pre><code>$ mv npm /tmp
</code></pre>
<p>3) Download and unpack fresh <code>npm</code> from the registry (substitute version you want to install, e.g. <code>3.10.8</code>):</p>
<pre><code>$ curl -L registry.npmjs.com/npm/-/npm-{VERSION}.tgz | tar xz --transform="s:^package:npm:"
</code></pre>
<p>You can automate some of that with this install script:</p>
<pre><code>$ curl -L https://www.npmjs.com/install.sh | sh
</code></pre>
<p>At this point <code>npm</code> should work again.</p> |
31,198,946 | Could not load the "" image referenced from a nib in the bundle with identifier | <p>when I load my application it shows a warning message that </p>
<blockquote>
<p>"Could not load the "" image referenced from a nib in the bundle with
identifier "</p>
</blockquote>
<p>I searched and confirmed all my images. But it still shows that warning.</p> | 46,719,986 | 24 | 4 | null | 2015-07-03 05:14:15.03 UTC | 7 | 2021-09-19 13:29:47.9 UTC | 2015-07-05 06:03:58.843 UTC | null | 1,307,905 | null | 5,068,021 | null | 1 | 78 | ios|iphone | 58,519 | <ol>
<li>Select your image(s) in Project Navigator. </li>
<li>Open the File Inspector.</li>
<li>Make sure you have the target selected.</li>
</ol>
<p><a href="https://i.stack.imgur.com/YlFPd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YlFPd.png" alt="Add your image to the target"></a></p> |
20,943,407 | Creating an Android Lock Screen App. | <p>How to create a lock-screen app that acts as a lock for android mobile. I did find one, But it was poorly constructed code wise and if I pressed the physical home key, it unlocked, making the application pointless.</p>
<p>I did come across a forum stating some method of blocking home button functionality was removed in Android 4.x </p>
<p>Yet, I have an awesome idea for a lock-screen but no ground to get started. If anyone has any knowledge on the subject, I'd love to hear it.</p>
<p>Thanks all :-) </p> | 20,944,151 | 1 | 6 | null | 2014-01-06 05:15:25.843 UTC | 33 | 2020-04-25 13:31:48.843 UTC | 2016-09-26 16:29:42.207 UTC | null | 3,082,414 | null | 3,047,494 | null | 1 | 30 | java|android|lockscreen | 81,951 | <p><strong>Yes, it is possible. This is a simple lock screen <a href="https://github.com/Kirk-Str/LockScreenApp" rel="noreferrer">Source Code</a> from GitHub</strong></p>
<p>Creating an app that works like a lock is no big deal but as you said for Home key issue, I would suggest you go on and develop the App as much as you need and the only final area you would get stuck is the home key control so, try to find some tricky way to get the control of home key and make it as an app launcher for your lock app. It is not very complicated but kinda tricky though. I will post you, if I can find any Home-key access source codes</p>
<p><strong>PS:</strong></p>
<p><strong>Here is the tutorial for accessing <a href="http://www.taywils.me/2011/07/05/buildanapplicationlauncherwithandroid.html" rel="noreferrer">Home Key</a></strong></p>
<p>I found the home key override somewhere. Add these lines in the App Manifest. </p>
<p>Following two lines will do the magic</p>
<pre><code> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</code></pre>
<p>and override this method in your activity</p>
<pre><code>@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
Log.i("Home Button","Clicked");
}
if(keyCode==KeyEvent.KEYCODE_BACK)
{
finish();
}
return false;
}
</code></pre>
<p>Keep in mind that I didn't test these codes or methods, just tried to help you (you might find some drawbacks). </p>
<p><strong>PS:</strong> based on the votes I can guarantee that my suggestion is working and you can develop such app with the above help :)</p> |
63,164,973 | Why does Rust allow calling functions via null pointers? | <p>I was experimenting with function pointer magic in Rust and ended up with a code snippet which I have absolutely no explanation for why it compiles and even more, why it runs.</p>
<pre><code>fn foo() {
println!("This is really weird...");
}
fn caller<F>() where F: FnMut() {
let closure_ptr = 0 as *mut F;
let closure = unsafe { &mut *closure_ptr };
closure();
}
fn create<F>(_: F) where F: FnMut() {
caller::<F>();
}
fn main() {
create(foo);
create(|| println!("Okay..."));
let val = 42;
create(|| println!("This will seg fault: {}", val));
}
</code></pre>
<p>I cannot explain <em>why</em> <code>foo</code> is being invoked by casting a null pointer in <code>caller(...)</code> to an instance of type <code>F</code>. I would have thought that functions may only be called through corresponding function pointers, but that clearly can't be the case given that the pointer itself is null. With that being said, it seems that I clearly misunderstand an important piece of Rust's type system.</p>
<p><a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e80717402ba5930d350e140b7bacf282" rel="noreferrer">Example on Playground</a></p> | 63,166,245 | 5 | 2 | null | 2020-07-30 01:50:20.027 UTC | 5 | 2020-08-11 15:40:37.007 UTC | 2020-07-30 19:48:08.76 UTC | null | 2,733,851 | null | 940,300 | null | 1 | 46 | rust | 5,700 | <p>This program never actually constructs a function pointer at all- it always invokes <code>foo</code> and those two closures <em>directly.</em></p>
<p>Every Rust function, whether it's a closure or a <code>fn</code> item, has a unique, anonymous type. This type implements the <code>Fn</code>/<code>FnMut</code>/<code>FnOnce</code> traits, as appropriate. The anonymous type of a <code>fn</code> item is zero-sized, just like the type of a closure with no captures.</p>
<p>Thus, the expression <code>create(foo)</code> instantiates <code>create</code>'s parameter <code>F</code> with <code>foo</code>'s type- this is not the function pointer type <code>fn()</code>, but an anonymous, zero-sized type just for <code>foo</code>. In error messages, rustc calls this type <code>fn() {foo}</code>, as you can see <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2c30794e639b53cb5f59212d1fabd174" rel="noreferrer">this error message</a>.</p>
<p>Inside <code>create::<fn() {foo}></code> (using the name from the error message), the expression <code>caller::<F>()</code> forwards this type to <code>caller</code> without giving it a value of that type.</p>
<p>Finally, in <code>caller::<fn() {foo}></code> the expression <code>closure()</code> desugars to <code>FnMut::call_mut(closure)</code>. Because <code>closure</code> has type <code>&mut F</code> where <code>F</code> is just the zero-sized type <code>fn() {foo}</code>, the <code>0</code> value of <code>closure</code> itself is simply never used<sup>1</sup>, and the program calls <code>foo</code> directly.</p>
<p>The same logic applies to the closure <code>|| println!("Okay...")</code>, which like <code>foo</code> has an anonymous zero-sized type, this time called something like <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7d4f09ea0eb0cb82c57c3e3cb0519c29" rel="noreferrer"><code>[closure@src/main.rs:2:14: 2:36]</code></a>.</p>
<p>The second closure is not so lucky- its type is <em>not</em> zero-sized, because it must contain a reference to the variable <code>val</code>. This time, <code>FnMut::call_mut(closure)</code> actually needs to dereference <code>closure</code> to do its job. So it crashes<sup>2</sup>.</p>
<hr>
<p><sup>1</sup> Constructing a null reference like this is technically undefined behavior, so the compiler makes no promises about this program's overall behavior. However, replacing <code>0</code> with some other "address" with the alignment of <code>F</code> avoids that problem for zero-sized types like <code>fn() {foo}</code>, and gives <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=847ca808ae5f44e2315fabdf05432352" rel="noreferrer">the same behavior</a>!)</p>
<p><sup>2</sup> Again, constructing a null (or dangling) reference is the operation that actually takes the blame here- after that, anything goes. A segfault is just one possibility- a future version of rustc, or the same version when run on a slightly different program, might do something else entirely!</p> |
61,386,847 | How can my Gradle build initialize class org.codehaus.groovy.classgen.Verifier? | <p>My tool versions are:</p>
<pre><code>Version: IntelliJ 2020.01
Gradle Version: 5.3
</code></pre>
<p>This is the error:</p>
<pre><code>Could not initialize class `org.codehaus.groovy.classgen.Verifier`
</code></pre>
<p>This is the full stacktrace:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Could not open cp_init remapped class cache for cu8zodz9lhma9nl4f6h0p0tmj (/home/wadhe/.gradle/caches/6.2/scripts-remapped/sync_studio_tooling3_3txli0t8xc4p0cha8vbu3368/cu8zodz9lhma9nl4f6h0p0tmj/cp_initcf39471ad2848fb82befe662c0627ed4).
> Could not open cp_init generic class cache for initialization script '/tmp/sync.studio.tooling3.gradle' (/home/wadhe/.gradle/caches/6.2/scripts/cu8zodz9lhma9nl4f6h0p0tmj/cp_init/cp_initcf39471ad2848fb82befe662c0627ed4).
> Could not initialize class org.codehaus.groovy.classgen.Verifier
* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Exception is:
org.gradle.cache.CacheOpenException: Could not open cp_init remapped class cache for cu8zodz9lhma9nl4f6h0p0tmj (/home/wadhe/.gradle/caches/6.2/scripts-remapped/sync_studio_tooling3_3txli0t8xc4p0cha8vbu3368/cu8zodz9lhma9nl4f6h0p0tmj/cp_initcf39471ad2848fb82befe662c0627ed4).
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:80)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:42)
at org.gradle.cache.internal.DefaultCacheFactory.doOpen(DefaultCacheFactory.java:95)
at org.gradle.cache.internal.DefaultCacheFactory.open(DefaultCacheFactory.java:68)
at org.gradle.cache.internal.DefaultCacheRepository$PersistentCacheBuilder.open(DefaultCacheRepository.java:126)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler.compile(FileCacheBackedScriptClassCompiler.java:105)
at org.gradle.groovy.scripts.internal.CrossBuildInMemoryCachingScriptClassCache.getOrCompile(CrossBuildInMemoryCachingScriptClassCache.java:50)
at org.gradle.groovy.scripts.internal.BuildScopeInMemoryCachingScriptClassCompiler.compile(BuildScopeInMemoryCachingScriptClassCompiler.java:50)
at org.gradle.groovy.scripts.DefaultScriptCompilerFactory$ScriptCompilerImpl.compile(DefaultScriptCompilerFactory.java:49)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:209)
at org.gradle.configuration.BuildOperationScriptPlugin$1$1.run(BuildOperationScriptPlugin.java:69)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:66)
at org.gradle.configuration.BuildOperationScriptPlugin$1.execute(BuildOperationScriptPlugin.java:63)
at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.apply(DefaultUserCodeApplicationContext.java:49)
at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:63)
at org.gradle.configuration.DefaultInitScriptProcessor.process(DefaultInitScriptProcessor.java:50)
at org.gradle.initialization.InitScriptHandler$1.run(InitScriptHandler.java:55)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.initialization.InitScriptHandler.executeScripts(InitScriptHandler.java:49)
at org.gradle.initialization.DefaultSettingsPreparer.prepareSettings(DefaultSettingsPreparer.java:33)
at org.gradle.initialization.BuildOperatingFiringSettingsPreparer$LoadBuild.doLoadBuild(BuildOperatingFiringSettingsPreparer.java:59)
at org.gradle.initialization.BuildOperatingFiringSettingsPreparer$LoadBuild.run(BuildOperatingFiringSettingsPreparer.java:54)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.initialization.BuildOperatingFiringSettingsPreparer.prepareSettings(BuildOperatingFiringSettingsPreparer.java:42)
at org.gradle.initialization.DefaultGradleLauncher.prepareSettings(DefaultGradleLauncher.java:208)
at org.gradle.initialization.DefaultGradleLauncher.doClassicBuildStages(DefaultGradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:140)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:120)
at org.gradle.internal.invocation.GradleBuildController$1.create(GradleBuildController.java:74)
at org.gradle.internal.invocation.GradleBuildController$1.create(GradleBuildController.java:67)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:189)
at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:40)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:67)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:56)
at org.gradle.tooling.internal.provider.runner.ClientProvidedPhasedActionRunner.run(ClientProvidedPhasedActionRunner.java:60)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.BuildOutcomeReportingBuildActionRunner.run(BuildOutcomeReportingBuildActionRunner.java:63)
at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
at org.gradle.launcher.exec.BuildCompletionNotifyingBuildActionRunner.run(BuildCompletionNotifyingBuildActionRunner.java:39)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.call(RunAsBuildOperationBuildActionRunner.java:51)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.call(RunAsBuildOperationBuildActionRunner.java:45)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:50)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:80)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:31)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:42)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:28)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:78)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:52)
at org.gradle.tooling.internal.provider.SubscribableBuildActionExecuter.execute(SubscribableBuildActionExecuter.java:60)
at org.gradle.tooling.internal.provider.SubscribableBuildActionExecuter.execute(SubscribableBuildActionExecuter.java:38)
at org.gradle.tooling.internal.provider.SessionScopeBuildActionExecuter.execute(SessionScopeBuildActionExecuter.java:68)
at org.gradle.tooling.internal.provider.SessionScopeBuildActionExecuter.execute(SessionScopeBuildActionExecuter.java:38)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:37)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:26)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:60)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:32)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:41)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:48)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:32)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:68)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:39)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:29)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:35)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.create(ForwardClientInput.java:78)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.create(ForwardClientInput.java:75)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:75)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:63)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:52)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: org.gradle.cache.CacheOpenException: Could not open cp_init generic class cache for initialization script '/tmp/sync.studio.tooling3.gradle' (/home/wadhe/.gradle/caches/6.2/scripts/cu8zodz9lhma9nl4f6h0p0tmj/cp_init/cp_initcf39471ad2848fb82befe662c0627ed4).
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:80)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:42)
at org.gradle.cache.internal.DefaultCacheFactory.doOpen(DefaultCacheFactory.java:95)
at org.gradle.cache.internal.DefaultCacheFactory.open(DefaultCacheFactory.java:68)
at org.gradle.cache.internal.DefaultCacheRepository$PersistentCacheBuilder.open(DefaultCacheRepository.java:126)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$RemapBuildScriptsAction.execute(FileCacheBackedScriptClassCompiler.java:435)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$RemapBuildScriptsAction.execute(FileCacheBackedScriptClassCompiler.java:403)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$ProgressReportingInitializer.execute(FileCacheBackedScriptClassCompiler.java:177)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$ProgressReportingInitializer.execute(FileCacheBackedScriptClassCompiler.java:156)
at org.gradle.cache.internal.DefaultPersistentDirectoryCache$Initializer.initialize(DefaultPersistentDirectoryCache.java:100)
at org.gradle.cache.internal.FixedSharedModeCrossProcessCacheAccess$1.run(FixedSharedModeCrossProcessCacheAccess.java:86)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.doWriteAction(DefaultFileLockManager.java:215)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.writeFile(DefaultFileLockManager.java:205)
at org.gradle.cache.internal.FixedSharedModeCrossProcessCacheAccess.open(FixedSharedModeCrossProcessCacheAccess.java:83)
at org.gradle.cache.internal.DefaultCacheAccess.open(DefaultCacheAccess.java:139)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:78)
... 118 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.classgen.Verifier
at org.gradle.groovy.scripts.internal.DefaultScriptCompilationHandler$CustomCompilationUnit.<init>(DefaultScriptCompilationHandler.java:284)
at org.gradle.groovy.scripts.internal.DefaultScriptCompilationHandler$1.createCompilationUnit(DefaultScriptCompilationHandler.java:124)
at org.gradle.groovy.scripts.internal.DefaultScriptCompilationHandler.compileScript(DefaultScriptCompilationHandler.java:142)
at org.gradle.groovy.scripts.internal.DefaultScriptCompilationHandler.compileToDir(DefaultScriptCompilationHandler.java:98)
at org.gradle.groovy.scripts.internal.BuildOperationBackedScriptCompilationHandler$2.run(BuildOperationBackedScriptCompilationHandler.java:54)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.groovy.scripts.internal.BuildOperationBackedScriptCompilationHandler.compileToDir(BuildOperationBackedScriptCompilationHandler.java:51)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$CompileToCrossBuildCacheAction.execute(FileCacheBackedScriptClassCompiler.java:152)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$CompileToCrossBuildCacheAction.execute(FileCacheBackedScriptClassCompiler.java:132)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$ProgressReportingInitializer.execute(FileCacheBackedScriptClassCompiler.java:177)
at org.gradle.groovy.scripts.internal.FileCacheBackedScriptClassCompiler$ProgressReportingInitializer.execute(FileCacheBackedScriptClassCompiler.java:156)
at org.gradle.cache.internal.DefaultPersistentDirectoryCache$Initializer.initialize(DefaultPersistentDirectoryCache.java:100)
at org.gradle.cache.internal.FixedSharedModeCrossProcessCacheAccess$1.run(FixedSharedModeCrossProcessCacheAccess.java:86)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.doWriteAction(DefaultFileLockManager.java:215)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.writeFile(DefaultFileLockManager.java:205)
at org.gradle.cache.internal.FixedSharedModeCrossProcessCacheAccess.open(FixedSharedModeCrossProcessCacheAccess.java:83)
at org.gradle.cache.internal.DefaultCacheAccess.open(DefaultCacheAccess.java:139)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.open(DefaultPersistentDirectoryStore.java:78)
... 133 more
* Get more help at https://help.gradle.org
BUILD FAILED in 25ms
</code></pre> | 61,411,823 | 4 | 1 | null | 2020-04-23 12:06:46.247 UTC | 6 | 2021-12-28 02:59:47.9 UTC | 2020-08-24 13:20:28.273 UTC | null | 219,658 | null | 3,855,050 | null | 1 | 47 | gradle|intellij-idea|groovy|build.gradle | 48,531 | <p>I've been facing the exactly same issue after installing the latest Kotlin Plugin yesterday. This is what resolved the issue for me: I had to change the version of Gradle used as the build tool to (again) use the version installed on my local system. It seems to me that installing the update has caused my settings to be changed as well. </p>
<p>For doing to open your settings (<code>File -> Settings</code>) and navigate to the Gradle settings (<code>Build, Execution, Deployment -> Build Tools -> Gradle</code>)</p>
<p>There you will see a dropdown for <code>Use Gradle from:</code>. This for me was set to the <code>gradle-wrapper.properties</code> file which it couldn't locate. I changed the selected value to <code>Specified location</code> and ensured that the path which is then displayed is the path to my local Gradle installation. Finally click <code>OK</code> to save the settings. </p>
<p>This is what resolved the issue for me. Hope this helps!</p>
<p>For documentation purposes let me also include the different versions of the tooling on my system (truncated):</p>
<pre><code>IntelliJ IDEA 2020.1 (Community Edition)
Build #IC-201.6668.121, built on April 8, 2020
Runtime version: 11.0.6+8-b765.25 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
...
Non-Bundled Plugins: org.jetbrains.kotlin`
Kotlin Plugin 1.3.72-release-IJ2020.1-1
Gradle 6.3
Build time: 2020-03-24 19:52:07 UTC
...
Kotlin: 1.3.70
Groovy: 2.5.10
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
</code></pre> |
47,187,863 | Can Excel's INDEX function return array? | <p>If the data in the range <code>A1:A4</code> is as follows:</p>
<pre><code>Apple
Banana
Orange
Strawberry
</code></pre>
<p>Then <code>INDEX</code> can be used to individually return any value from that list, e.g.</p>
<pre><code>= INDEX(A1:A4,3)
</code></pre>
<p>Would return <code>Orange</code>.</p>
<p>Is there a similar Excel functions or combination of functions that would effectively allow you to do something like this:</p>
<pre><code>= INDEX(A1:A4,{2;3})
</code></pre>
<p>Which would return an array <code>{Banana;Orange}</code>?</p>
<p>Is this possible (preferably without VBA), and if so, how? I'm having a tough time figuring out how to accomplish this, even with the use of helper cells.</p>
<p>I can figure out a somewhat complicated solution if the data is numbers (using <code>MMULT</code>), but the fact that the data is text is tripping me up because <code>MMULT</code> does not work with text.</p> | 47,189,998 | 4 | 10 | null | 2017-11-08 19:15:25.463 UTC | 9 | 2021-01-09 16:51:44.81 UTC | 2017-11-09 08:36:28.37 UTC | null | 6,792,573 | null | 8,370,633 | null | 1 | 14 | arrays|excel|indexing|excel-formula | 41,192 | <p>OFFSET is probably the function you want. </p>
<pre><code>=OFFSET(A1:A4,1,,2)
</code></pre>
<p>But to answer your question, INDEX can indeed be used to return an array. Or rather, two INDEX functions with a colon between them:</p>
<pre><code>=INDEX(A1:A4,2):INDEX(A1:A4,3)
</code></pre>
<p>This is because INDEX actually returns a cell reference OR a number, and Excel determines which of these you want depending on the context in which you are asking. If you put a colon in the middle of two INDEX functions, Excel says "Hey a colon...normally there is a cell reference on each side of one of these" and so interprets the INDEX as just that. You can read more on this at <a href="http://blog.excelhero.com/2011/03/21/the_imposing_index/" rel="noreferrer">http://blog.excelhero.com/2011/03/21/the_imposing_index/</a></p>
<p>I actually prefer INDEX to OFFSET because OFFSET is volatile, meaning it constantly recalculates at the drop of a hat, and then forces any formulas downstream of it to do the same. For more on this, read my post <a href="https://chandoo.org/wp/2014/03/03/handle-volatile-functions-like-they-are-dynamite/" rel="noreferrer">https://chandoo.org/wp/2014/03/03/handle-volatile-functions-like-they-are-dynamite/</a> </p>
<p>You can actually use just <em>one</em> INDEX and return an array, but it's complicated, and requires something called dereferencing. Here's some content from a book I'm writing on this: </p>
<p>The worksheet in this screenshot has a named range called Data assigned to the range A2:E2 across the top. That range contains the numbers 10, 20, 30, 40, and 50. And it also has a named range called Elements assigned to the range A5:B5. That Elements range tells the formula in A8:B8 which of those five numbers from the Data range to display.</p>
<p><a href="https://i.stack.imgur.com/gEKvd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gEKvd.png" alt="enter image description here"></a></p>
<p>If you look at the formula in A8:B8, youβll see that itβs an array-entered INDEX function: {=INDEX(Data,Elements)}. This formula says, βGo to the data range and fetch elements from it based on whatever elements the user has chosen in the Elements range.β
In this particular case, the user has requested the fifth and second items from it. And sure enough, thatβs just what INDEX fetches into cells A8:B8: the corresponding values of 50 and 20.</p>
<p>But look at what happens if you take that perfectly good INDEX function and try to put a SUM around it, as shown in A11. You get an incorrect result: 50+20 does not equal 50. What happened to 20, Excel?</p>
<p>For some reason, while <code>=INDEX(Data,Elements)</code> will quite happily fetch disparate elements from somewhere and then return those numbers separately to a range, it is rather reluctant to comply if you ask it to instead give those numbers to another function. Itβs so reluctant, in fact, that it passes only the first element to the function.</p>
<p>Consequently, youβre seemingly forced to return the results of the =INDEX(Data,Elements) function to the grid first if you want to do something else with it. Tedious. But pretty much every Excel pro would simply tell you that thereβs no workaround...thatβs just the way it is, and you have no other choice.</p>
<p>Buuuuuuuut, theyβre wrong. At the post <a href="http://excelxor.com/2014/09/05/index-returning-an-array-of-values/" rel="noreferrer">http://excelxor.com/2014/09/05/index-returning-an-array-of-values/</a>, mysterious formula superhero XOR outlines two fairly simple ways to βde-referenceβ INDEX so that you can then use its results directly in other formulas; one of those methods is shown in A18 above. It turns out that if you amend the INDEX function slightly by adding an extra bit to encase that Elements argument, INDEX plays ball. And all you need to do is encase that Elements argument as I've done below:</p>
<p>N(IF({1},Elements))</p>
<p>With this in mind, your original misbehaving formula:</p>
<pre><code>=SUM(INDEX(Data,Elements))
</code></pre>
<p>...becomes this complex but well-mannered darling:</p>
<pre><code>=SUM(INDEX(Data, N(IF({1},Elements))))
</code></pre> |
23,152,207 | Gnuplot how to lower the number of tics in x axis | <p>The figure has too many xtics and ytics. Can I have half of them?</p>
<p>I know I can manually set tics in a way similar to this:</p>
<pre><code>set xtics (1,2,4,8,16,32,64,128,256,512,1024)
</code></pre>
<p>But I feel it is not a general solution. You can not manually set tics for all figures. I have loads of them and the gnuplot code is automatically generated using Java.</p>
<p>Here is the code for the figure: <a href="https://dl.dropboxusercontent.com/u/45318932/gnuplot2.plt" rel="noreferrer">https://dl.dropboxusercontent.com/u/45318932/gnuplot2.plt</a></p>
<p>Can you help lower down the number of x and y tics?</p>
<p><img src="https://i.stack.imgur.com/cJvRi.png" alt="enter image description here"></p> | 23,155,048 | 4 | 2 | null | 2014-04-18 10:27:51.297 UTC | 2 | 2020-09-25 14:38:44.99 UTC | null | null | null | null | 3,227,495 | null | 1 | 12 | gnuplot|axis | 51,676 | <p>There is no option in gnuplot to explicitly set the number of tics you want on an axis and have gnuplot decide where to put them. (I really wish there were.)</p>
<p>One option you have is to use the <code>stats</code> command (in gnuplot 4.6+) to find out the range of the data:</p>
<pre><code>ntics = 4
stats 'data.dat' using 1 name 'x' nooutput
stats 'data.dat' using 2 name 'y' nooutput
stats 'data.dat' using 3 name 'z' nooutput
set xtics x_max/ntics
set ytics y_max/ntics
set ztics z_max/ntics
</code></pre>
<p>You might have to adjust whether you want the tics to be at integer values or not, but that is the general idea.</p> |
1,362,995 | Properly locking a List<T> in MultiThreaded Scenarios? | <p>Okay, I just can't get my head around multi-threading scenarios properly. Sorry for asking a similar question again, I'm just seeing many different "facts" around the internet. </p>
<pre><code>public static class MyClass {
private static List<string> _myList = new List<string>;
private static bool _record;
public static void StartRecording()
{
_myList.Clear();
_record = true;
}
public static IEnumerable<string> StopRecording()
{
_record = false;
// Return a Read-Only copy of the list data
var result = new List<string>(_myList).AsReadOnly();
_myList.Clear();
return result;
}
public static void DoSomething()
{
if(_record) _myList.Add("Test");
// More, but unrelated actions
}
}
</code></pre>
<p>The idea is that if Recording is activated, calls to DoSomething() get recorded in an internal List, and returned when StopRecording() is called.</p>
<p>My specification is this:</p>
<ul>
<li>StartRecording is not considered Thread-Safe. The user should call this while no other Thread is calling DoSomething(). But if it somehow could be, that would be great.</li>
<li>StopRecording is also not officially thread-safe. Again, it would be great if it could be, but that is not a requirement.</li>
<li>DoSomething has to be thread-safe</li>
</ul>
<p>The usual way seems to be:</p>
<pre><code> public static void DoSomething()
{
object _lock = new object();
lock(_lock){
if(_record) _myList.Add("Test");
}
// More, but unrelated actions
}
</code></pre>
<p>Alternatively, declaring a static variable:</p>
<pre><code> private static object _lock;
public static void DoSomething()
{
lock(_lock){
if(_record) _myList.Add("Test");
}
// More, but unrelated actions
}
</code></pre>
<p>However, <a href="https://stackoverflow.com/questions/230716/difference-between-locklocker-and-lockvariablewhichiamusing/230861#230861">this answer</a> says that this does not prevent other code from accessing it.</p>
<p>So I wonder</p>
<ul>
<li>How would I properly lock a list?</li>
<li>Should I create the lock object in my function or as a static class variable?</li>
<li>Can I wrap the functionality of Start and StopRecording in a lock-block as well?</li>
<li>StopRecording() does two things: Set a boolean variable to false (to prevent DoSomething() from adding more stuff) and then copying the list to return a copy of the data to the caller). I assume that _record = false; is atomic and will be in effect immediately? So normally I wouldn't have to worry about Multi-Threading here at all, unless some other Thread calls StartRecording() again?</li>
</ul>
<p>At the end of the day, I am looking for a way to express "Okay, this list is mine now, all other threads have to wait until I am done with it".</p> | 1,363,187 | 5 | 1 | null | 2009-09-01 15:09:36.85 UTC | 9 | 2013-06-13 17:37:28.45 UTC | 2017-05-23 10:29:21.167 UTC | null | -1 | null | 91 | null | 1 | 35 | c#|.net|multithreading | 49,430 | <p>I will lock on the _myList itself here since it is private, but using a separate variable is more common. To improve on a few points:</p>
<pre><code>public static class MyClass
{
private static List<string> _myList = new List<string>;
private static bool _record;
public static void StartRecording()
{
lock(_myList) // lock on the list
{
_myList.Clear();
_record = true;
}
}
public static IEnumerable<string> StopRecording()
{
lock(_myList)
{
_record = false;
// Return a Read-Only copy of the list data
var result = new List<string>(_myList).AsReadOnly();
_myList.Clear();
return result;
}
}
public static void DoSomething()
{
lock(_myList)
{
if(_record) _myList.Add("Test");
}
// More, but unrelated actions
}
}
</code></pre>
<p>Note that this code uses <code>lock(_myList)</code> to synchronize access to both _myList <strong>and</strong> _record. And you need to sync all actions on those two.</p>
<p>And to agree with the other answers here, <code>lock(_myList)</code> does nothing to _myList, it just uses _myList as a token (presumably as key in a HashSet). All methods must play fair by asking permission using the same token. A method on another thread can still use _myList without locking first, but with unpredictable results.</p>
<p>We can use any token so we often create one specially:</p>
<pre><code>private static object _listLock = new object();
</code></pre>
<p>And then use <code>lock(_listLock)</code> instead of <code>lock(_myList)</code> everywhere.</p>
<p>This technique would have been advisable if myList had been public, and it would have been absolutely necessary if you had re-created myList instead of calling Clear().</p> |
1,460,361 | How to set application icon in a Qt-based project? | <p>How do you set application icon for application made using Qt? Is there some easy way? It's a qmake-based project.</p> | 1,460,372 | 5 | 1 | null | 2009-09-22 14:16:48.11 UTC | 14 | 2021-07-18 15:31:36.503 UTC | 2013-10-16 13:24:01.537 UTC | null | 1,329,652 | null | 113,071 | null | 1 | 63 | c++|qt | 96,006 | <p>For <strong>Qt 5</strong>, this process is automated by qmake. Just add the following to the project file:</p>
<pre><code>win32:RC_ICONS += your_icon.ico
</code></pre>
<p>The automated resource file generation also uses the values of the following qmake variables: <code>VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, QMAKE_TARGET_COPYRIGHT, QMAKE_TARGET_PRODUCT, RC_LANG, RC_CODEPAGE</code>.</p>
<p>For <strong>Qt 4</strong>, you need to do it manually. On Windows, you need to create a .rc file and add it to your project (.pro). The RC file should look like this:</p>
<pre><code>IDI_ICON1 ICON DISCARDABLE "path_to_you_icon.ico"
</code></pre>
<p>The .pro entry should also be win32 specific, e.g.:</p>
<pre><code>win32:RC_FILE += MyApplication.rc
</code></pre> |
2,280,496 | What are the best practices when running a process as a windows service? | <p>Is there any things to take care of when running your process or executable as service.Things like silent logging.Critical error reporting scenarios? etc? How do you handle it ?</p> | 2,280,524 | 6 | 1 | null | 2010-02-17 12:25:32.937 UTC | 10 | 2015-07-23 19:06:53.07 UTC | 2010-03-06 04:06:08.4 UTC | null | 164,901 | null | 39,278 | null | 1 | 25 | c#|.net|windows-services | 13,408 | <p>For critical error reporting, you are constrained to using the standard Service settings (in the properties of the installed service), or doing something yourself. This could be as simple a log file that logs unexpected errors (by using <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx" rel="noreferrer">AppDomain.UnhandledException</a> to catch and log them), using the Windows event log to log similar info, or having another process watch the service for errors (ie. the service stopping) and alerting someone.</p>
<p>Microsoft has an article entitled "<a href="http://msdn.microsoft.com/en-us/library/d56de412.aspx" rel="noreferrer">Introduction to Windows Service Applications</a>" that is a good general introduction to making services in .Net.</p>
<p>Some other things about developing Windows services from my experience:</p>
<ul>
<li>A Windows service is allowed about 30 seconds to start. After that, Windows will report it as not having started correctly. This means that you need to ensure that your <code>OnStart</code> method of the service kicks off a new thread to run the service and then returns.</li>
<li>Don't expect any user interaction (ie. message boxes, confirmations) because the service runs "headless" (ie. without a UI), so you cannot expect a user to interact with it.</li>
<li>Check the account that the service will run as to ensure that you are not running it as a user with unnecessarily high security privileges.</li>
<li>Make extensive use of logging (eg. log4net) so that you can see what the service is doing during runtime, as well as being able to diagnose any errors (by logging stack traces).</li>
<li>Make sure you use the correct version of InstallUtil (ie. 32 or 64 bit) to install the service with. Even better, let the service install itself using the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.installhelper.aspx" rel="noreferrer">ManagedInstallerClass.InstallHelper</a>.</li>
</ul> |
1,589,706 | Iterating over arbitrary dimension of numpy.array | <p>Is there function to get an iterator over an arbitrary dimension of a numpy array?</p>
<p>Iterating over the first dimension is easy...</p>
<pre><code>In [63]: c = numpy.arange(24).reshape(2,3,4)
In [64]: for r in c :
....: print r
....:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
</code></pre>
<p>But iterating over other dimensions is harder. For example, the last dimension:</p>
<pre><code>In [73]: for r in c.swapaxes(2,0).swapaxes(1,2) :
....: print r
....:
[[ 0 4 8]
[12 16 20]]
[[ 1 5 9]
[13 17 21]]
[[ 2 6 10]
[14 18 22]]
[[ 3 7 11]
[15 19 23]]
</code></pre>
<p>I'm making a generator to do this myself, but I'm surprised there isn't a function named something like numpy.ndarray.iterdim(axis=0) to do this automatically.</p> | 1,593,130 | 6 | 0 | null | 2009-10-19 16:27:11.747 UTC | 12 | 2021-06-14 20:41:54.593 UTC | 2009-10-20 05:59:41.493 UTC | null | 79,513 | null | 79,513 | null | 1 | 81 | python|numpy|loops | 71,253 | <p>What you propose is quite fast, but the legibility can be improved with the clearer forms:</p>
<pre><code>for i in range(c.shape[-1]):
print c[:,:,i]
</code></pre>
<p>or, better (faster, more general and more explicit):</p>
<pre><code>for i in range(c.shape[-1]):
print c[...,i]
</code></pre>
<p>However, the first approach above appears to be about twice as slow as the <code>swapaxes()</code> approach:</p>
<pre><code>python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
'for r in c.swapaxes(2,0).swapaxes(1,2): u = r'
100000 loops, best of 3: 3.69 usec per loop
python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
'for i in range(c.shape[-1]): u = c[:,:,i]'
100000 loops, best of 3: 6.08 usec per loop
python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
'for r in numpy.rollaxis(c, 2): u = r'
100000 loops, best of 3: 6.46 usec per loop
</code></pre>
<p>I would guess that this is because <code>swapaxes()</code> does not copy any data, and because the handling of <code>c[:,:,i]</code> might be done through general code (that handles the case where <code>:</code> is replaced by a more complicated slice).</p>
<p>Note however that the more explicit second solution <code>c[...,i]</code> is both quite legible and quite fast:</p>
<pre><code>python -m timeit -s 'import numpy; c = numpy.arange(24).reshape(2,3,4)' \
'for i in range(c.shape[-1]): u = c[...,i]'
100000 loops, best of 3: 4.74 usec per loop
</code></pre> |
1,969,096 | Saving changes after table edit in SQL Server Management Studio | <p>If I want to save any changes in a table, previously saved in SQL Server Management Studio (no data in table present) I get an error message:</p>
<blockquote>
<p>Saving changes is not permitted. The changes you have made require the
following tables to be dropped and re-created. You have either made
changes to a table that can't be re-created or enabled the option
Prevent saving changes that require the table to be re-created.</p>
</blockquote>
<p>What can prevent the table to be easily edited? Or, is it the usual way for SQL Server Management Studio to require re-creating table for editing? What is it - this <strong>"option Prevent saving changes"</strong>?</p> | 1,969,110 | 7 | 5 | null | 2009-12-28 11:43:21.42 UTC | 52 | 2022-06-26 06:41:12.463 UTC | 2017-03-10 13:56:14.797 UTC | null | 542,251 | null | 199,722 | null | 1 | 299 | sql|sql-server|ssms|database-table | 254,092 | <p>Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.</p>
<p>That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."</p> |
2,094,963 | PostgreSQL: improving pg_dump, pg_restore performance | <p>When I began, I used <code>pg_dump</code> with the default plain format. I was unenlightened.</p>
<p>Research revealed to me time and file size improvements with <code>pg_dump -Fc | gzip -9 -c > dumpfile.gz</code>. I was enlightened.</p>
<p>When it came time to create the database anew,</p>
<pre><code># create tablespace dbname location '/SAN/dbname';
# create database dbname tablespace dbname;
# alter database dbname set temp_tablespaces = dbname;
% gunzip dumpfile.gz # to evaluate restore time without a piped uncompression
% pg_restore -d dbname dumpfile # into a new, empty database defined above
</code></pre>
<p>I felt unenlightened: the restore took 12 hours to create the database that's only a fraction of what it will become:</p>
<pre><code># select pg_size_pretty(pg_database_size('dbname'));
47 GB
</code></pre>
<p>Because there are predictions this database will be a few terabytes, I need to look at improving performance now.</p>
<p>Please, enlighten me.</p> | 2,095,283 | 7 | 0 | null | 2010-01-19 16:18:40.473 UTC | 44 | 2022-08-18 14:57:15.857 UTC | 2010-12-02 20:30:19.687 UTC | null | 477,213 | null | 477,213 | null | 1 | 96 | performance|postgresql|backup|restore | 72,764 | <p>First check that you are getting reasonable IO performance from your disk setup. Then check that you PostgreSQL installation is appropriately tuned. In particular <code>shared_buffers</code> should be set correctly, <code>maintenance_work_mem</code> should be increased during the restore, <code>full_page_writes</code> should be off during the restore, <code>wal_buffers</code> should be increased to 16MB during the restore, <code>checkpoint_segments</code> should be increased to something like 16 during the restore, you shouldn't have any unreasonable logging on (like logging every statement executed), <code>auto_vacuum</code> should be disabled during the restore.</p>
<p>If you are on 8.4 also experiment with parallel restore, the --jobs option for pg_restore.</p> |
2,052,017 | Ravioli code - why an anti-pattern? | <p>I recently came across a term '<a href="http://en.wikipedia.org/wiki/God_object" rel="noreferrer">God object</a>' which was described as an 'anti-pattern'. I'd heard of bad coding practices, but I'd never heard them described thus.</p>
<p>So I headed off to Wikipedia to find out more, and I found that there is an anti-pattern called <a href="http://en.wikipedia.org/wiki/Ravioli_code#Ravioli_code" rel="noreferrer">'Ravioli code'</a> which is described as being "characterized by a number of small and (ideally) loosely-coupled software components."</p>
<p>I'm puzzled - why is this a bad thing?</p> | 2,052,051 | 8 | 4 | null | 2010-01-12 20:12:42.097 UTC | 3 | 2017-07-10 18:31:43.46 UTC | 2010-01-12 20:21:18.13 UTC | null | 84,651 | null | 192,131 | null | 1 | 39 | anti-patterns | 15,993 | <p>Spaghhetti:</p>
<blockquote>
<p>Spaghetti code is a <strong>pejorative</strong> term
for source code</p>
</blockquote>
<p>Ravioli:</p>
<blockquote>
<p>Ravioli code is a type of computer
program structure, characterized by a
number of small and (ideally)
loosely-coupled software components.
The term <strong>is in comparison</strong> with
spaghetti code, comparing program
structure to pasta;</p>
</blockquote>
<p>It's comparing them. It isn't saying it's an anti-pattern.</p>
<p>But I agree. The article is confusing. The problem is not with ravioli analogy but with the wikipedia article structure itself. It starts calling Spaghetti as a bad practice, then says some examples and after that say something about Ravioli code.</p>
<p>EDIT: They improved the article. Is an anti-pattern because</p>
<blockquote>
<p>While generally desirable from a coupling and cohesion perspective, overzealous separation and encapsulation of code can bloat call stacks and make navigation through the code for maintenance purposes more difficult.</p>
</blockquote> |
2,208,186 | Proper Table naming convention for a many-to-many intersect table | <p>I have a many to many relation for: Client and Broker tables (just an example). Obviously, each client can have multiple brokers and each broker can have multiple clients. What is considered the proper naming convention for the intersect table.... is it ClientBroker...?</p> | 2,208,199 | 8 | 1 | null | 2010-02-05 15:18:09.71 UTC | 12 | 2022-06-12 17:36:37.52 UTC | 2010-02-05 15:23:49.387 UTC | null | 17,675 | null | 17,675 | null | 1 | 52 | database-design | 35,052 | <p>I usually use the names of both of the joining tables.</p>
<p>So, in your case, ClientBroker.</p> |
1,742,938 | How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority" | <p>I have a WCF service hosted in IIS 7 using HTTPS. When I browse to this site in Internet Explorer, it works like a charm, this is because I <em>have</em> added the certificate to the local root certificate authority store.</p>
<p>I'm developing on 1 machine, so client and server are same machine. The certificate is self-signed directly from IIS 7 management snap in.</p>
<p>I continually get this error now...</p>
<blockquote>
<p>Could not establish trust relationship for the SSL/TLS secure channel with authority.</p>
</blockquote>
<p>... when called from client console.</p>
<p>I manually gave myself permissions and network service to the certificate, using <code>findprivatekey</code> and using <code>cacls.exe</code>.</p>
<p>I tried to connect to the service using SOAPUI, and that works, so it must be an issue in my client application, which is code based on what used to work with http.</p>
<p>Where else can I look I seem to have exhausted all possibilities as to why I can't connect?</p> | 1,742,967 | 19 | 2 | null | 2009-11-16 15:35:47.463 UTC | 37 | 2022-07-21 00:50:03.497 UTC | 2021-05-30 09:41:44.52 UTC | null | 5,468,463 | null | 41,543 | null | 1 | 147 | .net|wcf|iis|certificate | 375,088 | <p>As a workaround you could add a handler to the <code>ServicePointManager</code>'s <code>ServerCertificateValidationCallback</code> on the client side:</p>
<pre><code>System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
</code></pre>
<p>but be aware that <strong><em>this is not a good practice</em></strong> as it completely ignores the server certificate and tells the service point manager that whatever certificate is fine which can seriously compromise client security. You could refine this and do some custom checking (for certificate name, hash etc).
at least you can circumvent problems during development when using test certificates.</p> |
2,041,993 | How do I rename a Git repository? | <p><code>git mv</code> renames a file or directory in a repository. How do I rename the Git repository itself?</p> | 2,042,020 | 21 | 2 | null | 2010-01-11 13:11:30.25 UTC | 172 | 2022-09-20 14:35:05.437 UTC | 2019-10-08 15:38:10.16 UTC | null | 63,550 | null | 153,487 | null | 1 | 568 | git | 473,103 | <p>There are various possible interpretations of what is meant by renaming a Git repository: the displayed name, the repository directory, or the remote repository name. Each requires different steps to rename.</p>
<h2>Displayed Name</h2>
<p>Rename the displayed name (for example, shown by <code>gitweb</code>):</p>
<ol>
<li>Edit <code>.git/description</code> to contain the repository's name.</li>
<li>Save the file.</li>
</ol>
<h2>Repository Directory</h2>
<p>Git does not reference the name of the directory containing the repository, as used by <code>git clone master child</code>, so we can simply rename it:</p>
<ol>
<li>Open a command prompt (or file manager window).</li>
<li>Change to the directory that contains the repository directory (i.e., do not go into the repository directory itself).</li>
<li>Rename the directory (for example, using <code>mv</code> from the command line or the <kbd>F2</kbd> hotkey from a GUI).</li>
</ol>
<h2>Remote Repository</h2>
<p>Rename a remote repository as follows:</p>
<ol>
<li>Go to the remote host (for example, <a href="https://github.com/User/project" rel="noreferrer">https://github.com/User/project</a>).</li>
<li>Follow the host's instructions to rename the project (will differ from host to host, but usually <strong>Settings</strong> is a good starting point).</li>
<li>Go to your local repository directory (i.e., open a command prompt and change to the repository's directory).</li>
<li>Determine the new URL (for example, <code>[email protected]:User/project-new.git</code>)</li>
<li><p>Set the new URL using Git:</p>
<pre><code>git remote set-url origin [email protected]:User/project-new.git
</code></pre></li>
</ol> |
8,506,611 | Type DATE is not a defined system type | <p>Trying this to cast time away </p>
<pre><code> select CONVERT(char(10), [Reg Date1], 103) [Reg Date], Regs
from (
select cast(SetupDateTime as DATE) [Reg Date1]
, COUNT(distinct ID) [Regs]
from dbo.tbl_User
where cast(SetupDateTime as DATE)
between cast((DATEADD (dd , -7 , GETDATE())) AS DATE)
and cast((DATEADD (dd , -1 , GETDATE())) AS DATE)
group by cast(SetupDateTime as DATE)
) a
order by a.[Reg Date1]
</code></pre>
<p>but I get this error </p>
<blockquote>
<p>Msg 243, Level 16, State 1, Line 1<br>
Type DATE is not a defined system type.</p>
</blockquote> | 8,506,640 | 2 | 2 | null | 2011-12-14 15:00:03.73 UTC | null | 2015-08-23 09:22:17.327 UTC | 2015-08-23 09:22:17.327 UTC | null | 2,314,991 | null | 1,097,453 | null | 1 | 14 | sql-server|sql-server-2005 | 49,650 | <p>You are using SQL Server 2005 or earlier. Data type <a href="http://msdn.microsoft.com/en-us/library/bb630352.aspx" rel="noreferrer">date</a> was introduced in SQL Server 2008. Try to cast to <a href="http://msdn.microsoft.com/en-us/library/ms187819.aspx" rel="noreferrer">datetime</a> instead.</p>
<p>Have a look at this question on how to remove the time part from a datetime. <a href="https://stackoverflow.com/questions/1177449/best-approach-to-remove-time-part-of-datetime-in-sql-server">Best approach to remove time part of datetime in SQL Server</a></p> |
8,699,812 | What is the format specifier for unsigned short int? | <p>I have the following program </p>
<pre><code>#include <stdio.h>
int main(void)
{
unsigned short int length = 10;
printf("Enter length : ");
scanf("%u", &length);
printf("value is %u \n", length);
return 0;
}
</code></pre>
<p>Which when compiled using <code>gcc filename.c</code> issued the following warning (in the <code>scanf()</code> line). </p>
<p><code>warning: format β%uβ expects argument of type βunsigned int *β, but argument 2 has type βshort unsigned int *β [-Wformat]</code></p>
<p>I then referred the <code>C99 specification - 7.19.6 Formatted input/output functions</code> and couldn't understand the correct format specifier when using the length modifiers (like <code>short</code>, <code>long</code>, etc) with <code>unsigned</code> for <code>int</code> data type.</p>
<p>Is <code>%u</code> the correct specifier <code>unsigned short int</code>? If so why am I getting the above mentioned warning?! </p>
<p>EDIT:
Most of the time, I was trying <code>%uh</code> and it was still giving the warning. </p> | 8,699,826 | 4 | 2 | null | 2012-01-02 10:35:45.627 UTC | 33 | 2018-03-01 07:55:48.573 UTC | 2012-01-02 12:48:24.593 UTC | null | 1,056,289 | null | 1,056,289 | null | 1 | 155 | c|scanf | 341,344 | <p>Try using the <code>"%h"</code> modifier:</p>
<pre><code>scanf("%hu", &length);
^
</code></pre>
<blockquote>
<p>ISO/IEC 9899:201x - 7.21.6.1-7</p>
<p>Specifies that a following d , i , o , u , x , X , or n conversion
specifier applies to an argument with type <strong>pointer to short or
unsigned short</strong>.</p>
</blockquote> |
46,586,656 | ReactJS display fetch response onClick | <p>Im working on a ReactJS project where you can generate a random activity when pressing the generate button. Im doing a fetch to my api to display some data from it. This works fine. Now I want to do the fetch and display the returned data every time I click the generate button (which is in the home component). So the generate button has to do a new fetch and refresh the component. Also it has to be empty on default. I searched a while and can't find a relevant answer. Can some of you guys help me out? Thanks.</p>
<p><strong>fetch component</strong></p>
<pre><code>import React from "react";
export class ItemLister extends React.Component {
constructor() {
super();
this.state = { suggestion: "" };
}
componentDidMount() {
fetch("......./suggestions/random", {
method: "GET",
dataType: "JSON",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(resp => {
return resp.json();
})
.then(data => {
this.setState({ suggestion: data.suggestion });
})
.catch(error => {
console.log(error, "catch the hoop");
});
}
render() {
return <h2>{this.state.suggestion}</h2>;
}
}
</code></pre>
<p><strong>home component</strong></p>
<pre><code>import React from "react";
import { ItemLister } from "./apiCall";
export class Home extends React.Component {
constructor(props) {
super(props);
console.log();
window.sessionStorage.setItem("name", this.props.params.name);
window.sessionStorage.setItem("token", this.props.params.token);
}
render() {
return (
<div className="contentContainer AD">
<table>
<thead>
<tr>
<th>
<p>Het is heel leuk als het werkt!</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ItemLister />
</td>
</tr>
</tbody>
</table>
<div className="container center">
<button>GENERATE</button>
<button>SAVE</button>
<button>MATCH</button>
</div>
</div>
);
}
}
</code></pre> | 46,587,899 | 2 | 4 | null | 2017-10-05 13:18:32.607 UTC | 9 | 2019-03-18 02:46:52.407 UTC | 2019-03-18 02:46:52.407 UTC | null | 615,274 | null | 8,726,330 | null | 1 | 10 | reactjs|fetch | 40,577 | <p>I would say that you move your fetch logic to <code>home</code> component and maintain a state in <code>home</code> component just like you are doing in <code>Itemlister</code> component. Then all you have to do is pass your state to <code>Itemlister</code> component. Your home component will look like this</p>
<pre><code>export class Home extends React.Component {
constructor(props) {
super(props)
this.state = {suggestion: ""}
...
}
componentDidMount(){
// For initial data
this.fetchData();
}
fetchData = () => {
fetch("......./suggestions/random", {
method: "GET",
dataType: "JSON",
headers: {
"Content-Type": "application/json; charset=utf-8",
}
})
.then((resp) => {
return resp.json()
})
.then((data) => {
this.setState({ suggestion: data.suggestion })
})
.catch((error) => {
console.log(error, "catch the hoop")
})
}
render() {
return (
...
<tbody >
// Pass state to itemlister like this
<tr><td><ItemLister suggestion={this.state.suggestion}/></td></tr>
</tbody>
</table>
<div className="container center">
// Add event handler here. On every click it will fetch new data
<button onClick={this.fetchData}>GENERATE</button>
<button>SAVE</button>
<button>MATCH</button>
</div>
</div>
)
}
}
</code></pre>
<p>And your <code>ItemLister</code> component has the responsibility to display the data via props.</p>
<pre><code>export class ItemLister extends React.Component {
constructor() {
super();
}
render() {
return(
<h2>
{this.props.suggestion}
</h2>
)
}
}
</code></pre>
<p>As per the suggestion by <a href="https://stackoverflow.com/users/1695393/dubes">dubes</a> in comment, If you don't want to maintain any state in this component then you can make this functional component like this</p>
<pre><code>function ItemLister(props) {
return <h2>
{props.suggestion}
</h2>;
}
</code></pre> |
17,703,312 | What does EntityManager.flush do and why do I need to use it? | <p>I have an EJB where I am saving an object to the database. In an example I have seen, once this data is saved (EntityManager.persist) there is a call to EntityManager.flush(); Why do I need to do this? The object I am saving is not attached and not used later in the method. In fact, once saved the method returns and I would expect the resources to be released. (The example code does this on a remove call as well.)</p>
<pre><code>if (somecondition) {
entityManager.persist(unAttachedEntity);
} else {
attachedEntityObject.setId(unAttachedEntity.getId());
}
entityManager.flush();
</code></pre> | 17,703,822 | 5 | 0 | null | 2013-07-17 15:00:12.177 UTC | 18 | 2021-03-24 21:00:53.92 UTC | 2018-10-17 03:14:21.217 UTC | null | 3,641,067 | null | 207,933 | null | 1 | 74 | java|jpa|entitymanager | 156,420 | <p>A call to <code>EntityManager.flush();</code> will force the data to be persist in the database immediately as <code>EntityManager.persist()</code> will not (depending on how the EntityManager is configured : <a href="http://docs.oracle.com/javaee/5/api/javax/persistence/FlushModeType.html">FlushModeType </a>(AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited). </p> |
44,633,798 | What is the meaning of list[:] in this code? | <p>This code is from Python's Documentation. I'm a little confused.</p>
<pre><code>words = ['cat', 'window', 'defenestrate']
for w in words[:]:
if len(w) > 6:
words.insert(0, w)
print(words)
</code></pre>
<p>And the following is what I thought at first:</p>
<pre><code>words = ['cat', 'window', 'defenestrate']
for w in words:
if len(w) > 6:
words.insert(0, w)
print(words)
</code></pre>
<p>Why does this code create a infinite loop and the first one doesn't?</p> | 44,633,938 | 4 | 9 | null | 2017-06-19 14:53:51.003 UTC | 16 | 2019-04-15 14:01:46.223 UTC | 2018-12-28 19:32:14.81 UTC | null | 4,909,087 | null | 8,013,696 | null | 1 | 59 | python|list|for-loop|iteration | 21,342 | <p>This is one of the gotchas! of python, that can escape beginners.</p>
<p>The <code>words[:]</code> is the magic sauce here. </p>
<p>Observe:</p>
<pre><code>>>> words = ['cat', 'window', 'defenestrate']
>>> words2 = words[:]
>>> words2.insert(0, 'hello')
>>> words2
['hello', 'cat', 'window', 'defenestrate']
>>> words
['cat', 'window', 'defenestrate']
</code></pre>
<p>And now without the <code>[:]</code>:</p>
<pre><code>>>> words = ['cat', 'window', 'defenestrate']
>>> words2 = words
>>> words2.insert(0, 'hello')
>>> words2
['hello', 'cat', 'window', 'defenestrate']
>>> words
['hello', 'cat', 'window', 'defenestrate']
</code></pre>
<p>The main thing to note here is that <code>words[:]</code> returns a <code>copy</code> of the existing list, so you are iterating over a copy, which is not modified. </p>
<p>You can check whether you are referring to the same lists using <code>id()</code>:</p>
<p>In the first case:</p>
<pre><code>>>> words2 = words[:]
>>> id(words2)
4360026736
>>> id(words)
4360188992
>>> words2 is words
False
</code></pre>
<p>In the second case:</p>
<pre><code>>>> id(words2)
4360188992
>>> id(words)
4360188992
>>> words2 is words
True
</code></pre>
<p>It is worth noting that <code>[i:j]</code> is called the <em>slicing operator</em>, and what it does is it returns a fresh copy of the list starting from index <code>i</code>, upto (but not including) index <code>j</code>.</p>
<p>So, <code>words[0:2]</code> gives you</p>
<pre><code>>>> words[0:2]
['hello', 'cat']
</code></pre>
<p>Omitting the starting index means it defaults to <code>0</code>, while omitting the last index means it defaults to <code>len(words)</code>, and the end result is that you receive a copy of the <em>entire</em> list.</p>
<hr>
<p>If you want to make your code a little more readable, I recommend the <code>copy</code> module.</p>
<pre><code>from copy import copy
words = ['cat', 'window', 'defenestrate']
for w in copy(words):
if len(w) > 6:
words.insert(0, w)
print(words)
</code></pre>
<p>This basically does the same thing as your first code snippet, and is much more readable.</p>
<p>Alternatively (as mentioned by DSM in the comments) and on python >=3, you may also use <code>words.copy()</code> which does the same thing. </p> |
6,742,820 | Malloc function (dynamic memory allocation) resulting in an error when it is used globally | <pre><code>#include<stdio.h>
#include<string.h>
char *y;
y=(char *)malloc(40); // gives an error here
int main()
{
strcpy(y,"hello world");
}
</code></pre>
<hr>
<pre><code>error: conflicting types for 'y'
error: previous declaration of 'y' was here
warning: initialization makes integer from pointer without a cast
error: initializer element is not constant
warning: data definition has no type or storage class
warning: passing arg 1 of `strcpy' makes pointer from integer without cast
</code></pre>
<p>Now the real question is, can't we make the dynamic memory allocation globally? Why does it show an error when I use malloc globally? And the code works with no error if I put <code>malloc</code> statement inside the main function or some other function. Why is this so?</p>
<pre><code>#include<stdio.h>
#include<string.h>
char *y;
int main()
{
y=(char *)malloc(40);
strcpy(y,"hello world");
}
</code></pre> | 6,742,841 | 3 | 1 | null | 2011-07-19 05:52:21.213 UTC | 9 | 2015-01-08 05:39:44.817 UTC | 2014-02-17 20:59:43.403 UTC | null | 759,866 | null | 834,032 | null | 1 | 12 | c|malloc|global-variables|dynamic-memory-allocation | 22,895 | <p>You can't execute code outside of functions. The only thing you can do at global scope is declaring variables (and initialize them with compile-time constants).</p>
<p><code>malloc</code> is a function call, so that's invalid outside a function.</p>
<p>If you initialize a global pointer variable with <code>malloc</code> from your main (or any other function really), it will be available to all other functions where that variable is in scope (in your example, all functions within the file that contains <code>main</code>).</p>
<p>(Note that global variables should be avoided when possible.)</p> |
6,806,880 | How to create a UI like the new market or Google plus? | <p>I was wondering if there is an "official" way to create apps for Android that will have the same design as the new <a href="http://www.youtube.com/watch?v=5Pbo-d62ivY&feature=player_embedded&t=10">Android market</a> or Google+ app. By that I mean having the possibility to slide to the left/right to change the view, have the list on the top, etc.. (any Android user probably get what I mean)</p>
<p>If there is no official way, do you have any tips on how to reproduce these effets ?</p> | 6,807,264 | 4 | 3 | null | 2011-07-24 12:48:29.637 UTC | 19 | 2013-03-16 02:50:53.393 UTC | 2013-03-16 02:50:53.393 UTC | null | 918,414 | null | 860,221 | null | 1 | 20 | android|mobile|user-interface|google-play|google-plus | 10,082 | <p>I believe this is what your referring to ' Android Compatibility Package '</p>
<p><a href="http://developer.android.com/sdk/compatibility-library.html" rel="noreferrer">http://developer.android.com/sdk/compatibility-library.html</a></p>
<p>This allows the following:</p>
<blockquote>
<p>ViewPager: A ViewGroup that manages the layout for the child views, which the user can swipe between.</p>
<p>PagerAdapter: An adapter that populates the ViewPager with the views that represent each page.</p>
</blockquote>
<p>These are used in the G+ app</p>
<blockquote>
<p>ListFragment</p>
</blockquote>
<p>is used in the Market app.</p>
<p>Your best reading the URL I posted at the top for full description and use.</p>
<p>Another way to get best practive UI is to read the source of the Google Official Apps:</p>
<p><a href="http://code.google.com/p/iosched/source/browse/#hg/android/src/com/google/android/apps/iosched/ui" rel="noreferrer">Google IO Sched Source</a></p>
<p>You might also want to check out some of the Google IO Presentations:</p>
<p>On the web: <a href="http://www.google.com/events/io/2011/sessions/designing-and-implementing-android-uis-for-phones-and-tablets.html" rel="noreferrer">Implementing UIs IO 2011</a></p>
<p>On your phone: <a href="https://market.android.com/details?id=com.blundell.googleio.free" rel="noreferrer">All IO 2011 & 2010 Videos</a> ( Shameless Plug :p )</p> |
6,680,568 | SQL: Select most recent date for each category | <p>I'm pulling data from a database and one of the tables contain two columns that together identify a location and another column containing a date of each time it was serviced. Is it possible to write a SQL query such that I get the most recent time that each location was serviced?</p>
<p>So if my raw data looks like this:</p>
<pre><code>category_a category_b date
1 a 1/1/01
1 a 2/2/02
1 b 1/2/01
1 b 2/3/02
2 a 1/3/01
2 a 2/4/02
2 b 1/4/01
2 b 2/5/02
</code></pre>
<p>then the query would return this:</p>
<pre><code>category_a category_b date
1 a 2/2/02
1 b 2/3/02
2 a 2/4/02
2 b 2/5/02
</code></pre>
<p>This would be easy to do if the database was authored in such a way that the category combinations were stored in a separate table. However, I don't control this database, so I can't make changes to it.</p> | 6,680,622 | 4 | 3 | null | 2011-07-13 14:31:37.977 UTC | 4 | 2014-04-13 16:45:49.403 UTC | null | null | null | null | 173,292 | null | 1 | 31 | sql | 53,056 | <pre><code>SELECT
category_a,
category_b,
MAX(date)
FROM
Some_Unnamed_Table
GROUP BY
category_a,
category_b
ORDER BY
category_a,
category_b
</code></pre>
<p>I certainly don't mind helping people when I can, or I wouldn't be on this site, but did you really search for an answer for this before posting?</p> |
36,055,585 | Renderer multiple selectRootElement Issue | <p>I am trying to use Renderer.selectRootElement to get some elements from my Component, as described <a href="https://stackoverflow.com/questions/36036885/how-to-find-element-in-a-component/36037121#36037121">here</a>.</p>
<p>Everything works fine, unless I select only one element (<a href="http://plnkr.co/edit/pofXHp6yiko61nCpImWV?p=preview" rel="nofollow noreferrer">plnkr</a>).</p>
<p>As you can see, I have created a component:</p>
<pre><code>export class ExampleComponent implements OnInit{
@Input() start: any;
@Input() end: any;
constructor(public _renderer:Renderer){
};
ngOnChanges(){
}
ngOnInit(){
console.log("NG ON CHAN START DATE",this.start);
console.log("NG ON INIT END DATE",this.end);
var container = this._renderer.selectRootElement('.container');
console.log(container);
var inner1 = this._renderer.selectRootElement('.inner1');
console.log(inner1);
var inner2 = this._renderer.selectRootElement('.inner2');
console.log(inner2);
}
}
</code></pre>
<p>When I try to run this, I have an error of :</p>
<blockquote>
<p>EXCEPTION: The selector ".inner1" did not match any elements in [{{exampleData.end}} in MainViewComponent@3:65]</p>
</blockquote>
<p>(however, in my app, when only the first container is found, then none others are found).</p>
<p>Any ideas where does this come from?</p>
<p><strong>UPDATE</strong></p>
<p>I found out that the directive is not invoked fully - only div with class <code>container</code> gets added to the HTML.</p>
<p><a href="https://i.stack.imgur.com/ftKWN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ftKWN.png" alt="enter image description here"></a></p> | 36,059,595 | 2 | 4 | null | 2016-03-17 08:52:14.863 UTC | 10 | 2019-04-03 00:58:31.827 UTC | 2018-11-09 15:55:36.28 UTC | null | 2,528,907 | null | 4,345,344 | null | 1 | 5 | angular | 17,706 | <h1>DO NOT USE selectRootElement</h1>
<p>Its purpose is not to select random elements by selector in your components view.</p>
<p>Simply see its implementation in <a href="https://github.com/angular/angular/blob/c8a1a14b87e5907458e8e87021e47f9796cb3257/packages/platform-browser/src/dom/dom_renderer.ts" rel="noreferrer">DomRootRenderer</a></p>
<pre class="lang-js prettyprint-override"><code>selectRootElement(selector: string): Element {
var el = DOM.querySelector(this._rootRenderer.document, selector);
if (isBlank(el)) {
throw new BaseException(`The selector "${selector}" did not match any elements`);
}
DOM.clearNodes(el);
return el;
}
</code></pre>
<p>Do you see something interesting there? It's removing the nodes inside the element! Why would it do that? Because its purpose it's to grab the root element! So which one is the root element? Does this sound familiar?</p>
<pre><code><my-app>
Loading...
</my-app>
</code></pre>
<p>Yes! That's the root element. Okay then, but <em>what's wrong with using <code>selectRootElement</code> if I only want to grab the element? It returns the element without its children and nothing changes in the view!</em> Well, you can still use it of course, but you will be defeating its purpose and misusing it just like people do with <code>DynamicComponentLoader#loadAsRoot</code> and subscribing manually to EventEmitter.</p>
<p>Well, after all its name, <code>selectRootElement</code>, says pretty much what it does, doesn't it?</p>
<p>You have two options to grab elements inside your view, and two correct options.</p>
<ul>
<li>Using a local variable and @ViewChild</li>
</ul>
<pre class="lang-js prettyprint-override"><code><div #myElement>...</div>
@ViewChild('myElement') element: ElementRef;
ngAfterViewInit() {
// Do something with this.element
}
</code></pre>
<ul>
<li>Create a directive to grab the element you want</li>
</ul>
<pre class="lang-js prettyprint-override"><code>@Directive({
selector : '.inner1,inner2' // Specify all children
// or make one generic
// selector : '.inner'
})
class Children {}
template : `
<div class="container">
<div class="inner1"></div>
<div class="inner2"></div>
<!-- or one generic
<div class="inner"></div>
<div class="inner"></div>
-->
</div>
`
class Parent (
@ViewChildren(Children) children: QueryList<Children>;
ngAfterViewInit() {
// Do something with this.children
}
)
</code></pre> |
52,063,759 | Passing default list argument to dataclasses | <p>I would like to pass default argument in my class,
but somehow I am having problem:</p>
<pre><code>from dataclasses import dataclass, field
from typing import List
@dataclass
class Pizza():
ingredients: List = field(default_factory=['dow', 'tomatoes'])
meat: str = field(default='chicken')
def __repr__(self):
return 'preparing_following_pizza {} {}'.format(self.ingredients, self.meat)
</code></pre>
<p>If I now try to instantiate <code>Pizza</code>, I get the following error:</p>
<pre><code>>>> my_order = Pizza()
Traceback (most recent call last):
File "pizza.py", line 13, in <module>
Pizza()
File "<string>", line 2, in __init__
TypeError: 'list' object is not callable
</code></pre>
<p>What am I doing wrong?</p> | 52,064,202 | 2 | 12 | null | 2018-08-28 17:54:32.81 UTC | 13 | 2021-10-25 06:13:52.433 UTC | 2021-10-06 14:00:07.713 UTC | null | 13,990,016 | null | 5,745,211 | null | 1 | 76 | python|python-3.x|python-dataclasses | 75,722 | <p>From <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.field" rel="noreferrer">the <code>dataclasses.field</code> docs</a>:</p>
<blockquote>
<p>The parameters to <code>field()</code> are:</p>
<ul>
<li><strong>default_factory:</strong> If provided, <strong>it must be a zero-argument callable</strong> that
will be called when a default value is needed for this field. Among
other purposes, this can be used to specify fields with mutable
default values, as discussed below. It is an error to specify both
default and default_factory.</li>
</ul>
</blockquote>
<p>Your <code>default_factory</code> is not a 0-argument callable but a list, which is the reason for the error:</p>
<pre><code>from dataclasses import dataclass, field
from typing import List
@dataclass
class Pizza():
ingredients: List = field(default_factory=['dow', 'tomatoes']) # <- wrong!
</code></pre>
<p>Use a lambda function instead:</p>
<pre><code>@dataclass
class Pizza():
ingredients: List = field(default_factory=lambda: ['dow', 'tomatoes'])
</code></pre> |
23,627,871 | Twitter bootstrap - Make a table row inactive | <p>Hi I want to make a row in a table inactive. Even if it is easy to hack by myself and add a custom css with the same colour of the inactive elements of my current theme I think it can be handles by bootstrap itself.</p>
<p>Any suggestions?</p> | 23,628,412 | 4 | 3 | null | 2014-05-13 09:45:48.593 UTC | 3 | 2020-03-25 15:22:17.197 UTC | null | null | null | null | 433,685 | null | 1 | 19 | css|twitter-bootstrap-3 | 41,783 | <p>Bootstrap has a few elements you might find helpful:</p>
<hr>
<p>Use contextual classes to change row colors:</p>
<pre><code><!-- On rows -->
<tr class="active">...</tr>
<tr class="success">...</tr>
<tr class="warning">...</tr>
<tr class="danger">...</tr>
<tr class="info">...</tr>
<!-- On cells (`td` or `th`) -->
<tr>
<td class="active">...</td>
<td class="success">...</td>
<td class="warning">...</td>
<td class="danger">...</td>
<td class="info">...</td>
</tr>
</code></pre>
<p><a href="http://getbootstrap.com/css/#tables-contextual-classes">http://getbootstrap.com/css/#tables-contextual-classes</a></p>
<hr>
<p>Use contextual colors to change the color of text:</p>
<pre><code><p class="text-muted">...</p>
<p class="text-primary">...</p>
<p class="text-success">...</p>
<p class="text-info">...</p>
<p class="text-warning">...</p>
<p class="text-danger">...</p>
</code></pre>
<p><a href="http://getbootstrap.com/css/#helper-classes-colors">http://getbootstrap.com/css/#helper-classes-colors</a></p>
<hr>
<p>The disabled element is primary for form elements and buttons. Check that out here, </p> |
18,308,876 | Jquery: How to dynamically SHOW image using the "value" of <input type="file"> Field | <p>I was wondering whether there is a way to dynamically display an image that a user just uploaded to the input type="file" field.</p>
<p>For example, so far I have the following code:</p>
<p><br></p>
<p><strong>image_upload.html</strong></p>
<pre><code><form id ="image_upload_form" action="" method="post" enctype="multipart/form-data">
<input id ="id_iamge" type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<div id="image_view">
<img id="uploaded_image">
</div>
</code></pre>
<p><br>
<strong>upload.js</strong></p>
<pre><code>$(document).ready(function() {
$("#id_image").change(file_select);
});
function file_select(event) {
$("#uploaded_image").attr("src", $("#id_image").val());
}
</code></pre>
<p><br></p>
<p>So I basically want to show the image that the user just uploaded on the Field.</p>
<p>Of course, I know I can easily view the image if the user already SUBMITTED the form, and when the image is already inside my Database server.</p>
<p>However, I want to preview the image BEFORE the image is submitted into the database server.</p>
<p>In order to do this, I guess I have to find out the PATH of the Image in the Uploader's own computer and then set that "Local path" as the "src" of the image.</p>
<p>Is there a way to fetch this LOCAL PATH of the image that the user just submitted?</p>
<p>(My Javascript code above obviously didn't work, since it just sets the NAME of the image file, not the absolute Path, as the "src". For example, when I run that code and upload an image, I get this:</p>
<p><strong>The Result:</strong></p>
<pre><code><img id="uploaded_image" src="random_image.jpg" />
</code></pre>
<p>which doesn't show anything.</p> | 18,309,091 | 2 | 10 | null | 2013-08-19 07:54:25.91 UTC | 2 | 2016-09-26 18:13:44.633 UTC | null | null | null | null | 2,492,270 | null | 1 | 11 | javascript|jquery | 38,990 | <p>Take a look at this sample, this should work: <a href="http://jsfiddle.net/LvsYc/" rel="noreferrer">http://jsfiddle.net/LvsYc/</a></p>
<p>HTML:</p>
<pre><code><form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
</code></pre>
<p>JS:</p>
<pre><code>function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
</code></pre> |
15,501,030 | div inside php echo | <p>i have this: </p>
<pre><code><?php
if ( ($cart->count_product) > 0) {
print $cart->count_product;
} else {
print '';
}
?>
</code></pre>
<p>and i need to put <code>print $cart->count_product</code> inside of <code><div class="my_class"></div></code></p>
<p>I tried different ways, but i'm missing something in syntax. I'll be glad if someone could help. </p> | 15,501,054 | 6 | 5 | null | 2013-03-19 13:35:52.693 UTC | 2 | 2013-03-19 13:59:03.047 UTC | 2013-03-19 13:44:53.427 UTC | null | 314 | null | 1,650,803 | null | 1 | 8 | php | 119,494 | <p>You can do the following:</p>
<pre><code>echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';
</code></pre>
<p>If you want to have it inside your statement, do this:</p>
<pre><code>if($cart->count_product > 0)
{
echo '<div class="my_class">'.$cart->count_product.'</div>';
}
</code></pre>
<p>You don't need the <code>else</code> statement, since you're only going to output the above when it's truthy anyway.</p> |
39,971,929 | What are variable annotations? | <p>Python 3.6 is about to be released. <a href="https://www.python.org/dev/peps/pep-0494/" rel="noreferrer">PEP 494 -- Python 3.6 Release Schedule</a> mentions the end of December, so I went through <a href="https://docs.python.org/3.6/whatsnew/3.6.html" rel="noreferrer">What's New in Python 3.6</a> to see they mention the <em>variable annotations</em>:</p>
<blockquote>
<p><a href="https://www.python.org/dev/peps/pep-0484" rel="noreferrer">PEP 484</a> introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:</p>
<pre><code>primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
</code></pre>
<p>Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in a special attribute <code>__annotations__</code> of a class or module. In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the <code>__annotations__</code> attribute.</p>
</blockquote>
<p>So from what I read they are part of the type hints coming from Python 3.5, described in <a href="https://stackoverflow.com/q/32557920/1983854">What are Type hints in Python 3.5</a>.</p>
<p>I follow the <code>captain: str</code> and <code>class Starship</code> example, but not sure about the last one: How does <code>primes: List[int] = []</code> explain? Is it defining an empty list that will just allow integers?</p> | 39,972,031 | 2 | 3 | null | 2016-10-11 07:00:15.003 UTC | 59 | 2021-10-06 12:54:53.607 UTC | 2021-10-06 12:54:53.607 UTC | null | 13,990,016 | null | 1,983,854 | null | 1 | 119 | python|python-3.x|type-hinting|python-typing | 68,514 | <p>Everything between <code>:</code> and the <code>=</code> is a type hint, so <code>primes</code> is indeed defined as <code>List[int]</code>, and initially set to an empty list (and <code>stats</code> is an empty dictionary initially, defined as <code>Dict[str, int]</code>).</p>
<p><code>List[int]</code> and <code>Dict[str, int]</code> are not part of the next syntax however, these were already defined in the Python 3.5 typing hints PEP. The 3.6 <a href="https://www.python.org/dev/peps/pep-0526/">PEP 526 β <em>Syntax for Variable Annotations</em></a> proposal <em>only</em> defines the syntax to attach the same hints to variables; before you could only attach type hints to variables with comments (e.g. <code>primes = [] # List[int]</code>).</p>
<p>Both <code>List</code> and <code>Dict</code> are <em>Generic</em> types, indicating that you have a list or dictionary mapping with specific (concrete) contents. </p>
<p>For <code>List</code>, there is only one 'argument' (the elements in the <code>[...]</code> syntax), the type of every element in the list. For <code>Dict</code>, the first argument is the key type, and the second the value type. So <em>all</em> values in the <code>primes</code> list are integers, and <em>all</em> key-value pairs in the <code>stats</code> dictionary are <code>(str, int)</code> pairs, mapping strings to integers.</p>
<p>See the <a href="https://docs.python.org/3/library/typing.html#typing.List"><code>typing.List</code></a> and <a href="https://docs.python.org/3/library/typing.html#typing.Dict"><code>typing.Dict</code></a> definitions, the <a href="https://docs.python.org/3/library/typing.html#generics">section on <em>Generics</em></a>, as well as <a href="https://www.python.org/dev/peps/pep-0483">PEP 483 β <em>The Theory of Type Hints</em></a>.</p>
<p>Like type hints on functions, their use is optional and are also considered <em>annotations</em> (provided there is an object to attach these to, so globals in modules and attributes on classes, but not locals in functions) which you could introspect via the <code>__annotations__</code> attribute. You can attach arbitrary info to these annotations, you are not strictly limited to type hint information.</p>
<p>You may want to read the <a href="https://www.python.org/dev/peps/pep-0526/">full proposal</a>; it contains some additional functionality above and beyond the new syntax; it specifies when such annotations are evaluated, how to introspect them and how to declare something as a class attribute vs. instance attribute, for example.</p> |
51,279,270 | Class static variable initialization order | <p>I have a class A which has two static variables. I'd like to initialize one with another, unrelated static variable, just like this:</p>
<pre><code>#include <iostream>
class A
{
public:
static int a;
static int b;
};
int A::a = 200;
int a = 100;
int A::b = a;
int main(int argc, char* argv[])
{
std::cout << A::b << std::endl;
return 0;
}
</code></pre>
<p>The output is 200. So, could anyone tell me why? </p> | 51,279,348 | 4 | 5 | null | 2018-07-11 07:08:58.297 UTC | 6 | 2018-07-18 06:30:42.127 UTC | 2018-07-11 07:49:07.71 UTC | null | 817,643 | null | 10,063,155 | null | 1 | 61 | c++|scope|language-lawyer | 2,414 | <p>That's correct according to the lookup rules. <a href="https://timsong-cpp.github.io/cppwp/n4659/basic.lookup.unqual#13" rel="noreferrer">[basic.lookup.unqual]/13</a> says:</p>
<blockquote>
<p>A name used in the definition of a static data member of class X
(after the qualified-id of the static member) is looked up as if the
name was used in a member function of X. [βNote: [class.static.data]
further describes the restrictions on the use of names in the
definition of a static data member. βββend noteβ]</p>
</blockquote>
<p>Since the unqualified <code>a</code> is looked up <em>as if</em> you are inside a member function, it must find the member <code>A::a</code> first. The initialization order of <code>A::a</code> and <code>A::b</code> doesn't affect the lookup, though it affects how well defined the result is.</p> |
302,983 | Best Django 'CMS' component for integration into existing site | <p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p>
<p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p> | 3,892,818 | 7 | 0 | null | 2008-11-19 19:04:55.003 UTC | 11 | 2011-03-06 03:48:00.573 UTC | null | null | null | kkubasik | 39,058 | null | 1 | 15 | python|django|content-management-system | 12,727 | <p>I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.</p>
<p>The grid comparison at djangopluggables.com certainly can make evaluating each of these easier.</p>
<p><strong>django-cms</strong> is the most full-featured and is something you could actually hand over to clients without being irresponsible. Even though it has features for integrating other apps, it doesn't have the extensibility/integration of FeinCMS or the simplicity of django-page-cms. That being said, I think the consensus is that this is the best Open Source CMS for Django. However, it's docs are a little lacking. <strong><em>update</em></strong>: <em>I have been told that integrating apps into DjangoCMS 2.1 has been improved.</em></p>
<p><strong>FeinCMS</strong> - Is a great set of tools for combining and building CMS functionality into your own apps. It's not "out of the box" at all, which means that you can integrate it however you want. It doesn't want to take over your urls.py or control how you route pages. It's probably a prototype for the next-generation of truly pluggable apps in Django. - We are moving from django-page-cms to FeinCMS because our primary models is high volume eCommerce and I have custom content-types I want to integrate that aren't blogs or flash. Good documentation and support as well.</p>
<p><strong>Django-page-cms</strong> - Is great if you want to just have some "About Us" pages around your principle application. Its menu system is not truly hierarchical and building your page presentation is up to you. But it's very simple, unobtrusive, and very easy to slap into your app and get a navigation going that clients can manage, or even for yourself. It has no docs that I know of, but you won't really need any. Read the code and you will get it all in 30 minutes or less.</p>
<p><em>update</em></p>
<p><strong>Mezzanine</strong> - Is a very well designed CMS and one that I have finally settled on for most of my client work, mostly because it has an integrated eCommerce portion. But beyond that it has very extensible page models, and a custom admin interface that a client might be willing to use. It also has the best "out of the box" experience i.e. You can have a full fledged site up with one command.</p> |
524,428 | Cannot implicitly convert List<T> to Collection<T> | <p>This is a compiler error (slightly changed for readability).</p>
<p>This one always puzzled me. FxCop tells that this is a bad thing to return <code>List<T></code> and classes that are derived from <code>Collection<T></code> should be preferable as return types.</p>
<p>Also, FxCop says that it is OK to use <code>List<T></code> for internal data storage/manipulation. Ok, I get it, but what I don't get is why the compiler complains about trying to implicitly convert <code>List<T></code> to <code>Collection<T></code>. Isn't <code>List<T></code> more interface-charged and functional? Why prohibit implicit conversion?</p>
<p>And another question that stems from above: is the <code>new List<int>(some collection<int>)</code> constructor expensive?</p> | 524,436 | 7 | 0 | null | 2009-02-07 19:39:21.397 UTC | 8 | 2022-08-10 03:05:32.397 UTC | 2022-08-10 03:05:32.397 UTC | Jon Skeet | 2,288,578 | Valentin Vasiliev | 430,254 | null | 1 | 46 | c#|generics|collections | 107,083 | <p><code>List<T></code> doesn't derive from <code>Collection<T></code> - it does, however, implement <code>ICollection<T></code>. That would be a better choice of return type.</p>
<p>As for the <code>new List<int>(some collection<int>)</code> question - it partly depends on what the collection is. If it implements <code>ICollection<T></code> (at execution time) then the constructor can use its <code>Count</code> property to create the list with the right initial capacity before iterating through it and adding each item. If it doesn't implement <code>ICollection<T></code> then it's just equivalent to:</p>
<pre><code>List<int> list = new List<int>();
foreach (int x in otherCollection)
{
list.Add(x);
}
</code></pre>
<p>Still nice to have in a convenient constructor, but not hugely efficient - it can't be, really.</p>
<p>I don't believe the constructor does anything cunning for arrays, which it potentially could - using <code>Array.Copy</code> or whatever to just copy the lot in one go rather than iterating though. (Likewise if it were another <code>List<T></code> it could get at the backing array and copy that directly.)</p> |
153,584 | How to iterate over a timespan after days, hours, weeks and months? | <p>How do I iterate over a timespan after days, hours, weeks or months?</p>
<p>Something like:</p>
<pre><code>for date in foo(from_date, to_date, delta=HOURS):
print date
</code></pre>
<p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p> | 155,172 | 7 | 1 | null | 2008-09-30 15:35:22.6 UTC | 31 | 2019-09-16 17:03:15.977 UTC | 2019-09-16 17:03:15.977 UTC | DzinX | 355,230 | sverrejoh | 473 | null | 1 | 74 | python|datetime | 50,597 | <p>Use <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> and its rrule implementation, like so:</p>
<pre><code>from dateutil import rrule
from datetime import datetime, timedelta
now = datetime.now()
hundredDaysLater = now + timedelta(days=100)
for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):
print dt
</code></pre>
<p>Output is</p>
<pre><code>2008-09-30 23:29:54
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54
</code></pre>
<p>Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.</p>
<p>This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.</p> |
1,066,677 | How to iterate over a std::map full of strings in C++ | <p>I have the following issue related to iterating over an associative array of strings defined using <code>std::map</code>.</p>
<pre><code>-- snip --
class something
{
//...
private:
std::map<std::string, std::string> table;
//...
}
</code></pre>
<p>In the constructor I populate table with pairs of string keys associated to string data. Somewhere else I have a method <code>toString</code> that returns a string object that contains all the keys and associated data contained in the table object(as key=data format).</p>
<pre><code>std::string something::toString()
{
std::map<std::string, std::string>::iterator iter;
std::string* strToReturn = new std::string("");
for (iter = table.begin(); iter != table.end(); iter++) {
strToReturn->append(iter->first());
strToReturn->append('=');
strToRetunr->append(iter->second());
//....
}
//...
}
</code></pre>
<p>When I'm trying to compile I get the following error:</p>
<pre><code>error: "error: no match for call to β(std::basic_string<char,
std::char_traits<char>, std::allocator<char> >) ()β".
</code></pre>
<p>Could somebody explain to me what is missing, what I'm doing wrong?
I only found some discussion about a similar issue in the case of <code>hash_map</code> where the user has to define a hashing function to be able to use <code>hash_map</code> with <code>std::string</code> objects. Could be something similar also in my case?</p> | 1,066,706 | 8 | 1 | null | 2009-06-30 23:51:54.747 UTC | 7 | 2020-01-21 04:11:04.667 UTC | 2018-10-23 12:19:31.25 UTC | null | 3,204,551 | null | 131,404 | null | 1 | 62 | c++|dictionary|iterator|std|stdmap | 138,782 | <p>Your main problem is that you are calling a method called <code>first()</code> in the iterator. What you are meant to do is use the property called <code>first</code>:</p>
<pre><code>...append(iter->first) rather than ...append(iter->first())
</code></pre>
<p>As a matter of style, you shouldn't be using <code>new</code> to create that string.</p>
<pre><code>std::string something::toString()
{
std::map<std::string, std::string>::iterator iter;
std::string strToReturn; //This is no longer on the heap
for (iter = table.begin(); iter != table.end(); ++iter) {
strToReturn.append(iter->first); //Not a method call
strToReturn.append("=");
strToReturn.append(iter->second);
//....
// Make sure you don't modify table here or the iterators will not work as you expect
}
//...
return strToReturn;
}
</code></pre>
<p><strong>edit:</strong> facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop </p>
<pre><code>for (auto& item: table) {
...
}
</code></pre> |
844,461 | return only Digits 0-9 from a String | <p>I need a regular expression that I can use in VBScript and .NET that will return only the numbers that are found in a string. </p>
<p>For Example any of the following "strings" should return only <strong>1231231234</strong></p>
<ul>
<li>123 123 1234</li>
<li>(123) 123-1234</li>
<li>123-123-1234</li>
<li>(123)123-1234</li>
<li>123.123.1234</li>
<li>123 123 1234</li>
<li>1 2 3 1 2 3 1 2 3 4</li>
</ul>
<p>This will be used in an email parser to find telephone numbers that customers may provide in the email and do a database search.</p>
<p>I may have missed a similar regex but I did search on regexlib.com.</p>
<p>[EDIT] - Added code generated by <a href="http://www.regexbuddy.com/" rel="noreferrer">RegexBuddy</a> after setting up musicfreak's answer</p>
<p><strong>VBScript Code</strong></p>
<pre><code>Dim myRegExp, ResultString
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "[^\d]"
ResultString = myRegExp.Replace(SubjectString, "")
</code></pre>
<p><strong>VB.NET</strong></p>
<pre><code>Dim ResultString As String
Try
Dim RegexObj As New Regex("[^\d]")
ResultString = RegexObj.Replace(SubjectString, "")
Catch ex As ArgumentException
'Syntax error in the regular expression
End Try
</code></pre>
<p><strong>C#</strong></p>
<pre><code>string resultString = null;
try {
Regex regexObj = new Regex(@"[^\d]");
resultString = regexObj.Replace(subjectString, "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
</code></pre> | 844,471 | 8 | 1 | null | 2009-05-10 00:57:11.743 UTC | 15 | 2022-08-26 09:43:19.88 UTC | 2009-05-10 05:47:45.243 UTC | null | 30,453 | null | 3,747 | null | 1 | 77 | c#|vb.net|regex|vbscript|code-generation | 80,554 | <p>I don't know if VBScript has some kind of a "regular expression replace" function, but if it does, then you could do something like this pseudocode:</p>
<pre><code>reg_replace(/\D+/g, '', your_string)
</code></pre>
<p>I don't know VBScript so I can't give you the exact code but this would remove anything that is not a number.</p>
<p>EDIT: Make sure to have the global flag (the "g" at the end of the regexp), otherwise it will only match the first non-number in your string.</p> |
867,365 | In Java, can I define an integer constant in binary format? | <p>Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?</p> | 8,569,929 | 8 | 4 | null | 2009-05-15 07:14:56.1 UTC | 17 | 2022-04-21 09:43:36.73 UTC | 2022-04-21 09:43:36.73 UTC | null | 5,446,749 | null | 39,529 | null | 1 | 88 | java|syntax|binary | 84,034 | <p>So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:</p>
<pre><code>byte fourTimesThree = 0b1100;
byte data = 0b0000110011;
short number = 0b111111111111111;
int overflow = 0b10101010101010101010101010101011;
long bow = 0b101010101010101010101010101010111L;
</code></pre>
<p>And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:</p>
<pre><code>public static final int thingy = 0b0101;
</code></pre>
<p>Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:</p>
<pre><code>byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte
</code></pre>
<p>Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:</p>
<pre><code>int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011;
long bow = 0b1__01010101__01010101__01010101__01010111L;
</code></pre>
<p>Now isn't that nice and clean, not to mention highly readable?</p>
<p>I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details:</p>
<p><a href="http://www.theserverside.com/tutorial/Java-7-and-Binary-Notation">Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam</a></p> |
1,231,188 | emacs list-buffers behavior | <p>In GNU emacs, every time I hit <kbd>Ctrl-x Ctrl-b</kbd> to see all of my buffers, the window is split to show the buffer list, or if I have my window already split in 2 (for instance, I will have a shell running in the lower window), the buffer list appears in the other window. </p>
<p>My desired behavior is for the buffer list to appear in my active window so that I can select the buffer I want and continue to working in the same window, rather than having to <kbd>Ctrl-x Ctrl-o</kbd> to the other buffer, selecting the buffer (with <kbd>enter</kbd>) and editing that buffer in the other window... I've googled for it but it doesn't seem to be a common desire? I wonder if anyone has an elispy (or other) solution?</p> | 1,231,270 | 9 | 0 | null | 2009-08-05 04:28:18.11 UTC | 8 | 2015-01-22 11:08:39.35 UTC | 2010-01-30 13:18:35.887 UTC | null | 745 | null | 143,476 | null | 1 | 50 | emacs|elisp | 10,736 | <p>You might want to rebind <kbd>C-x C-b</kbd> to invoke <code>buffer-menu</code> rather than <code>list-buffers</code>: </p>
<pre><code>(global-set-key "\C-x\C-b" 'buffer-menu)
</code></pre> |
170,394 | An implementation of the fast Fourier transform (FFT) in C# | <p>Where can I find a free, very quick, and reliable implementation of FFT in C#?</p>
<p>That can be used in a product? Or are there any restrictions?</p> | 170,413 | 9 | 0 | null | 2008-10-04 14:12:19.573 UTC | 53 | 2021-02-03 10:06:41.813 UTC | 2016-04-27 15:00:18.48 UTC | Hallgrim | 63,550 | Anna | 4,044 | null | 1 | 76 | c#|signal-processing|fft | 135,414 | <p><a href="http://code.google.com/p/aforge/" rel="noreferrer">AForge.net</a> is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/<a href="https://github.com/andrewkirillov/AForge.NET/blob/master/Sources/Imaging/ComplexImage.cs" rel="noreferrer">ComplexImage.cs</a> for usage, Sources/Math/<a href="https://github.com/andrewkirillov/AForge.NET/blob/master/Sources/Math/FourierTransform.cs" rel="noreferrer">FourierTransform.cs</a> for implemenation)</p> |
33,034 | How do banks remember "your computer"? | <p>As many of you probably know, online banks nowadays have a security system whereby you are asked some personal questions before you even enter your password. Once you have answered them, you can choose for the bank to "remember this computer" so that in the future you can login by only entering your password.</p>
<p>How does the "remember this computer" part work? I know it cannot be cookies, because the feature still works despite the fact that I clear all of my cookies. I thought it might be by IP address, but my friend with a dynamic IP claims it works for him, too (but maybe he's wrong). He thought it was MAC address or something, but I strongly doubt that! So, is there a concept of https-only cookies that I don't clear?</p>
<p>Finally, the programming part of the question: how can I do something similar myself in, say, PHP?</p> | 33,059 | 10 | 0 | null | 2008-08-28 18:37:07.513 UTC | 11 | 2015-12-03 19:46:25.873 UTC | null | null | null | Anonymous Rex | 3,508 | null | 1 | 24 | https|onlinebanking|sessiontracking | 12,393 | <p>In fact they most probably use cookies. An alternative for them would be to use "<a href="http://www.bestflashanimationsite.com/tutorials/4/" rel="noreferrer">flash cookies</a>" (officially called "<a href="http://www.adobe.com/support/flash/action_scripts/local_shared_object/" rel="noreferrer">Local Shared Objects</a>"). They are similar to cookies in that they are tied to a website and have an upper size limit, but they are maintained by the flash player, so they are invisible to any browser tools.</p>
<p>To clear them (and test this theory), you can use <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=52697ee8&sliceId=2" rel="noreferrer">the instructions provided by Adobe</a>. An other nifty (or maybe worrying, depending on your viewpoint) feature is that the LSO storage is shared by all browsers, so using LSO you can identify users <em>even if they switched browser</em> (as long as they are logged in as the same user).</p> |
286,846 | Describe the architecture you use for Java web applications? | <p><strong>Let's share Java based web application architectures!</strong></p>
<p>There are lots of different architectures for web applications which are to be implemented using Java. The answers to this question may serve as a library of various web application designs with their pros and cons. While I realize that the answers will be subjective, let's try to be as objective as we can and motivate the pros and cons we list.</p>
<p>Use the detail level you prefer for describing your architecture. For your answer to be of any value you'll at least have to describe the major technologies and ideas used in the architecture you describe. And last but not least, <em>when</em> should we use your architecture?</p>
<p>I'll start...</p>
<hr>
<h1>Overview of the architecture</h1>
<p>We use a 3-tier architecture based on open standards from Sun like Java EE, Java Persistence API, Servlet and Java Server Pages.</p>
<ul>
<li>Persistence</li>
<li>Business</li>
<li>Presentation</li>
</ul>
<p>The possible communication flows between the layers are represented by:</p>
<pre><code>Persistence <-> Business <-> Presentation
</code></pre>
<p>Which for example means that the presentation layer never calls or performs persistence operations, it always does it through the business layer. This architecture is meant to fulfill the demands of a high availability web application.</p>
<h2>Persistence</h2>
<p>Performs create, read, update and delete (<a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" rel="noreferrer">CRUD</a>) persistence operations. In our case we are using (<a href="http://java.sun.com/javaee/technologies/persistence.jsp" rel="noreferrer">Java Persistence API</a>) JPA and we currently use <a href="http://www.hibernate.org/" rel="noreferrer">Hibernate</a> as our persistence provider and use <a href="http://www.hibernate.org/397.html" rel="noreferrer">its EntityManager</a>.</p>
<p>This layer is divided into multiple classes, where each class deals with a certain type of entities (i.e. entities related to a shopping cart might get handled by a single persistence class) and is <em>used</em> by one and only one <em>manager</em>.</p>
<p>In addition this layer also stores <a href="http://en.wikipedia.org/wiki/Java_Persistence_API#Entities" rel="noreferrer">JPA entities</a> which are things like <code>Account</code>, <code>ShoppingCart</code> etc.</p>
<h2>Business</h2>
<p>All logic which is tied to the web application functionality is located in this layer. This functionality could be initiating a money transfer for a customer who wants to pay for a product on-line using her/his credit card. It could just as well be creating a new user, deleting a user or calculating the outcome of a battle in a web based game.</p>
<p>This layer is divided into multiple classes and each of these classes is annotated with <code>@Stateless</code> to become a <a href="http://en.wikipedia.org/wiki/Session_Beans" rel="noreferrer">Stateless Session Bean</a> (SLSB). Each SLSB is called a <em>manager</em> and for instance a manager could be a class annotated as mentioned called <code>AccountManager</code>.</p>
<p>When <code>AccountManager</code> needs to perform CRUD operations it makes the appropriate calls to an instance of <code>AccountManagerPersistence</code>, which is a class in the persistence layer. A rough sketch of two methods in <code>AccountManager</code> could be:</p>
<pre><code>...
public void makeExpiredAccountsInactive() {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
// Calls persistence layer
List<Account> expiredAccounts = amp.getAllExpiredAccounts();
for(Account account : expiredAccounts) {
this.makeAccountInactive(account)
}
}
public void makeAccountInactive(Account account) {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
account.deactivate();
amp.storeUpdatedAccount(account); // Calls persistence layer
}
</code></pre>
<p>We use <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html" rel="noreferrer">container manager transactions</a> so we don't have to do transaction demarcation our self's. What basically happens under the hood is we initiate a transaction when entering the SLSB method and commit it (or rollback it) immediately before exiting the method. It's an example of convention over configuration, but we haven't had a need for anything but the default, Required, yet.</p>
<p>Here is how The Java EE 5 Tutorial from Sun explains the <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html" rel="noreferrer">Required transaction attribute</a> for Enterprise JavaBeans (EJB's):</p>
<blockquote>
<p>If the client is running within a
transaction and invokes the enterprise
beanβs method, the method executes
within the clientβs transaction. If
the client is not associated with a
transaction, the container starts a
new transaction before running the
method.</p>
<p>The Required attribute is the implicit
transaction attribute for all
enterprise bean methods running with
container-managed transaction
demarcation. You typically do not set
the Required attribute unless you need
to override another transaction
attribute. Because transaction
attributes are declarative, you can
easily change them later.</p>
</blockquote>
<h2>Presentation</h2>
<p>Our presentation layer is in charge of... presentation! It's responsible for the user interface and shows information to the user by building HTML pages and receiving user input through GET and POST requests. We are currently using the old <a href="http://java.sun.com/products/servlet/" rel="noreferrer">Servlet</a>'s + Java Server Pages (<a href="http://java.sun.com/products/jsp/" rel="noreferrer">JSP</a>) combination.</p>
<p>The layer calls methods in <em>managers</em> of the business layer to perform operations requested by the user and to receive information to show in the web page. Sometimes the information received from the business layer are less complex types as <code>String</code>'s and <code>int</code>egers, and at other times <a href="http://en.wikipedia.org/wiki/Java_Persistence_API#Entities" rel="noreferrer">JPA entities</a>.</p>
<h1>Pros and cons with the architecture</h1>
<h2>Pros</h2>
<ul>
<li>Having everything related to a specific way of doing persistence in this layer only means we can swap from using JPA into something else, without having to re-write anything in the business layer.</li>
<li>It's easy for us to swap our presentation layer into something else, and it's likely that we will if we find something better.</li>
<li>Letting the EJB container manage transaction boundaries is nice.</li>
<li>Using Servlet's + JPA is easy (to begin with) and the technologies are widely used and implemented in lots of servers.</li>
<li>Using Java EE is supposed to make it easier for us to create a high availability system with <a href="http://en.wikipedia.org/wiki/Load_balancing_(computing)" rel="noreferrer">load balancing</a> and <a href="http://en.wikipedia.org/wiki/Failover" rel="noreferrer">fail over</a>. Both of which we feel that we must have.</li>
</ul>
<h2>Cons</h2>
<ul>
<li>Using JPA you may store often used queries as named queries by using the <code>@NamedQuery</code> annotation on the JPA entity class. If you have as much as possible related to persistence in the persistence classes, as in our architecture, this will spread out the locations where you may find queries to include the JPA entities as well. It will be harder to overview persistence operations and thus harder to maintain.</li>
<li>We have JPA entities as part of our persistence layer. But <code>Account</code> and <code>ShoppingCart</code>, aren't they really business objects? It is done this way as you have to touch these classes and turn them into entities which JPA knows how to handle.</li>
<li>The JPA entities, which are also our business objects, are created like Data Transfer Objects (<a href="http://en.wikipedia.org/wiki/Data_Transfer_Object" rel="noreferrer">DTO</a>'s), also known as Value Objects (VO's). This results in an <a href="http://en.wikipedia.org/wiki/Anemic_Domain_Model" rel="noreferrer">anemic domain model</a> as the business objects have no logic of their own except accessor methods. All logic is done by our managers in the business layer, which results in a more procedural programming style. It's not good object oriented design, but maybe that's not a problem? (After all object orientation isn't the only programming paradigm which has delivered results.)</li>
<li>Using EJB and Java EE introduces a bit of complexity. And we can't use purely Tomcat (adding an EJB micro-container isn't <em>purely</em> Tomcat).</li>
<li>There are lots of issues with using Servlet's + JPA. Use Google for more information about these issues.</li>
<li>As the transactions are closed when exiting the business layer we can't load any information from JPA entities which is configured to be loaded from the database when it's needed (using <code>fetch=FetchType.LAZY</code>) from inside the presentation layer. It will trigger an exception. Before returning an entity containing these kinds of fields we have to be sure to call the relevant getter's. Another option is to use Java Persistence Query Language (<a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnbtg.html" rel="noreferrer">JPQL</a>) and do a <code>FETCH JOIN</code>. However both of these options are a little bit cumbersome.</li>
</ul> | 286,893 | 10 | 3 | 2008-11-13 12:55:32.957 UTC | 2008-11-13 12:55:32.957 UTC | 172 | 2016-10-31 20:09:31.67 UTC | null | null | null | user14070 | null | null | 1 | 148 | java|architecture|jakarta-ee | 83,088 | <p>Ok I'll do a (shorter) one:</p>
<ul>
<li>Frontend : <a href="https://tapestry.apache.org/index.html" rel="noreferrer">Tapestry</a> (3 for older projects, 5 for newer projects)</li>
<li>Business layer: Spring</li>
<li>DAO's : Ibatis</li>
<li>Database : Oracle</li>
</ul>
<p>We use Sping transaction support, and start transactions upon entering the service layer, propagating down to the DAO call's. The Service layer has the most bussines model knowledge, and the DAO's do relatively simple CRUD work.</p>
<p>Some more complicated query stuff is handled by more complicated queries in the backend for performance reasons.</p>
<p>Advantages of using Spring in our case is that we can have country/language dependant instances, which are behind a Spring Proxy class. Based on the user in the session, the correct country/language implementation is used when doing a call.</p>
<p>Transaction management is nearly transparent, rollback on runtime exceptions. We use unchecked exceptions as much as possible. We used to do checked exceptions, but with the introduction of Spring I see the benefits of unchecked exceptions, only handling exceptions when you can. It avoids a lot of boilerplate "catch/rethrow" or "throws" stuff.</p>
<p>Sorry it's shorter than your post, hope you find this interesting...</p> |
998,552 | What are some problems best/worst addressed by functional programming? | <p>I've often heard that functional programming solves a lot of problems that are difficult in procedural/imperative programming. But I've also heard that it isn't great at some other problems that procedural programming is just naturally great at.</p>
<p>Before I crack open my book on Haskell and dive into functional programming, I'd like at least a basic idea of what I can really use it for (outside the examples in the book). So, what are those things that functional programming excels at? What are the problems that it is not well suited for?</p>
<h2>Update</h2>
<p>I've got some good answers about this so far. I can't wait to start learning Haskell now--I just have to wait until I master C :)</p>
<p>Reasons why functional programming is great:</p>
<ul>
<li>Very concise and succinct -- it can express complex ideas in short, unobfuscated statements.</li>
<li>Is easier to verify than imperative languages -- good where safety in a system is critical.</li>
<li>Purity of functions and immutability of data makes concurrent programming more plausible.</li>
<li>Well suited for scripting and writing compilers (I would appreciate to know why though).</li>
<li>Math related problems are solved simply and beautifully.</li>
</ul>
<p>Areas where functional programming struggles:</p>
<ul>
<li><em>Debatable</em>: web applications (though I guess this would depend on the application).</li>
<li>Desktop applications (although it depends on the language probably, F# would be good at this wouldn't it?).</li>
<li>Anything where performance is critical, such as game engines.</li>
<li>Anything involving lots of program state.</li>
</ul> | 998,578 | 11 | 5 | null | 2009-06-15 21:43:06.427 UTC | 23 | 2013-03-19 14:36:11.693 UTC | 2013-03-19 14:36:11.693 UTC | null | 1,039,608 | null | 84,478 | null | 1 | 42 | haskell|functional-programming | 7,971 | <p>Functional programming excels at succinctness, owing to the existence of <a href="http://en.wikipedia.org/wiki/Higher-order_function" rel="noreferrer">higher level functions</a> (map, lfold, grep) and <a href="http://en.wikipedia.org/wiki/Type_inference" rel="noreferrer">type inference</a>.</p>
<p>It is also excellent at <a href="http://en.wikipedia.org/wiki/Generic_programming" rel="noreferrer">generic programming</a>, for the same reasons, and that further increases the ability to express complex ideas in a short statement without obfuscation.</p>
<p>I appreciate these properties since they make <a href="http://en.wikipedia.org/wiki/Interactive_programming" rel="noreferrer">interactive programming</a> plausible. (e.g. <a href="http://www.r-project.org/" rel="noreferrer">R</a>, <a href="http://www.smlnj.org/" rel="noreferrer">SML</a>).</p>
<p>I suspect that functional programming can also be verified more readily that other programming approaches, which is advantageous in safety critical systems (Nuclear Power Stations and Medical Devices).</p> |
444,080 | Do you recommend using semicolons after every statement in JavaScript? | <p>In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?</p>
<p>If you're unfamiliar with the rules, there's a description of semicolon insertion on the <a href="http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html" rel="nofollow noreferrer">Mozilla site</a>. Here's the key point:</p>
<blockquote>
<p>If the first through the n<sup>th</sup> tokens of a JavaScript program form are grammatically valid but the first through the n+1<sup>st</sup> tokens are not and there is a line break between the n<sup>th</sup> tokens and the n+1<sup>st</sup> tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the n<sup>th</sup> and the n+1<sup>st</sup> tokens.</p>
</blockquote>
<p>That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)</p>
<p><a href="https://stackoverflow.com/questions/42247/are-semicolons-needed-after-an-object-literal-assignment-in-javascript">This stackoverflow question</a> is related, but only talks about a specific scenario.</p> | 444,082 | 11 | 0 | 2009-01-14 18:19:11.88 UTC | 2009-01-14 18:14:04.26 UTC | 161 | 2012-11-18 20:01:52.667 UTC | 2017-05-23 12:34:25.273 UTC | anon | -1 | anon | null | null | 1 | 51 | javascript | 213,153 | <p>Yes, you should use semicolons after every statement in JavaScript.</p> |
24,891 | C Memory Management | <p>I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.</p>
<p>Can someone show me (with code examples) an example of when you would have to do some "memory management" ?</p> | 24,922 | 12 | 1 | null | 2008-08-24 06:50:56.497 UTC | 67 | 2021-10-11 07:42:44.63 UTC | 2008-09-02 01:54:13.19 UTC | Chris Hanson | 714 | The.Anti.9 | 2,128 | null | 1 | 98 | c|memory | 49,279 | <p>There are two places where variables can be put in memory. When you create a variable like this:</p>
<pre><code>int a;
char c;
char d[16];
</code></pre>
<p>The variables are created in the "<strong>stack</strong>". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion.</p>
<p>Many beginner examples will use only stack variables.</p>
<p>The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables.</p>
<p>If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B".</p>
<p>Plan B is called the "<strong>heap</strong>". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways:</p>
<pre><code>int size;
// ...
// Set size to some value, based on information available at run-time. Then:
// ...
char *p = (char *)malloc(size);
</code></pre>
<p>(Note that variables in the heap are not manipulated directly, but via pointers)</p>
<p>Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with:</p>
<pre><code>free(p);
</code></pre>
<p>What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake <em>before</em> you are actually done with it.</p>
<p>In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and .NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance.</p>
<p><em>(I have glossed over many details to give a simpler, but hopefully more leveled answer)</em></p> |
796,412 | How to turn plural words singular? | <p>I'm preparing some table names for an ORM, and I want to turn plural table names into single entity names. My only problem is finding an algorithm that does it reliably. Here's what I'm doing right now:</p>
<ol>
<li>If a word ends with <em>-ies</em>, I replace the ending with <em>-y</em></li>
<li>If a word ends with <em>-es</em>, I remove this ending. This doesn't always work however - for example, it replaces <em>Types</em> with <em>Typ</em></li>
<li>Otherwise, I just remove the trailing <em>-s</em></li>
</ol>
<p>Does anyone know of a better algorithm?</p> | 796,445 | 13 | 4 | null | 2009-04-28 06:05:17.997 UTC | 10 | 2022-05-31 19:20:44.587 UTC | 2022-05-31 19:20:44.587 UTC | null | 2,756,409 | null | 9,476 | null | 1 | 22 | algorithm|nlp|lemmatization | 23,250 | <p>Those are all general rules (and good ones) but English is not a language for the faint of heart :-).</p>
<p>My own preference would be to have a transformation engine along with a set of transformations (surprisingly enough) for doing the actual work. You would run through the transformations (from specific to general) and, when a match was found, apply the transformation to the word and stop.</p>
<p>Regular expressions would be an ideal approach to this due to their expressiveness. An example rule set:</p>
<pre><code> 1. If the word is fish, return fish.
2. If the word is sheep, return sheep.
3. If the word is "radii", return "radius".
4. If the word ends in "ii", replace that "ii" with "us" (octopii,virii).
5. If a word ends with -ies, replace the ending with -y
6. If a word ends with -es, remove it.
7. Otherwise, just remove any trailing -s.
</code></pre>
<p>Note the requirement to keep this transformation set up to date. For example, let's say someone adds the table name <code>types</code>. This would currently be captured by rule <code>#6</code> and you would get the singular value <code>typ</code>, which is obviously wrong.</p>
<p>The solution is to insert a new rule somewhere <em>before</em> <code>#6</code>, something like:</p>
<pre><code> 3.5: If the word is "types", return "type".
</code></pre>
<p>for a very specific transformation, or perhaps somewhere later if it can be made more general.</p>
<p>In other words, you'll basically need to keep this transformation table updated as you find all those wondrous exceptions that English has spawned over the centuries.</p>
<hr />
<p>The <em>other</em> possibility is to not waste your time with general rules at all.</p>
<p>Since the use case of this requirement is currently only to singularise the table names, and that set of table names will be relatively tiny (at least compared to the set of plural English words), just create <em>another</em> table (or some sort of data structure) called <code>singulars</code> which maps all the current plural table names (<code>employees</code>, <code>customers</code>) to singular object names (<code>employee</code>, <code>customer</code>).</p>
<p>Then every time a table is added to your schema, ensure you add an entry to the singulars "table" so you can singularize it.</p> |
638,496 | What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)? | <p>Which of the following code is fastest/best practice for converting some object x?</p>
<pre><code>int myInt = (int)x;
</code></pre>
<p>or</p>
<pre><code>int myInt = Convert.ToInt32(x);
</code></pre>
<p>or</p>
<pre><code>int myInt = Int32.Parse(x);
</code></pre>
<p>or in the case of a string 's'</p>
<pre><code>int myInt;
Int32.TryParse(s, out myInt);
</code></pre>
<p>I'm curious on which performs the fastest for datatypes which have a method in Convert, not just ints. I just used int as an example.</p>
<p>Edit: This case arose from getting information back from a datatable. Will (int) still work the fastest? </p>
<p>From some testing, when object x =123123123, int performs the fastest, like many have said. When x is a string, Parse runs the fastest (note: cast throws an exception). What I am really curious is how they run when the value is being retrieved in the following way: </p>
<pre><code>foreach(DataRow row in someTable.Rows)
{
myInt = (int)row["some int value"];
myInt2 = Int.Parse(row["some int value"]);
myInt2 = Convert.ToInt32(row["some int value"]);
}
</code></pre> | 638,519 | 15 | 2 | null | 2009-03-12 12:55:22.21 UTC | 7 | 2022-06-05 08:19:00.597 UTC | 2009-03-12 13:30:42.593 UTC | phsr | 53,587 | phsr | 53,587 | null | 1 | 49 | c#|optimization|casting | 36,731 | <p>Why don't you just try it a couple of thousand times?</p>
<p>(this goes for all "What is fastest:" questions)</p>
<hr>
<p>Hmmm, lots of downvotes over the years... I guess I should expand on this answer.</p>
<p>The above statement was made with a degree of flippancy in my youth, however I still agree with its sentiment. It is not worthwhile spending time creating a SO question asking others what they think is faster out of two or three operations that take less than 1ms each.</p>
<p>The fact that one might take a cycle or two longer than the other will almost certainly be negligible in day-to-day usage. And if you ever notice a performance problem in your application when you are converting millions of objects to ints, <strong>that's</strong> the point where you can profile the <em>actual</em> code, and you'll easily be able to test whether the int conversion is actually the bottleneck.</p>
<p>And whereas today it's the object-int converter, tomorrow maybe you'll think your object-DateTime converter is taking a long time. Would you create another SO question to find out what's the fastest method?</p>
<p>As for your situation (no doubt long since resolved by now), as mentioned in a comment, you are querying a database, so object-int conversion is the least of your worries. If I was you I would use any of the conversion methods you mentioned. If a problem arises I would isolate the call, using a profiler or logging. Then when I notice that object-int conversion is being done a million times and the total time taken by that conversion seems relatively high, I would change to using a different conversion method and re-profile. Pick the conversion method that takes the least time. You could even test this in a separate solution, or even LINQPad, or Powershell etc.</p> |
791,959 | Download a specific tag with Git | <p>I'm trying to figure out how I can download a particular tag of a Git repository - it's one version behind the current version.</p>
<p>I saw there was a tag for the previous version on the git web page, with object name of something long hex number. </p>
<p>But the version name is "<code>Tagged release 1.1.5</code>" according the site.</p>
<p>I tried a command like this (with names changed):</p>
<pre><code>git clone http://git.abc.net/git/abc.git my_abc
</code></pre>
<p>And I did get something - a directory, a bunch of subdirectories, etc. </p>
<p>If it's the whole repository, how do I get at the version I'm seeking? If not, how do I download that particular version? </p> | 792,027 | 16 | 4 | null | 2009-04-27 01:15:12.417 UTC | 584 | 2021-09-03 03:47:18.007 UTC | 2017-01-29 19:05:29.91 UTC | null | 5,265,403 | null | 64,895 | null | 1 | 2,076 | git|git-clone|git-tag | 1,548,083 | <pre class="lang-bash prettyprint-override"><code>$ git clone
</code></pre>
<p>will give you the whole repository.</p>
<p>After the clone, you can list the tags with <code>$ git tag -l</code> and then checkout a specific tag:</p>
<pre class="lang-bash prettyprint-override"><code>$ git checkout tags/<tag_name>
</code></pre>
<p>Even better, checkout and create a branch (otherwise you will be on a branch named after the revision number of tag):</p>
<pre class="lang-bash prettyprint-override"><code>$ git checkout tags/<tag_name> -b <branch_name>
</code></pre> |
651,535 | Management Studio default file save location | <p>Open a new query window. Write some SQL. Save the script, the Save File As
dialog box opens - but always to the same default location in the Profiles
directory. Is there any way to set my default file location? ...Like I used
to do with apps from the 1980s?</p>
<p>Under Tools|Options a default location can be specified for query results.
I need the same thing for new queries (the text editor). Tried changing
locations in the Registry but SSMS just overwrote my changes. Any
suggestions?</p>
<p>(I saw this unanswered question at <a href="http://www.eggheadcafe.com/software/aspnet/30098335/management-studio-default.aspx" rel="noreferrer">http://www.eggheadcafe.com/software/aspnet/30098335/management-studio-default.aspx</a>
and I had same exact question so I just reposted it here)</p> | 6,693,957 | 16 | 1 | null | 2009-03-16 18:09:04.93 UTC | 14 | 2021-11-10 20:20:10.087 UTC | 2015-05-12 13:53:19.523 UTC | null | 1,118,488 | jayrdub | 45,767 | null | 1 | 68 | sql-server|ssms | 102,497 | <p>I know this is an old question, but I found a link expaining how to do this properly, at least for SQL 2005. Think it will work for later versions as well.</p>
<p><a href="https://web.archive.org/web/20110829003107/http://visualstudiohacks.com/options/changing-the-my-projects-folder-location-and-other-settings-in-ssms//" rel="nofollow noreferrer">Changing the my projects folder</a></p>
<blockquote>
<p>The settings are stored in an <code>.vssettings</code> XML file in <code>My Documents\SQL Server Management Studio\Settings</code> folder. Make sure you close SSMS
before making changes to this file: SSMS writes to it when you close
the application and will overwrite any changes you make. To change the
<code>My Projects</code> folder, you are looking for this line:</p>
</blockquote>
<pre><code> <PropertyValue name="ProjectsLocation">%vsspv_user_documents%\My
Projects</PropertyValue>
</code></pre>
<blockquote>
<p>The value inside is the location of the <code>My Projects</code> folder. Simply
change the value, and the next time you open SSMS the <code>My Projects</code>
folder will be mapped.</p>
</blockquote> |
26,845 | Do you use distributed version control? | <p>I'd like to hear from people who are using distributed version control (aka distributed revision control, decentralized version control) and how they are finding it. What are you using, Mercurial, Darcs, Git, Bazaar? Are you still using it? If you've used client/server rcs in the past, are you finding it better, worse or just different? What could you tell me that would get me to jump on the bandwagon? Or jump off for that matter, I'd be interested to hear from people with negative experiences as well. </p>
<p>I'm currently looking at replacing our current source control system (Subversion) which is the impetus for this question.</p>
<p>I'd be especially interested in anyone who's used it with co-workers in other countries, where your machines may not be on at the same time, and your connection is very slow.</p>
<p>If you're not sure what distributed version control is, here are a couple articles:</p>
<p><a href="http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/" rel="nofollow noreferrer">Intro to Distributed Version Control</a></p>
<p><a href="http://en.wikipedia.org/wiki/Distributed_revision_control" rel="nofollow noreferrer">Wikipedia Entry</a></p> | 27,033 | 18 | 0 | null | 2008-08-25 20:46:10.427 UTC | 10 | 2009-05-08 16:37:04.097 UTC | 2009-04-10 16:30:58.597 UTC | Chris Fournier | 287 | Chris Blackwell | 1,329,401 | null | 1 | 37 | version-control|dvcs|revision | 2,921 | <p>I've been using Mercurial both at work and in my own personal projects, and I am really happy with it. The advantages I see are:</p>
<ol>
<li><strong>Local version control.</strong> Sometimes I'm working on something, and I want to keep a version history on it, but I'm not ready to push it to the central repositories. With distributed VCS, I can just commit to my local repo until it's ready, without branching. That way, if other people make changes that I need, I can still get them and integrate them into my code. When I'm ready, I push it out to the servers.</li>
<li><strong>Fewer merge conflicts.</strong> They still happen, but they seem to be less frequent, and are less of a risk, because all the code is checked in to my local repo, so even if I botch the merge, I can always back up and do it again.</li>
<li><strong>Separate repos as branches.</strong> If I have a couple development vectors running at the same time, I can just make several clones of my repo and develop each feature independently. That way, if something gets scrapped or slipped, I don't have to pull pieces out. When they're ready to go, I just merge them together.</li>
<li><strong>Speed.</strong> Mercurial is much faster to work with, mostly because most of your common operations are local.</li>
</ol>
<p>Of course, like any new system, there was some pain during the transition. You have to think about version control differently than you did when you were using SVN, but overall I think it's very much worth it.</p> |
51,470 | How do I reset a sequence in Oracle? | <p>In <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a>, I can do something like this:</p>
<pre><code>ALTER SEQUENCE serial RESTART WITH 0;
</code></pre>
<p>Is there an Oracle equivalent?</p> | 93,633 | 18 | 3 | null | 2008-09-09 09:36:39.32 UTC | 68 | 2022-07-26 18:10:34.4 UTC | 2017-08-25 15:48:32.007 UTC | null | 3,357,935 | Mauli | 917 | null | 1 | 193 | sql|database|oracle|sequence | 670,486 | <p>Here is a good procedure for resetting any sequence to 0 from Oracle guru <a href="http://asktom.oracle.com" rel="noreferrer">Tom Kyte</a>. Great discussion on the pros and cons in the links below too.</p>
<pre><code>[email protected]>
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
l_val number;
begin
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by -' || l_val ||
' minvalue 0';
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/
</code></pre>
<p>From this page: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592" rel="noreferrer">Dynamic SQL to reset sequence value</a><br>
Another good discussion is also here: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597" rel="noreferrer">How to reset sequences?</a></p> |
1,284,423 | Read entire file in Scala? | <p>What's a simple and canonical way to read an entire file into memory in Scala? (Ideally, with control over character encoding.)</p>
<p>The best I can come up with is:</p>
<pre><code>scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_)
</code></pre>
<p>or am I supposed to use one of <a href="https://stackoverflow.com/questions/731365/reading-and-displaying-data-from-a-txt-file">Java's god-awful idioms</a>, the best of which (without using an external library) seems to be:</p>
<pre><code>import java.util.Scanner
import java.io.File
new Scanner(new File("file.txt")).useDelimiter("\\Z").next()
</code></pre>
<p>From reading mailing list discussions, it's not clear to me that <code>scala.io.Source</code> is even supposed to be the canonical I/O library. I don't understand what its intended purpose is, exactly.</p>
<p>... I'd like something dead-simple and easy to remember. For example, in these languages it's very hard to forget the idiom ...</p>
<pre><code>Ruby open("file.txt").read
Ruby File.read("file.txt")
Python open("file.txt").read()
</code></pre> | 1,284,446 | 19 | 4 | null | 2009-08-16 14:33:20.74 UTC | 89 | 2022-08-08 22:13:13.59 UTC | 2022-08-08 22:13:13.59 UTC | null | 1,159,167 | null | 86,684 | null | 1 | 352 | scala | 254,689 | <pre><code>val lines = scala.io.Source.fromFile("file.txt").mkString
</code></pre>
<p>By the way, "<code>scala.</code>" isn't really necessary, as it's always in scope anyway, and you can, of course, import io's contents, fully or partially, and avoid having to prepend "io." too.</p>
<p>The above leaves the file open, however. To avoid problems, you should close it like this:</p>
<pre><code>val source = scala.io.Source.fromFile("file.txt")
val lines = try source.mkString finally source.close()
</code></pre>
<p>Another problem with the code above is that it is horribly slow due to its implementation. For larger files one should use:</p>
<pre><code>source.getLines mkString "\n"
</code></pre> |
79,126 | Create Generic method constraining T to an Enum | <p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p> | 8,086,788 | 22 | 18 | null | 2008-09-17 01:56:19.267 UTC | 248 | 2021-10-14 15:44:51.907 UTC | 2021-04-13 00:37:05.473 UTC | null | 5,302 | lagerdalek | 5,302 | null | 1 | 1,373 | c#|generics|enums|generic-constraints | 451,206 | <h2>This feature is finally supported in C# 7.3!</h2>
<p>The following snippet (from <a href="https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190" rel="noreferrer">the dotnet samples</a>) demonstrates how:</p>
<pre><code>public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
</code></pre>
<p>Be sure to set your language version in your C# project to version 7.3.</p>
<hr />
<p>Original Answer below:</p>
<p>I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but <em>is possible</em> in MSIL. I wrote this little....thing</p>
<pre><code>// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
</code></pre>
<p>Which generates a function that <strong>would</strong> look like this, if it were valid C#:</p>
<pre><code>T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
</code></pre>
<p>Then with the following C# code:</p>
<pre><code>using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
</code></pre>
<p>Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by <code>System.Enum</code>. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.</p>
<p>By removing the line <code>.assembly MyThing{}</code> and invoking ilasm as follows:</p>
<pre><code>ilasm.exe /DLL /OUTPUT=MyThing.netmodule
</code></pre>
<p>you get a netmodule instead of an assembly.</p>
<p>Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the <code>/addmodule:{files}</code> command line argument. It wouldn't be <em>too</em> painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.</p>
<p>So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.</p>
<hr />
<h3>F# Solution as alternative</h3>
<p>Extra Credit: It turns out that a generic restriction on <code>enum</code> is possible in at least one other .NET language besides MSIL: F#.</p>
<pre class="lang-ml prettyprint-override"><code>type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
</code></pre>
<p>This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code <em>is</em> very different) and it relies on the <code>FSharp.Core</code> library, which, just like any other external library, needs to become part of your distribution.</p>
<p>Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:</p>
<pre><code>// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
</code></pre> |
133,031 | How to check if a column exists in a SQL Server table | <p>I need to add a specific column if it does not exist. I have something like the following, but it always returns false:</p>
<pre><code>IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
</code></pre>
<p>How can I check if a column exists in a table of the SQL Server database?</p> | 133,057 | 31 | 5 | null | 2008-09-25 12:34:00.093 UTC | 370 | 2022-04-23 05:25:26.877 UTC | 2022-04-20 20:10:34.513 UTC | Maciej | 63,550 | Maciej | 2,631,856 | null | 1 | 2,083 | sql-server|sql-server-2008|tsql|sql-server-2012|sql-server-2016 | 1,486,565 | <p>SQL Server 2005 onwards:</p>
<pre><code>IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
</code></pre>
<p>Martin Smith's version is shorter:</p>
<pre><code>IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
</code></pre> |
6,957,443 | How to display div after click the button in Javascript? | <p>I have following DIV . I want to display the DIV after button click .Now it is display none </p>
<pre><code><div style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" >
</code></pre> | 6,957,506 | 4 | 2 | null | 2011-08-05 13:55:48.05 UTC | 19 | 2020-01-31 06:45:47.193 UTC | 2017-05-23 12:18:14.06 UTC | null | -1 | null | 829,504 | null | 1 | 41 | javascript|html | 576,323 | <p>HTML Code:</p>
<pre><code><div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
</code></pre>
<p>Javascript: </p>
<pre><code>function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
</code></pre>
<p>See the Demo: <a href="http://jsfiddle.net/rathoreahsan/vzmnJ/" rel="noreferrer">http://jsfiddle.net/rathoreahsan/vzmnJ/</a></p> |
6,824,862 | Data Type Recognition/Guessing of CSV data in python | <p>My problem is in the context of processing data from large CSV files. </p>
<p>I'm looking for the most efficient way to determine (that is, guess) the data type of a column based on the values found in that column. I'm potentially dealing with very messy data. Therefore, the algorithm should be error-tolerant to some extent. </p>
<p>Here's an example:</p>
<pre><code>arr1 = ['0.83', '-0.26', '-', '0.23', '11.23'] # ==> recognize as float
arr2 = ['1', '11', '-1345.67', '0', '22'] # ==> regognize as int
arr3 = ['2/7/1985', 'Jul 03 1985, 00:00:00', '', '4/3/2011'] # ==> recognize as date
arr4 = ['Dog', 'Cat', '0.13', 'Mouse'] # ==> recognize as str
</code></pre>
<p>Bottom line: I'm looking for a python package or an algorithm that can detect either</p>
<ul>
<li>the schema of a CSV file, or even better</li>
<li>the data type of an individual column
as an array</li>
</ul>
<p><a href="https://stackoverflow.com/questions/3098337/method-for-guessing-type-of-data-represented-currently-represented-as-strings-in">Method for guessing type of data represented currently represented as strings</a> goes in a similar direction.
I'm worried about performance, though, since I'm possibly dealing with many large spreadsheets (where the data stems from)</p> | 18,036,886 | 5 | 0 | null | 2011-07-26 03:17:37.447 UTC | 10 | 2020-07-20 13:19:58.753 UTC | 2017-05-23 12:32:29.317 UTC | null | -1 | null | 25,842 | null | 1 | 23 | python|algorithm|csv|schema|heuristics | 14,118 | <p>You may be interested in this python library which does exactly this kind of type guessing on CSVs and XLS files for you:</p>
<ul>
<li><a href="https://github.com/okfn/messytables">https://github.com/okfn/messytables</a></li>
<li><a href="https://messytables.readthedocs.org/">https://messytables.readthedocs.org/</a> - docs</li>
</ul>
<p>It happily scales to very large files, to streaming data off the internet etc.</p>
<p>There is also an even simpler wrapper library that includes a command line tool named dataconverters: <a href="http://okfnlabs.org/dataconverters/">http://okfnlabs.org/dataconverters/</a> (and an online service: <a href="https://github.com/okfn/dataproxy">https://github.com/okfn/dataproxy</a>!)</p>
<p>The core algorithm that does the type guessing is here: <a href="https://github.com/okfn/messytables/blob/7e4f12abef257a4d70a8020e0d024df6fbb02976/messytables/types.py#L164">https://github.com/okfn/messytables/blob/7e4f12abef257a4d70a8020e0d024df6fbb02976/messytables/types.py#L164</a></p> |
6,383,914 | Is there a way to instantiate a class without calling __init__? | <p>Is there a way to circumvent the constructor <code>__init__</code> of a class in python?</p>
<p>Example:</p>
<pre><code>class A(object):
def __init__(self):
print "FAILURE"
def Print(self):
print "YEHAA"
</code></pre>
<p>Now I would like to create an instance of <code>A</code>. It could look like this, however this syntax is not correct.</p>
<pre><code>a = A
a.Print()
</code></pre>
<p>EDIT:</p>
<p>An even more complex example:</p>
<p>Suppose I have an object <code>C</code>, which purpose it is to store one single parameter and do some computations with it. The parameter, however, is not passed as such but it is embedded in a huge parameter file. It could look something like this:</p>
<pre><code>class C(object):
def __init__(self, ParameterFile):
self._Parameter = self._ExtractParamterFile(ParameterFile)
def _ExtractParamterFile(self, ParameterFile):
#does some complex magic to extract the right parameter
return the_extracted_parameter
</code></pre>
<p>Now I would like to dump and load an instance of that object <code>C</code>. However, when I load this object, I only have the single variable <code>self._Parameter</code> and I cannot call the constructor, because it is expecting the parameter file. </p>
<pre><code> @staticmethod
def Load(file):
f = open(file, "rb")
oldObject = pickle.load(f)
f.close()
#somehow create newObject without calling __init__
newObject._Parameter = oldObject._Parameter
return newObject
</code></pre>
<p>In other words, it is not possible to create an instance without passing the parameter file. In my "real" case, however, it is not a parameter file but some huge junk of data I certainly not want to carry around in memory or even store it to disc.</p>
<p>And since I want to return an instance of <code>C</code> from the method <code>Load</code> I do somehow have to call the constructor.</p>
<p>OLD EDIT:</p>
<p>A more complex example, which explains <strong>why</strong> I am asking the question:</p>
<pre><code>class B(object):
def __init__(self, name, data):
self._Name = name
#do something with data, but do NOT save data in a variable
@staticmethod
def Load(self, file, newName):
f = open(file, "rb")
s = pickle.load(f)
f.close()
newS = B(???)
newS._Name = newName
return newS
</code></pre>
<p>As you can see, since <code>data</code> is not stored in a class variable I cannot pass it to <code>__init__</code>. Of course I could simply store it, but what if the data is a huge object, which I do not want to carry around in memory all the time or even save it to disc?</p> | 6,384,982 | 6 | 12 | null | 2011-06-17 09:37:22.84 UTC | 21 | 2018-12-22 11:26:54.527 UTC | 2017-10-06 19:55:03.167 UTC | null | 3,885,376 | null | 572,616 | null | 1 | 79 | python|class|constructor|instantiation | 56,403 | <p>You <em>can</em> circumvent <code>__init__</code> by calling <code>__new__</code> directly. Then you can create a object of the given type and call an alternative method for <code>__init__</code>. This is something that <code>pickle</code> would do. </p>
<p>However, first I'd like to stress very much that it is something that you <strong><em>shouldn't</em></strong> do and whatever you're trying to achieve, there are better ways to do it, some of which have been mentioned in the other answers. In particular, it's a <em>bad</em> idea to skip calling <code>__init__</code>. </p>
<p>When objects are created, more or less this happens:</p>
<pre><code>a = A.__new__(A, *args, **kwargs)
a.__init__(*args, **kwargs)
</code></pre>
<p>You could skip the second step.</p>
<p><strong>Here's why you <em>shouldn't</em> do this:</strong> The purpose of <code>__init__</code> is to initialize the object, fill in all the fields and ensure that the <code>__init__</code> methods of the parent classes are also called. With <code>pickle</code> it is an exception because it tries to store all the data associated with the object (including <em>any</em> fields/instance variables that are set for the object), and so anything that was set by <code>__init__</code> the previous time would be restored by pickle, there's no need to call it again. </p>
<p>If you skip <code>__init__</code> and use an alternative initializer, you'd have a sort of a code duplication - there would be two places where the instance variables are filled in, and it's easy to miss one of them in one of the initializers or accidentally make the two fill the fields act differently. This gives the possibility of subtle bugs that aren't that trivial to trace (you'd have to <em>know</em> which initializer was called), and the code will be more difficult to maintain. Not to mention that you'd be in an even bigger mess if you're using inheritance - the problems will go up the inheritance chain, because you'd have to use this alternative initializer everywhere up the chain.</p>
<p>Also by doing so you'd be more or less overriding Python's instance creation and making your own. Python already does that for you pretty well, no need to go reinventing it and it will confuse people using your code.</p>
<p><strong>Here's what to best do instead:</strong> Use a single <code>__init__</code> method that is to be called for all possible instantiations of the class that initializes all instance variables properly. For different modes of initialization use either of the two approaches:</p>
<ol>
<li>Support different signatures for <code>__init__</code> that handle your cases by using optional arguments.</li>
<li>Create several class methods that serve as alternative constructors. Make sure they all create instances of the class in the normal way (i.e. calling <code>__init__</code>), <a href="https://stackoverflow.com/a/6384228">as shown by Roman Bodnarchuk</a>, while performing additional work or whatever. It's best if they pass all the data to the class (and <code>__init__</code> handles it), but if that's impossible or inconvenient, you can set some instance variables after the instance was created and <code>__init__</code> is done initializing.</li>
</ol>
<p>If <code>__init__</code> has an optional step (e.g. like processing that <code>data</code> argument, although you'd have to be more specific), you can either make it an optional argument or make a normal method that does the processing... or both.</p> |
6,901,363 | Detecting the iPhone's Ring / Silent / Mute switch using AVAudioPlayer not working? | <p>I've tried using these methods in an attempt to detect that the Ring/Silent switch is active or not:</p>
<p><a href="https://stackoverflow.com/questions/287543/how-to-programatically-sense-the-iphone-mute-switch">How to programmatically sense the iPhone mute switch?</a></p>
<p><a href="https://stackoverflow.com/questions/5560555/avaudiosession-category-not-working-as-documentation-dictates">AVAudioSession category not working as documentation dictates</a></p>
<p>But on my iPhone 4, the "state" value is always "Speaker" (and the length value returned by CFStringGetLength(state) is always 7). Has anyone used this method successfully? If so, on what kind of device and SDK version?</p>
<p>I'm calling it like so:</p>
<pre><code>
- (BOOL)deviceIsSilenced {
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus audioStatus = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if (audioStatus == kAudioSessionNoError) {
NSLog(@"audio route: %@", state) // "Speaker" regardless of silent switch setting, but "Headphone" when my headphones are plugged in
return (CFStringGetLength(state) <= 0);
}
return NO;
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
audioSession.delegate = self;
[audioSession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioSession setActive:YES error:nil];
NSLog(@"muted? %i", [self deviceIsSilenced]);
...
}
</code></pre>
<p>I was thinking maybe some other (more accurate) kAudioSessionProperty event is fired when the physical switch on the phone is ... switched. Anyone have any ideas?</p>
<p>By the way, I'm using the AVAudioSessionCategoryAmbient category with my [AVAudioSession sharedInstance].</p>
<p><strong>Update:</strong> I've also tried using different audio categories, and a handful of other audio session properties, none seem to fire when muting/unmuting the switch. :(</p>
<p><strong>Jan. 1, 2014 Update:</strong> It's a bit of a hack, and I encountered a crash while multitasking w/ it on my iPhone 5S, but the <a href="http://sharkfood.com/content/Developers/content/Sound%20Switch/" rel="nofollow noreferrer">SoundSwitch</a> library linked in the new accepted answer is the way to go if you want to detect the silent switch. It even works in iOS 7.</p> | 16,884,290 | 7 | 5 | null | 2011-08-01 16:18:18.99 UTC | 28 | 2017-08-12 08:12:08.177 UTC | 2017-05-23 12:34:01.78 UTC | null | -1 | null | 100,027 | null | 1 | 33 | iphone|ios4|iphone-sdk-3.0|avaudioplayer|avaudiosession | 33,099 | <p>I went through this VSSilentSwitch library.<br/>
Didn't work for me (doesn't work when you start actually using audio).<br/>
I was thinking on how he did it, and then realised that the audio completion call is being called almost as soon as the sound begins playing when we're silent.<br/>
To be a bit more specific:<br/>
System sounds being played using <code>AudioServicesPlaySystemSound</code> will complete playback as soon as it started.<br/>
Of course, this will only work on audio categories that respect the silent switch (the default <code>AVAudioSessionCategoryAmbient</code> respects it).<br/>
So the trick is to create a system sound, preferably of a silent sound, and keep playing it over and over again, while checking the time it took from playback to completion (install a completion procedure using <code>AudioServicesAddSystemSoundCompletion</code>).<br/>
If the completion proc is called very soon (allow <em>some</em> threshold) - it means the silent switch is on.<br/>
This trick has many caveats, the biggest one being the fact that it won't work on all audio categories.<br/>
If your app plays audio in the background - make sure you stop this test while in the background or your app will run forever in the background (and will be rejected by apple, too).</p> |
6,594,388 | Why we should use Join in threads? | <p>I have 2 threads T1 and T2 ,both have different jobs so usually we prefer to accomplish this task by thread Joins. </p>
<p>But we can do this with out using join(). We can add T2 thread's code inside T1 thread.
What difference does this make ?</p> | 6,594,400 | 10 | 1 | null | 2011-07-06 09:43:11.217 UTC | 12 | 2022-05-03 16:00:49.83 UTC | 2011-07-06 10:17:38.853 UTC | null | 830,964 | null | 632,533 | null | 1 | 23 | java|multithreading | 51,954 | <p>The main difference is when we join T2 thread with T1 ,the time T2 is executing the job can be utilised by T1 also ,that means they will do different job parllely.But this cann't happen when you include the T2 thread code inside T1 thread.</p> |
6,994,393 | Singleton: How to stop create instance via Reflection | <p>I know in Java we can create an instance of a Class by <code>new</code>, <code>clone()</code>, <code>Reflection</code> and by <code>serializing and de-serializing</code>.</p>
<p>I have create a simple class implementing a Singleton.</p>
<p>And I need stop all the way one can create instance of my Class.</p>
<pre><code>public class Singleton implements Serializable{
private static final long serialVersionUID = 3119105548371608200L;
private static final Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton getInstance(){
return singleton;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning of this class is not allowed");
}
protected Object readResolve() {
return singleton;
}
//-----> This is my implementation to stop it but Its not working. :(
public Object newInstance() throws InstantiationException {
throw new InstantiationError( "Creating of this object is not allowed." );
}
}
</code></pre>
<p>In this Class I have managed to stop the class instance by <code>new</code>, <code>clone()</code> and <code>serialization</code>, But am unable to stop it by Reflection.</p>
<p>My Code for creating the object is</p>
<pre><code>try {
Class<Singleton> singletonClass = (Class<Singleton>) Class.forName("test.singleton.Singleton");
Singleton singletonReflection = singletonClass.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
</code></pre> | 6,994,438 | 13 | 3 | null | 2011-08-09 09:58:17.603 UTC | 24 | 2020-12-23 11:39:12.423 UTC | null | null | null | null | 358,163 | null | 1 | 44 | java|reflection|singleton | 53,339 | <p>By adding below check inside your private constructor</p>
<pre><code>private Singleton() {
if( singleton != null ) {
throw new InstantiationError( "Creating of this object is not allowed." );
}
}
</code></pre> |
45,504,241 | Create single row python pandas dataframe | <p>I want to create a python pandas DataFrame with a single row, to use further pandas functionality like dumping to *.csv.</p>
<p>I have seen code like the following being used, but I only end up with the column structure, but empty data</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
df['A'] = 1
df['B'] = 1.23
df['C'] = "Hello"
df.columns = [['A','B','C']]
print df
Empty DataFrame
Columns: [A, B, C]
Index: []
</code></pre>
<p>While I know there are other ways to do it (like from a dictionary), I want to understand why this piece of code is not working for me!? Is this a version issue? (using pandas==0.19.2)</p> | 45,504,298 | 3 | 5 | null | 2017-08-04 10:19:17.743 UTC | 5 | 2022-07-31 17:23:46.43 UTC | null | null | null | null | 6,777,817 | null | 1 | 46 | python|pandas|dataframe | 104,007 | <pre><code>In [399]: df = pd.DataFrame(columns=list('ABC'))
In [400]: df.loc[0] = [1,1.23,'Hello']
In [401]: df
Out[401]:
A B C
0 1 1.23 Hello
</code></pre>
<p>or:</p>
<pre><code>In [395]: df = pd.DataFrame([[1,1.23,'Hello']], columns=list('ABC'))
In [396]: df
Out[396]:
A B C
0 1 1.23 Hello
</code></pre> |
45,631,081 | ERROR: localhost redirected you too many times | <p>Hi I'm a new student and starting to learn coding/programming specially on PHP. I tried learning some code and I have encountered this problem.</p>
<p><strong>This page isnβt working</strong></p>
<p><em>localhost redirected you too many times.</em>
Try clearing your cookies.
<strong>ERR_TOO_MANY_REDIRECTS</strong></p>
<p>and this is my code:</p>
<pre><code>session_start();
include('_includes/config.php');
include('_includes/db.php');
if(isset($_POST['register'])){
$_SESSION['uname'] = $_POST['uname'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['postal'] = $_POST['postal'];
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['con-pass'] = $_POST['con-pass'];
}
if(strlen($_POST['uname'])<3){
header("Location:register.php?err=" . urlencode("The username must be at least 3 characters long"));
die();
}
</code></pre>
<p>I really don't know what to do I have encountered some errors in php but I haven't encountered this kind of error PLEASE HELP and PLEASE ENLIGHTEN me on what I have done wrong.</p> | 45,631,270 | 1 | 6 | null | 2017-08-11 09:01:31.99 UTC | 1 | 2019-11-12 21:30:53.56 UTC | null | null | null | null | 8,449,860 | null | 1 | 3 | php | 68,698 | <p>Check if user request to register too than redirect, update code like below :</p>
<pre><code>session_start();
include('_includes/config.php');
include('_includes/db.php');
if(isset($_POST['register'])){
$_SESSION['uname'] = $_POST['uname'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['postal'] = $_POST['postal'];
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['con-pass'] = $_POST['con-pass'];
}
if(strlen($_POST['uname'])<3 && isset($_POST['register'])){ // add && isset($_POST['register'])
header("Location:register.php?err=" . urlencode("The username must be at least 3 characters long"));
die();
}
</code></pre>
<p><strong>Note:</strong> at all i'm suggest you don't redirect user to show error message if codes in some file! you can store error message in vars and check if error var is not empty echo it!</p>
<pre><code>session_start();
include('_includes/config.php');
include('_includes/db.php');
$error = ''; //add this var
if(isset($_POST['register'])){
$_SESSION['uname'] = $_POST['uname'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['postal'] = $_POST['postal'];
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['con-pass'] = $_POST['con-pass'];
}
if(strlen($_POST['uname'])<3 && isset($_POST['register'])){ // add && isset($_POST['register'])
/*header("Location:register.php?err=" . urlencode("The username must be at least 3 characters long"));
die();*/
$error = 'this is error message';
}
//add below code anywhere you want show error
if($error){
echo $error;
}
</code></pre> |
15,659,559 | Angularjs. How can I pass variable as argument to custom filter? | <p>I have following HTML</p>
<pre><code><span class="items-count">{{items | countmessage}}</span>
</code></pre>
<p>And following filter to show right count message</p>
<pre><code> app.filters
.filter('countmessage', function () {
return function (input) {
var result = input.length + ' item';
if (input.length != 1) result += 's';
return message;
}
});
</code></pre>
<p>but I want use different words instead 'item(s)', so I modified the filter</p>
<pre><code> app.filters
.filter('countmessage', function () {
return function (input, itemType) {
var result = input.length + ' ' + itemType;
if (input.length != 1) result += 's';
return message;
}
});
</code></pre>
<p>it works when I use a string like that</p>
<pre><code><span class="items-count">{{items | countmessage:'car'}}</span>
</code></pre>
<p>but doesn't work with a variable from the $scope, is it possible to use $scope variable</p>
<pre><code><span class="items-count">{{items | countmessage:itemtype}}</span>
</code></pre>
<p>Thanks</p> | 15,660,979 | 1 | 0 | null | 2013-03-27 13:06:08.787 UTC | 3 | 2018-02-05 11:18:55.073 UTC | 2013-03-27 14:15:03.96 UTC | null | 730,845 | null | 730,845 | null | 1 | 31 | javascript|angularjs | 41,512 | <p>Yes, it is possible to use variable from the <code>$scope</code></p>
<p>See this fiddle for an example:
<a href="http://jsfiddle.net/lopisan/Kx4Tq/" rel="noreferrer">http://jsfiddle.net/lopisan/Kx4Tq/</a></p>
<p>HTML:</p>
<pre><code><body ng-app="myApp">
<div ng-controller="MyCtrl">
<input ng-model="variable"/><br/>
Live output: {{variable | countmessage : type}}!<br/>
Output: {{1 | countmessage : type}}!
</div>
</body>
</code></pre>
<p>JavaScript:</p>
<pre><code>var myApp = angular.module('myApp',['myApp.filters']);
function MyCtrl($scope) {
$scope.type = 'cat';
}
angular.module('myApp.filters', [])
.filter('countmessage', function () {
return function (input, itemType) {
var result = input + ' ' + itemType;
if (input > 1) result += 's';
return result;
}
});
</code></pre> |
10,693,231 | Elegant TryParse | <p>I feel that every time I use <code>TryParse</code> that it results in somewhat ugly code. Mainly I am using it this way:</p>
<pre><code>int value;
if (!int.TryParse(someStringValue, out value))
{
value = 0;
}
</code></pre>
<p>Is there some more elegant solution for parsing all basic data types, to be specific is there a way to do fail safe parsing in one line? By fail safe I assume setting default value if parsing fails without exception.</p>
<p>By the way, this is for cases where I must do some action even if parsing fails, just using the default value.</p> | 18,979,800 | 8 | 3 | null | 2012-05-21 21:58:22.437 UTC | 14 | 2021-06-01 20:36:37.087 UTC | 2018-11-28 17:22:21.183 UTC | null | 1,185,053 | null | 351,383 | null | 1 | 82 | c# | 44,272 | <p>This is valid and you may prefer it if you have a liking for single-liners:</p>
<pre><code>int i = int.TryParse(s, out i) ? i : 42;
</code></pre>
<p>This sets the value of <code>i</code> to <code>42</code> if it cannot parse the string <code>s</code>, otherwise it sets <code>i = i</code>.</p> |
10,303,639 | adb command not found | <p>I need to run an <code>adb forward</code> command before I could use the <em>ezkeyboard</em> application which allows user to type on the phone using browser. </p>
<p>When I run <code>adb forward tcp:8080 tcp:8080</code> command I get the <code>adb command not found</code> error message.</p>
<p>I can run <code>android</code> command from terminal. Why <code>adb</code> is not working?</p> | 10,303,693 | 26 | 3 | null | 2012-04-24 18:13:35.933 UTC | 61 | 2022-04-14 19:46:07.07 UTC | 2018-07-27 01:18:39.823 UTC | null | 1,778,421 | null | 277,696 | null | 1 | 254 | android|macos|terminal|adb | 467,704 | <p>Make sure <code>adb</code> is in your user's <strong>$PATH</strong> variable.</p>
<p><strong>or</strong></p>
<p>You can try to locate it with <code>whereis</code> and run it with <code>./adb</code></p> |
10,656,841 | How to get GET parameters with ASP.NET MVC ApiController | <p>I feel a bit absurd asking this but I can't find a way to get parameters for a get request at
<code>/api/foo?sort=name</code> for instance.</p>
<p>In the <code>ApiController</code> class, I gave a <code>public string Get()</code>. Putting <code>Get(string sort)</code> makes <code>/api/foo</code> a bad request. Request instance in the <code>ApiController</code> is of type <code>System.Net.Http.HttpRequestMessage</code>. It doesn't have a <code>QueryString</code> or <code>Parameters</code> property or anything. </p> | 13,312,061 | 8 | 6 | null | 2012-05-18 17:03:28.543 UTC | 1 | 2020-04-08 21:52:52.897 UTC | 2012-05-20 06:39:32.853 UTC | null | 646,382 | null | 167,638 | null | 1 | 30 | asp.net-mvc|api|asp.net-mvc-4|asp.net-web-api | 45,068 | <p>You could just use</p>
<pre><code>HttpContext.Current.Request.QueryString
</code></pre> |
33,378,000 | Passing FILE pointer to a function | <p>I'm little bit confused over here, not quite sure about this. What I'm trying to do is to pass the name of a file through <code>terminal</code>/<code>cmd</code> that will be opened and read from.</p>
<pre><code>myfunction(char* fileName, FILE* readFile)
{
if((readFile = fopen(fileName,"r")) == NULL)
{
return FILE_ERROR;
}
return FILE_NO_ERROR;
}
int main(int argc, char **argv)
{
FILE* openReadFile;
if(myfunction(argv[1], openReadFile) != FILE_NO_ERROR)
{
printf("\n %s : ERROR opening file. \n", __FUNCTION__);
}
}
</code></pre>
<p>My question is if i pass a pointer <code>openReadFile</code> to <code>myfunction()</code> will a <code>readFile</code> pointer to opened file be saved into <code>openReadFile</code> pointer or do i need to put <code>*readFile</code> when opening.</p> | 33,378,074 | 1 | 6 | null | 2015-10-27 20:36:34.41 UTC | 6 | 2015-10-27 22:38:41.553 UTC | 2015-10-27 22:38:41.553 UTC | null | 4,413,307 | null | 4,676,162 | null | 1 | 3 | c|pointers | 41,596 | <p>FILE * needs to be a pointer, so in main openReadFile stays as a pointer.
myfunction takes **, so we can update the FILE * with the result from fopen
<code>*readFile = fopen...</code> updates the pointer.</p>
<pre><code>int myfunction(char* fileName, FILE** readFile) /* pointer pointer to allow pointer to be changed */
{
if(( *readFile = fopen(fileName,"r")) == NULL)
{
return FILE_ERROR;
}
return FILE_NO_ERROR;
}
int main(int argc, char **argv)
{
FILE* openReadFile; /* This needs to be a pointer. */
if(myfunction(argv[1], &openReadFile) != FILE_NO_ERROR) /* allow address to be updated */
{
printf("\n %s : ERROR opening file. \n", __FUNCTION__);
}
}
</code></pre> |
40,089,316 | How to share service between two modules - @NgModule in angular not between to components? | <p>In my application, I have two different bootstrap module (<code>@NgModule</code>) running independently in one application. There are not one angular app bit separate bootstrap module and now I want they should communicate to each other and share data.</p>
<p>I know through <code>@Injectable</code> service as the provider in the module, I can share data in all component under <code>@NgModule</code> but how I will share data between two different module ( not component inside module ).</p>
<p>Is there a way one service object can be accessed in another module? Is there a way I can access the object of Service available in browser memory and use it in my other angular module?</p> | 40,089,759 | 7 | 8 | null | 2016-10-17 14:40:39.773 UTC | 20 | 2021-02-03 13:18:30.96 UTC | 2017-09-28 20:28:34.787 UTC | null | 537,647 | null | 537,647 | null | 1 | 47 | angular|angular2-services|angular2-modules | 56,722 | <p><strong>2021-02-03</strong></p>
<p>In recent Angular versions this is solved using <code>@Injectable({providedIn: 'platform'})</code></p>
<p><a href="https://angular.io/api/core/Injectable" rel="nofollow noreferrer">https://angular.io/api/core/Injectable</a></p>
<p><strong>Original</strong></p>
<p>You can instantiate a service outside Angular and provide a value:</p>
<pre class="lang-ts prettyprint-override"><code>class SharedService {
...
}
</code></pre>
<pre class="lang-ts prettyprint-override"><code>window.sharedService = new SharedService();
@NgModule({
providers: [{provide: SharedService, useValue: window.sharedService}],
...
})
class AppModule1 {}
@NgModule({
providers: [{provide: SharedService, useValue: window.sharedService}],
...
})
class AppModule2 {}
</code></pre>
<p>If one application change the state in <code>SharedService</code> or calls a method that causes an <code>Observable</code> to emit a value and the subscriber is in a different application than the emitter, the code in the subscriber is executed in the <code>NgZone</code> of the emitter.</p>
<p>Therefore when subscribing to an observable in <code>SharedService</code> use</p>
<pre class="lang-ts prettyprint-override"><code>class MyComponent {
constructor(private zone:NgZone, private sharedService:SharedService) {
sharedService.someObservable.subscribe(data => this.zone.run(() => {
// event handler code here
}));
}
}
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/36566698/cant-initialize-dynamically-appended-html-component-in-angular-2">How to dynamically create bootstrap modals as Angular2 components?</a></p> |
22,942,115 | Checking to see if array is full | <p>If I have an Array <code>Candy[] type;</code></p>
<p>and <code>type = new Candy[capacity];</code></p>
<p>if the Array is full is <code>capacity = type.length</code> ?</p> | 22,942,233 | 4 | 3 | null | 2014-04-08 15:54:31.017 UTC | 1 | 2020-02-27 20:55:29.23 UTC | null | null | null | null | 2,896,914 | null | 1 | 6 | java|arrays | 63,355 | <p>Since you are using array, the size of array is determined during compilation. Thus if your intention is to check whether current array's index has reached the last array element, you may use the following condtion (possibly in a loop) to check whether your current array index is the last element. If it is true, then it has reached the last element of your array.</p>
<p><strong>Example:</strong></p>
<pre class="lang-java prettyprint-override"><code> int[] candy = new int[10]; //Array size is 10
//first array: Index 0, last array index: 9.
for (int x=0; x < candy.length; x++)
if (x == candy.length - 1)
//Reached last element of array
</code></pre>
<p>You can check the <strong>size</strong> of the array by using:</p>
<pre><code>candy.length
</code></pre>
<p>You check whether it is <strong>last element</strong> by using:</p>
<pre><code>if (currentIndex == candy.length - 1) //Where candy is your array
</code></pre>
<p>Make sure you are using <strong>double equal</strong> <code>==</code> for comparison. </p>
<p>Single equal <code>=</code> is for assignment.</p> |
13,482,351 | Sharing data between directives | <p>I have some data called <code>foo</code> which lives in a scope which is parent to three children:</p>
<pre><code><div ng-init="foo=[1, 2, 3]">
<bar foo="{{foo}}" baz="{{odp}}" />
<mpq foo="{{foo}}" bats="{{maktz}}" />
<ktr foo="{{foo}}" otr="{{ompg}}" />
</div>
bar.scope = {foo: '=', baz: '@'};
mpq.scope = {foo: '=', bats: '@'};
ktr.scope = {foo: '=', otr: '@'};
</code></pre>
<p>What is the best way to share <code>foo</code> between those three directives? Options include:</p>
<ul>
<li>Use an isolated scope to pass in <code>foo</code> three times, thereby duplicating it across four scopes</li>
<li>Have the child directives inherit the parent scope, and find <code>baz</code>, <code>bats</code>, or <code>otr</code> on <code>attrs</code></li>
<li>Put <code>foo</code> on the <code>$rootScope</code> and inject that into the child directives</li>
</ul>
<p>Or is there another approach that is better?</p> | 13,482,919 | 1 | 1 | null | 2012-11-20 21:20:50.613 UTC | 11 | 2017-01-24 14:02:13.943 UTC | null | null | null | null | 147,601 | null | 1 | 21 | angularjs | 31,283 | <p>You can create a factory that you can pass to each directive or controller. That will make sure you only have one instance of the array at any given time. EDIT: The only gotcha here is to make sure you're setting reference types and not primitive types on your directive scopes, or you'll end up duplicating the values in each scope.</p>
<p><a href="http://plnkr.co/edit/ZZOjr2" rel="nofollow noreferrer">Here is an example on Plnkr.co</a></p>
<pre><code>app.controller('MainCtrl', function($scope, dataService) {
$scope.name = 'World';
//set up the items.
angular.copy([ { name: 'test'} , { name: 'foo' } ], dataService.items);
});
app.directive('dir1', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 1</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.directive('dir2', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 2</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.directive('dir3', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 3</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.factory('dataService', [function(){
return { items: [] };
}]);
</code></pre>
<p>HTML</p>
<pre><code> <dir1></dir1>
<dir2></dir2>
<dir3></dir3>
</code></pre> |
13,396,856 | Markdown output for Sphinx based documentation | <p>I found myself with a use case, where in addition to generating HTML and PDF from my <a href="http://sphinx-doc.org"><em>Sphinx</em></a> based documentation sources, I would also like to generate a <a href="http://en.wikipedia.org/wiki/Markdown"><em>Markdown</em></a> version of the <a href="http://en.wikipedia.org/wiki/ReStructuredText"><em>reStructuredText</em></a> source files.</p>
<p>My preliminary research didn't find any core or extension support for this in <em>Sphinx</em>. Other than manually using <a href="http://johnmacfarlane.net/pandoc/"><em>pandoc</em></a> or creating a new <em>Sphinx</em> extension for the task, is there be a simpler/more integrated solution for this?</p> | 13,478,104 | 3 | 3 | null | 2012-11-15 11:43:41.903 UTC | 12 | 2020-10-06 02:12:30.94 UTC | 2020-10-06 02:12:30.94 UTC | null | 10,794,031 | null | 1,642,530 | null | 1 | 35 | markdown|python-sphinx|restructuredtext | 14,544 | <p>I didn't find anything which could take reStructuredText files and convert them to Markdown except for Pandoc, so I wrote a custom writer for <a href="http://docutils.sourceforge.net/">Docutils</a> (the reference implementation of reStructuredText and what Sphinx is built upon). The code is <a href="https://github.com/cgwrench/rst2md">available on GitHub</a>. </p>
<p>Note that it is only an initial implementation: it handles any reStructuredText document without error (tested against the <em>standard.txt</em> test document from the Docutils source repository) but many of the reStructuredText constructs (e.g. substitutions, raw directives etc.) are not supported and so not included in the Markdown output. I hope to add support for links, code blocks, images and tables: any help towards this is more than welcome - just go ahead and fork the code.</p>
<p>It seems that to add another writer/output format to Sphinx you need to <a href="http://sphinx-doc.org/builders.html#builders">add a "builder"</a> using an <a href="http://sphinx-doc.org/extensions.html#extensions">extension</a>.</p> |
13,586,865 | How to get ZPL code from a ZebraDesigner label? | <p>I'm using ZebraDesigner 2.2.2 (Build 2728).</p>
<p>Is there a way to extract the ZPL code from ZebraDesigner? I can't even export it to ZPL file, the only option I have is saving it as <code>.lbl</code>.</p>
<p><img src="https://i.stack.imgur.com/4WYdd.png" alt="enter image description here"></p> | 13,588,736 | 4 | 1 | null | 2012-11-27 14:53:37.317 UTC | 17 | 2021-03-22 14:34:51.92 UTC | 2019-09-23 12:45:40.137 UTC | null | 505,893 | null | 1,410,185 | null | 1 | 38 | printing|barcode|zebra-printers|zpl | 97,454 | <p>You can add a new ZebraDesigner ZPL driver to the system and use a file as the port. Then when you "Print" the document, it will write the ZPL code to the file.</p>
<p>Note that it might have some header information before the first <code>^XA</code> which you might not need.</p>
<p><strong>UPDATE : (How to add local port on a driver)</strong></p>
<ol>
<li>Go to <code>Printer Properties</code></li>
<li>Click on the <code>Ports</code> tab</li>
<li>Click <code>Add Port</code></li>
<li>Select <code>Local Port</code> and click <code>New port</code></li>
<li>Enter a filename e.g. <code>C:\output.zpl</code></li>
<li>Make sure it is checked in the ports list</li>
<li>Now all printing output should go to <code>C:\output.zpl</code></li>
</ol> |
13,291,788 | LINQ to find array indexes of a value | <p>Assuming I have the following string array:</p>
<pre><code>string[] str = new string[] {"max", "min", "avg", "max", "avg", "min"}
</code></pre>
<p>Is it possbile to use LINQ to get a list of indexes that match one string?</p>
<p>As an example, I would like to search for the string "avg" and get a list containing </p>
<blockquote>
<p>2, 4</p>
</blockquote>
<p>meaning that "avg" can be found at str[2] and str[4].</p> | 13,291,838 | 6 | 0 | null | 2012-11-08 15:12:47.773 UTC | 11 | 2014-10-29 14:02:11.457 UTC | 2012-11-08 15:25:12.39 UTC | null | 1,159,478 | null | 716,092 | null | 1 | 68 | c#|linq | 71,308 | <p><code>.Select</code> has a seldom-used overload that produces an index. You can use it like this:</p>
<pre><code>str.Select((s, i) => new {i, s})
.Where(t => t.s == "avg")
.Select(t => t.i)
.ToList()
</code></pre>
<p>The result will be a list containing 2 and 4.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb534869.aspx" rel="noreferrer">Documentation here</a></p> |
13,781,685 | angularjs: ng-src equivalent for background-image:url(...) | <p>In angularjs you have the <a href="http://docs.angularjs.org/api/ng.directive:ngSrc" rel="noreferrer">tag ng-src</a> which has the purpose that you won't receive an error for an invalid url before angularjs gets to evaluate the variables placed in between <code>{{</code> and <code>}}</code>.</p>
<p>The problem is that I use quite some DIV's with a <code>background-image</code> set to an url. I do this because of the excellent CSS3 property <code>background-size</code> which crops the image to the exact size of the DIV.</p>
<p>The only problem is that I receive a lot of errors for the exact same reason they created a ng-src tag: I have some variables in the url and the browser thinks the image doesn't exist.</p>
<p>I realize that there is a possibility of writing a crude <code>{{"style='background-image:url(myVariableUrl)'"}}</code>, but this seems 'dirty'.</p>
<p>I've searched a lot and can't find the right way to do this. My app is becoming a mess because of all of these errors.</p> | 13,782,311 | 9 | 0 | null | 2012-12-08 20:36:50.347 UTC | 56 | 2017-03-13 04:59:20.587 UTC | 2012-12-08 21:14:05.61 UTC | null | 1,066,031 | null | 1,888,394 | null | 1 | 152 | css|angularjs | 127,424 | <p><code>ngSrc</code> is a native directive, so it seems you want a similar directive that modifies your div's <code>background-image</code> style. </p>
<p>You could write your own directive that does exactly what you want. For example</p>
<pre><code>app.directive('backImg', function(){
return function(scope, element, attrs){
var url = attrs.backImg;
element.css({
'background-image': 'url(' + url +')',
'background-size' : 'cover'
});
};
});β
</code></pre>
<p>Which you would invoke like this</p>
<pre><code><div back-img="<some-image-url>" ></div>
</code></pre>
<p>JSFiddle with cute cats as a bonus: <a href="http://jsfiddle.net/jaimem/aSjwk/1/" rel="noreferrer">http://jsfiddle.net/jaimem/aSjwk/1/</a></p> |
51,641,641 | Convert from HttpResponseMessage to IActionResult in .NET Core | <p>I'm porting over some code that was previously written in .NET Framework to .NET Core.</p>
<p>I had something like this:</p>
<pre><code>HttpResponseMessage result = await client.SendAync(request);
if (result.StatusCode != HttpStatusCode.OK)
{
IHttpActionResult response = ResponseMessage(result);
return response;
}
</code></pre>
<p>The return value of this function is now <code>IActionResult</code>.</p>
<p>How do I take the <code>HttpResponseMessage result</code> object and return an <code>IActionResult</code> from it?</p> | 51,642,328 | 5 | 6 | null | 2018-08-01 20:17:06.57 UTC | 5 | 2022-06-27 16:02:24.243 UTC | null | null | null | null | 1,487,135 | null | 1 | 23 | c#|.net|asp.net-core | 39,084 | <p>You can return using hardset status codes like <code>Ok();</code> or <code>BadRequest();</code></p>
<p>Or return using a dynamic one using</p>
<pre><code>StatusCode(<Your status code number>,<Optional return object>);
</code></pre>
<p>This is <code>using Microsoft.AspNetCore.Mvc</code> </p>
<p>Below is this.StatusCode spelled out a little more:</p>
<pre><code>/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
StatusCodeResult scr = this.StatusCode(200);
/* OR */
Object myObject = new Object();
ObjectResult ores = this.StatusCode(200, myObject);
return scr; /* or return ores;*/
</code></pre> |
39,484,539 | Angular 2: How to tell SystemJS to use a bundle? | <p>I have an Angular 2 RC7 app where I use SystemJS to load JavaScript files. </p>
<p>This is my current configuration for SystemJS:</p>
<pre><code>(function (global) {
System.config({
defaultExtension: 'js',
defaultJSExtensions: true,
paths: {
'npm:': 'node_modules/'
},
// Let the system loader know where to look for things
map: {
// Our app is within the app folder
app: 'app',
// Angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// Other libraries
'rxjs': 'npm:rxjs',
'ng2-translate': 'node_modules/ng2-translate'
},
// Tell the system loader how to load when no filename and/or no extension
packages: {
app: { main: './main.js', defaultExtension: 'js' },
rxjs: { defaultExtension: 'js' },
'ng2-translate': { defaultExtension: 'js' }
}
});
})(this);
</code></pre>
<p>Now I have created a bundle called <code>app.bundle.min.js</code> that contains all my app logic, and a <code>dependencies.bundle.min.js</code> that contains dependencies used. </p>
<p>How do I tell SystemJS to use these files instead of importing the files individually?</p>
<p>I have tried replacing this:</p>
<pre><code><script>
System.import('app').catch(function(err){
console.error(err);
});
</script>
</code></pre>
<p>with:</p>
<pre><code><script src="production/dependencies.bundle.min.js"></script>
<script src="production/app.bundle.min.js"></script>
</code></pre>
<p>in my index.html, but that's not working. As long as I keep the <code>System.import...</code> script block inside index.html, the app loads but using individual files instead of bundles.</p>
<p>I also tried changing this:</p>
<pre><code>map: {
// Our app is within the app folder
app: 'production/app.bundle.min.js',
</code></pre>
<p>but that did not work either.</p>
<p>This is how the bundles are generated using Gulp:</p>
<pre><code>gulp.task('inline-templates', function () {
return gulp.src('app/**/*.ts')
.pipe(inlineNg2Template({
UseRelativePaths: true,
indent: 0,
removeLineBreaks: true
}))
.pipe(tsc({
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true
}))
.pipe(gulp.dest('dist'));
});
gulp.task('bundle-app', ['inline-templates'], function() {
var builder = new systemjsBuilder('', 'app/configs/systemjs.config.js');
return builder
.bundle('dist/**/* - [@angular/**/*.js] - [rxjs/**/*.js]', 'production/app.bundle.min.js', {
minify: true,
mangle: true
})
.then(function() {
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
});
});
gulp.task('bundle-dependencies', ['inline-templates'], function() {
var builder = new systemjsBuilder('', 'app/configs/systemjs.config.js');
return builder
.bundle('dist/**/*.js - [dist/**/*.js]', 'production/dependencies.bundle.min.js', {
minify: true,
mangle: true
})
.then(function() {
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
});
});
gulp.task('production', ['bundle-app', 'bundle-dependencies'], function(){});
</code></pre>
<p>I suspect I have to somehow change mappings inside my SystemJS configuration to point towards the bundles? How do I do this?</p> | 39,522,819 | 1 | 2 | null | 2016-09-14 07:15:28.23 UTC | 12 | 2017-05-13 21:27:53.203 UTC | 2016-09-15 04:21:19.067 UTC | null | 6,470,333 | null | 6,470,333 | null | 1 | 14 | javascript|angular|bundle|systemjs | 9,470 | <p>According to the <code>map</code> and <code>packages</code> in your SystemJS config, </p>
<pre><code>System.import('app')
</code></pre>
<p>translates into the request for the file <code>app/main.js</code>. However, if you look into generated app bundle, you see that this module is actually registered as </p>
<pre><code>System.registerDynamic("dist/main.js" ...
</code></pre>
<p>because the bundle was generated from <code>.js</code> files in the <code>dist</code> folder.</p>
<p>This mismatch is the reason why your modules are not loaded from the script bundle.</p>
<p>One possible solution is to always keep <code>.ts</code> and <code>.js</code> files in separate folders - <code>.ts</code> in <code>app</code>, <code>.js</code> in <code>dist</code>. That way, systemjs will need to know only about <code>dist</code>: the only part of systemjs.config.js that needs to change is <code>app</code> mapping:</p>
<pre><code>// Let the system loader know where to look for things
map: {
// Our app is compiled to js files in the dist folder
app: 'dist',
</code></pre>
<p>To check that it works, I started from <a href="https://github.com/angular/quickstart" rel="noreferrer">angular quickstart example</a> and added <code>gulpfile.js</code> with these tasks:</p>
<ol>
<li><p>compile typescript into <code>dist</code> using <a href="https://www.npmjs.com/package/gulp-typescript" rel="noreferrer">gulp-typescript</a> plugin.</p>
<pre><code>var gulp = require('gulp');
var typescript = require('typescript');
var tsc = require('gulp-typescript');
var systemjsBuilder = require('systemjs-builder');
gulp.task('tsc', function () {
return gulp.src(['app/**/*.ts', 'typings/index.d.ts'])
.pipe(tsc({
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true
}))
.js.pipe(gulp.dest('dist'));
});
</code></pre></li>
<li><p>copy systemjs config file into <code>dist</code> folder, so that is will be bundled together with the app code and will be available in production (it's needed because you are using <code>bundle</code> and not <code>buildStatic</code>)</p>
<pre><code>gulp.task('bundle-config', function() {
return gulp.src('app/configs/systemjs.config.js')
.pipe(gulp.dest('dist/configs'));
});
</code></pre></li>
<li><p>generate bundles with systemjs builder:</p>
<pre><code>gulp.task('bundle-app', ['bundle-config', 'tsc'], function() {
var builder = new systemjsBuilder('', 'app/configs/systemjs.config.js');
return builder
.bundle('[dist/**/*]', 'production/app.bundle.min.js', {
minify: true,
mangle: true
})
.then(function() {
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
});
});
gulp.task('bundle-dependencies', ['bundle-config', 'tsc'], function() {
var builder = new systemjsBuilder('', 'app/configs/systemjs.config.js');
return builder
.bundle('dist/**/* - [dist/**/*.js]', 'production/dependencies.bundle.min.js', {
minify: true,
mangle: true
})
.then(function() {
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
});
});
gulp.task('production', ['bundle-app', 'bundle-dependencies'], function(){});
</code></pre></li>
</ol>
<p>Note that it uses <code>[dist/**/*]</code> syntax for generating app bundle without any dependencies - the one in your gulpfile.js is different and generates much bigger bundle which includes some dependencies - I don't know if it's intentional or not.</p>
<p>Then, I created <code>index-production.html</code> with these changes from <code>index.html</code>:</p>
<ol>
<li><p>remove <code><script></code> tag for <code>systemjs.config.js</code> - we import it from the bundle</p></li>
<li><p>add <code><script></code> tags for bundles in <code><head></code></p>
<pre><code><script src="production/dependencies.bundle.min.js"></script>
<script src="production/app.bundle.min.js"></script>
</code></pre></li>
<li><p>add inline <code><script></code> that imports config and app module:</p>
<pre><code><script>
System.import('dist/configs/systemjs.config.js').then(function() {
System.import('app').catch(function(err){ console.error(err); });
});
</script>
</code></pre></li>
</ol>
<p>importing 'app' module is necessary because bundles generated with <code>bundle</code> do not import anything and don't run any code - they are only making all the modules available for import later, unlike 'sfx' bundles generated with <code>buildStatic</code>.</p>
<p>Also, this script block needs to be in the <code><body></code> after <code><my-app></code> element, otherwise <code>app</code> will start too early when the <code><my-app></code> element is not created yet (alternatively, <code>import('app')</code> can be called on 'document ready' event).</p>
<p>You can find complete example on github: <a href="https://github.com/fictitious/test-systemjs-angular-gulp" rel="noreferrer">https://github.com/fictitious/test-systemjs-angular-gulp</a></p> |
20,822,711 | jquery window.open in ajax success being blocked | <p>Trying to open a new browser window in my ajax success call, however, it is blocked as a popup. I did some searching and found that a user event needs to be tied to the window.open for this to not happen.</p>
<p>I also found this solution where you open a blank window before the ajax then load the url as normal in the success call.</p>
<p>So with this I have two questions :</p>
<p>1 - Is this the only solution because I would prefer not to open this blank window.</p>
<p>2 - If this indeed is the only way then how can I load my html into this new window? For example, if my ajax does not succeed, how can I add my error text into this blank window since the url will not be opened?</p>
<p>I should also note that I do not want to make the ajax call synchronous... this defeats the purpose of ajax and I believe this is going to be deprecated if not already... correct me if I read wrong in my searching.</p>
<pre><code> $('#user-login').on('click', function () {
var $form = $(this).closest('form');
window.open('about:blank', 'myNewPage');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_user_login.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
$myElem = $('#user_login_message'); //performance for not checking dom
$myElem.fadeOut('fast', function(){
if (response.success)
{
$myElem.html('<p><b class="text-blue">Success!</b> &nbsp;You have been logged in as \'<b>'+response.username+'</b>\' in a new browser window.</p>').fadeIn('fast');
// open new window as logged in user
//window.open('http://www.example.com/');
window.open('http://www.example.com/', 'myNewPage');
}
else
{
$myElem.html('<p><b class="text-red">Error!</b> &nbsp;Please select a valid user from the dropdown list.</p>').fadeIn('fast');
}
});
});
});
</code></pre>
<p><strong>EDIT:</strong></p>
<p>For anyone interested... here is the solution I came up with. A name is required for the new window so successive clicks will open in the same window and not open new ones repeatedly. Adding html is a little different than given in the answer and this works. Blurring of the window does not work so it is not there. From what I could find this is not controllable and is a browser thing.</p>
<pre><code> $('#user-login').on('click', function () {
var $form = $(this).closest('form');
//open blank window onclick to prevent popup blocker
var loginWindow = window.open('', 'UserLogin');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_user_login.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
$myElem = $('#user_login_message'); //performance for not checking dom
$myElem.fadeOut('fast', function(){
if (response.success)
{
// show success
$myElem.html('<p><b class="text-blue">Success!</b> &nbsp;You have been logged in as \'<b>'+response.username+'</b>\' in a new browser window.</p>').fadeIn('fast');
// open new window as logged in user
loginWindow.location.href = 'http://www.example.com/';
}
else
{
// show error
$myElem.html('<p><b class="text-red">Error!</b> &nbsp;Please select a valid user from the dropdown list.</p>').fadeIn('fast');
// add error to the new window (change this to load error page)
loginWindow.document.body.innerHTML = '<p><b>Error!</b> &nbsp;Please select a valid user from the dropdown list.</p>';
}
});
});
</code></pre> | 20,822,754 | 3 | 2 | null | 2013-12-29 06:20:28.71 UTC | 9 | 2020-02-21 04:40:31.113 UTC | 2020-02-21 04:40:31.113 UTC | null | 6,500,909 | null | 756,659 | null | 1 | 32 | javascript|ajax|jquery | 83,274 | <p>For opening a new URL in the window you opened in <code>onclick</code>, do the following</p>
<ol>
<li>Store the new window you created in a variable <code>var newWindow = window.open("","_blank");</code></li>
<li>Change the location of the new window <code>newWindow.location.href = newURL;</code></li>
</ol>
<p>One additional thing that can be done to improve user experience is to send the new window to background immediately (<code>newWindow.blur</code>) after opening and then bring it in foreground again (<code>newWindow.focus</code>) while opening the URL the the new window.</p> |
3,471,613 | Passing a parameter to onclick listener on a button in a listview row | <p>I just started android and I'm running into some problems.<br>
I have created a <code>ListView</code> that is populated from a database.<br>
Each row has a button to delete the item from the list and the database. </p>
<p>I am able to hook up an event listener to the button but I have not been able to determine the matching database record to be deleted. </p>
<p>My class is shown below </p>
<pre><code>public class FeedArrayAdapter extends ArrayAdapter<Feed> implements OnClickListener
{
private ARssEReaderDBAdapter dba;
private String TAG = "FeedArrayAdapter";
public FeedArrayAdapter(Context context, int textViewResourceId, List<Feed> items) {
super(context, textViewResourceId, items);
Log.w(TAG, "List");
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.w(TAG, "getView");
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feedlistrow, null);
}
Feed feed = getItem(position);
if (feed != null) {
TextView title = (TextView)v.findViewById(R.id.TextView01);
if (title != null) {
title.setText(feed.getTitle());
}
Button btnDelete = (Button)v.findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(this); //btnDeleteFeedListener
}
return v;
}
public void onClick(View v) {
Log.w(TAG, "something got clicked: ");
}
</code></pre>
<p>So how can I pass the database record ID to the handler so I can use the database adapter to delete it?</p> | 3,471,777 | 2 | 0 | null | 2010-08-12 20:07:40.64 UTC | 9 | 2016-09-13 05:46:30.783 UTC | 2016-09-13 05:46:30.783 UTC | null | 1,113,598 | null | 418,874 | null | 1 | 20 | android|listview|button | 26,193 | <p>You should store the ID of the record in the Tag, call <code>setTag()</code> on your view, and to read in onclick call <code>getTag()</code></p> |
3,529,666 | matplotlib matshow labels | <p>I start using matplotlib a month ago, so I'm still learning.<br>
I'm trying to do a heatmap with matshow. My code is the following:</p>
<pre><code>data = numpy.array(a).reshape(4, 4)
cax = ax.matshow(data, interpolation='nearest', cmap=cm.get_cmap('PuBu'), norm=LogNorm())
cbar = fig.colorbar(cax)
ax.set_xticklabels(alpha)
ax.set_yticklabels(alpha)
</code></pre>
<p>where alpha is a model from django with 4fields: 'ABC', 'DEF', 'GHI', 'JKL'</p>
<p>the thing is that I don't know why, the label 'ABC' doesn't appear, leaving the last cell without label.<br>
If someone would have a clue how to modify my script in a way to appear the 'ABC' I would be grateful :)</p> | 3,532,408 | 2 | 0 | null | 2010-08-20 09:30:25.643 UTC | 17 | 2020-12-04 23:02:22.797 UTC | 2011-07-23 01:57:13.57 UTC | null | 38,140 | null | 426,176 | null | 1 | 33 | python|django|matplotlib|label | 69,946 | <p>What's happening is that the xticks actually extend outside of the displayed figure when using matshow. (I'm not quite sure exactly why this is. I've almost never used matshow, though.) </p>
<p>To demonstrate this, look at the output of <code>ax.get_xticks()</code>. In your case, it's <code>array([-1., 0., 1., 2., 3., 4.])</code>. Therefore, when you set the xtick labels, "ABC" is at <-1, -1>, and isn't displayed on the figure.</p>
<p>The easiest solution is just to prepend a blank label to your list of labels, e.g.</p>
<pre><code>ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
</code></pre>
<p>As a full example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
alpha = ['ABC', 'DEF', 'GHI', 'JKL']
data = np.random.random((4,4))
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)
ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/fbKgh.png" alt="Matshow example"></p> |
3,939,919 | Can Perl string interpolation perform any expression evaluation? | <p>related to question: <a href="https://stackoverflow.com/questions/3939788/perl-regex-substituion/3939854">How do I substitute with an evaluated expression in Perl?</a></p>
<p>In Perl, is there a way like in Ruby to do:</p>
<pre><code>$a = 1;
print "#{$a + 1}";
</code></pre>
<p>and it can print out <code>2</code>?</p> | 3,939,925 | 2 | 0 | null | 2010-10-15 06:19:38.357 UTC | 12 | 2010-10-15 09:47:08.103 UTC | 2017-05-23 10:31:09.757 UTC | null | -1 | null | 325,418 | null | 1 | 41 | perl|string-interpolation | 13,957 | <p>There's a similar shorthand in Perl for this:</p>
<pre><code>$a = 1;
print "@{[$a + 1]}"
</code></pre>
<p>This works because the <code>[]</code> creates a reference to an array containing one element (the result of the calculation), and then the <code>@{}</code> dereferences the array, which inside string interpolation prints each element of the array in sequence. Since there is only one, it just prints the one element.</p> |
28,747,909 | How to disable spring-data-mongodb autoconfiguration in spring-boot | <p>Has anyone tried disabling autoconfiguration for mongodb in spring-boot?</p>
<p>I am trying out spring-boot with spring-data-mongodb; Using java based configuration; Using spring-boot 1.2.1.RELEASE, I import spring-boot-starter-web and its' parent pom for dependency management. I also import spring-data-mongodb (tried spring-boot-starter-mongodb as well).</p>
<p>I need to connect to two different MongoDB servers. So I need to configure two sets of instances for mongo connection, MongoTemplate etc. <strong>I also want to disable auto-configuration. Since I am connecting to multiple servers, I don't need to have a single default MongoTemplate and GridFsTemplate bean autoconfigured.</strong></p>
<p>My main class looks like this:</p>
<pre><code>@Configuration
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
//@SpringBootApplication // @Configuration @EnableAutoConfiguration @ComponentScan
public class MainRunner {
public static void main(String[] args) {
SpringApplication.run(MainRunner.class, args);
}
}
</code></pre>
<p>My two mongo configuration classes look like this:</p>
<pre><code>@Configuration
@EnableMongoRepositories(basePackageClasses = {Test1Repository.class},
mongoTemplateRef = "template1",
includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Test1Repository")}
)
public class Mongo1Config {
@Bean
public Mongo mongo1() throws UnknownHostException {
return new Mongo("localhost", 27017);
}
@Primary
@Bean
public MongoDbFactory mongoDbFactory1() throws UnknownHostException {
return new SimpleMongoDbFactory(mongo1(), "test1");
}
@Primary
@Bean
public MongoTemplate template1() throws UnknownHostException {
return new MongoTemplate(mongoDbFactory1());
}
}
</code></pre>
<p>and </p>
<pre><code>@Configuration
@EnableMongoRepositories(basePackageClasses = {Test2Repository.class},
mongoTemplateRef = "template2",
includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Test2Repository")}
)
public class Mongo2Config {
@Bean
public Mongo mongo2() throws UnknownHostException {
return new Mongo("localhost", 27017);
}
@Bean
public MongoDbFactory mongoDbFactory2() throws UnknownHostException {
return new SimpleMongoDbFactory(mongo2(), "test2");
}
@Bean
public MongoTemplate template2() throws UnknownHostException {
return new MongoTemplate(mongoDbFactory2());
}
}
</code></pre>
<p>With this setup everything works. If I remove @Primary annotations from mongoDbFactory1 and template1 beans, application will fail with an exception that seems like autoconfiguration hasn't been disabled. Exception message is listed below:</p>
<pre><code>org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:961)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:950)
at com.fourexpand.buzz.web.api.template.MainRunner.main(MainRunner.java:26)
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:98)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:75)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:378)
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:155)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
... 7 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.core.io.ResourceLoader org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.resourceLoader; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gridFsTemplate' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoDataAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.data.mongodb.MongoDbFactory]: : No qualifying bean of type [org.springframework.data.mongodb.MongoDbFactory] is defined: expected single matching bean but found 2: mongoDbFactory2,mongoDbFactory1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.MongoDbFactory] is defined: expected single matching bean but found 2: mongoDbFactory2,mongoDbFactory1
</code></pre> | 28,754,172 | 6 | 5 | null | 2015-02-26 16:41:01.047 UTC | 11 | 2020-10-09 17:34:50.54 UTC | 2015-02-26 16:55:32.89 UTC | null | 4,611,047 | null | 4,611,047 | null | 1 | 47 | java|spring-boot|spring-data|spring-data-mongodb | 73,047 | <p>As pointed out by Andy Wilkinson in comments, when using EnableAutoConfiguration with exclude list make sure there are no other classes annotated with EnableAutoConfiguration or SpringBootApplication.</p> |
16,134,642 | How to save figure with transparent background | <p>I have a plot in Matlab and am setting the background to transparent by:</p>
<pre><code>set(gcf, 'Color', 'None');
set(gca, 'Color', 'None');
</code></pre>
<p>When I try to save the image (from the viewer), I save as a ".png", but it saves with a white background. How can I save it with the transparent background?</p> | 16,134,889 | 6 | 0 | null | 2013-04-21 18:23:16.587 UTC | 1 | 2021-11-18 11:09:34.127 UTC | 2021-02-18 13:38:14.1 UTC | null | 1,536,976 | null | 225,814 | null | 1 | 15 | image|matlab|visualization | 44,990 | <p>It is disappointing but, MATLAB's default <code>saveas</code> and <code>print</code> commands cannot deal with transparent things very well. You'll have to save it with some background and then convert it either through <code>imread</code>/<code>imwrite</code> or some other tool.</p>
<p>There are some tools that might be helpful:</p>
<ul>
<li>Export fig <a href="http://www.mathworks.com/matlabcentral/fileexchange/23629" rel="noreferrer">http://www.mathworks.com/matlabcentral/fileexchange/23629</a></li>
<li>svg export <a href="http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures" rel="noreferrer">http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures</a></li>
</ul>
<p>I prefer vector graphics, so use svg exports when transparency is needed. If indeed you have a bitmap, use <code>imwrite(bitmapData, 'a.png', 'png', 'transparency', backgroundColor)</code>.</p> |
16,501,424 | Algorithm to apply permutation in constant memory space | <p>I saw this question is a programming interview book, here I'm simplifying the question.</p>
<p>Assume you have an array <code>A</code> of length <code>n</code>, and you have a permutation array <code>P</code> of length <code>n</code> as well. Your method will return an array where elements of <code>A</code> will appear in the order with indices specified in <code>P</code>. </p>
<p>Quick example: Your method takes <code>A = [a, b, c, d, e]</code> and <code>P = [4, 3, 2, 0, 1]</code>. then it will return <code>[e, d, c, a, b]</code>. You are allowed to use only constant space (i.e. you can't allocate another array, which takes <code>O(n)</code> space).</p>
<p>Ideas?</p> | 16,501,453 | 9 | 4 | null | 2013-05-11 20:27:34.677 UTC | 9 | 2021-09-07 01:20:54.937 UTC | 2017-11-04 03:09:18.737 UTC | null | 54,929 | null | 54,929 | null | 1 | 20 | arrays|algorithm|permutation|in-place | 8,837 | <p>There is a trivial O(n^2) algorithm, but you can do this in O(n). E.g.:</p>
<p>A = [a, b, c, d, e]</p>
<p>P = [4, 3, 2, 0, 1]</p>
<p>We can swap each element in <code>A</code> with the right element required by <code>P</code>, after each swap, there will be one more element in the right position, and do this in a circular fashion for each of the positions (swap elements pointed with <code>^</code>s):</p>
<pre><code>[a, b, c, d, e] <- P[0] = 4 != 0 (where a initially was), swap 0 (where a is) with 4
^ ^
[e, b, c, d, a] <- P[4] = 1 != 0 (where a initially was), swap 4 (where a is) with 1
^ ^
[e, a, c, d, b] <- P[1] = 3 != 0 (where a initially was), swap 1 (where a is) with 3
^ ^
[e, d, c, a, b] <- P[3] = 0 == 0 (where a initially was), finish step
</code></pre>
<p>After one circle, we find the next element in the array that does not stay in the right position, and do this again. So in the end you will get the result you want, and since each position is touched a constant time (for each position, at most one operation (swap) is performed), it is O(n) time.</p>
<p>You can stored the information of which one is in its right place by:</p>
<ol>
<li><p>set the corresponding entry in P to -1, which is unrecoverable: after the operations above, P will become <code>[-1, -1, 2, -1, -1]</code>, which denotes that only the second one might be not in the right position, and a further step will make sure it is in the right position and terminates the algorithm;</p></li>
<li><p>set the corresponding entry in P to <code>-n - 1</code>: P becomes <code>[-5, -4, 2, -1, -2]</code>, which can be recovered in O(n) trivially.</p></li>
</ol> |
16,072,817 | What does the authority section mean in dig results? | <p>Yesterday I changed my domain's name server from cloudflare to dnspod. And I used dig to test it. But the ANSWER SECTION is always the old name servers. </p>
<pre><code>;; AUTHORITY SECTION:
amazingjxq.com. 21336 IN NS kim.ns.cloudflare.com.
amazingjxq.com. 21336 IN NS brad.ns.cloudflare.com.
</code></pre>
<p>Is the ANSWER SECTION stand for name servers? If so why is it not changed?</p> | 16,073,348 | 2 | 3 | null | 2013-04-18 01:03:45.44 UTC | 12 | 2013-04-18 02:05:47.783 UTC | null | null | null | null | 108,176 | null | 1 | 51 | dns|dig | 63,753 | <p>The <a href="http://en.wikipedia.org/wiki/Domain_Name_System#Authoritative_name_server" rel="noreferrer">Authority section indicates the server(s) that are the ultimate authority</a> for answering DNS queries about that domain. </p>
<p>The reason for this section is that you can query any* DNS server(s) to answer a query for you. That server may choose though to answer the query from a cache. However, if you want to ensure you get an authoritative response ("from the horses mouth" so to speak) - you should ask the server(s) in the authority section. </p>
<p>(* = Any server which will accept your query, that is.)</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.