Programs & Examples On #Runtimemodification

Why doesn't file_get_contents work?

Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.

To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.

<html>
    <head>        
        <title>Test File</title>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
    </head>
    <body>
<?php

# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);

$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';

$jsonData = file_get_contents($url);

print '<p>', var_dump($jsonData), '</p>';

# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
    echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
    echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}


# Decide what to do based on return value:
if ($jsonData === FALSE) {
    echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
    echo "Function is disabled.";
} else {
   echo $jsonData;
}

?>
    </body>
</html>

If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

Ruby array to string conversion

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

Can't connect to MySQL server error 111

111 means connection refused, which in turn means that your mysqld only listens to the localhost interface.

To alter it you may want to look at the bind-address value in the mysqld section of your my.cnf file.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

Access maven properties defined in the pom

Maven already has a solution to do what you want:

Get MavenProject from just the POM.xml - pom parser?

btw: first hit at google search ;)

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Get safe area inset top and bottom heights

Swift 4, 5

To pin a view to a safe area anchor using constraints can be done anywhere in the view controller's lifecycle because they're queued by the API and handled after the view has been loaded into memory. However, getting safe-area values requires waiting toward the end of a view controller's lifecycle, like viewDidLayoutSubviews().

This plugs into any view controller:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = view.safeAreaInsets.top
        bottomSafeArea = view.safeAreaInsets.bottom
    } else {
        topSafeArea = topLayoutGuide.length
        bottomSafeArea = bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

I prefer this method to getting it off of the window (when possible) because it’s how the API was designed and, more importantly, the values are updated during all view changes, like device orientation changes.

However, some custom presented view controllers cannot use the above method (I suspect because they are in transient container views). In such cases, you can get the values off of the root view controller, which will always be available anywhere in the current view controller's lifecycle.

anyLifecycleMethod()
    guard let root = UIApplication.shared.keyWindow?.rootViewController else {
        return
    }
    let topSafeArea: CGFloat
    let bottomSafeArea: CGFloat

    if #available(iOS 11.0, *) {
        topSafeArea = root.view.safeAreaInsets.top
        bottomSafeArea = root.view.safeAreaInsets.bottom
    } else {
        topSafeArea = root.topLayoutGuide.length
        bottomSafeArea = root.bottomLayoutGuide.length
    }

    // safe area values are now available to use
}

Setting up connection string in ASP.NET to SQL SERVER

Connection in WebConfig

Add the your connection string to the <connectionStrings> element in the Web.config file.

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public static string ConnectionString{
get{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;}
set{}

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Here are a couple of things that could be preventing you from connecting to your Linode instance:

  1. DNS problem: if the computer that you're using to connect to your remote server isn't resolving test.kameronderdehamer.nl properly then you won't be able to reach your host. Try to connect using the public IP address assigned to your Linode and see if it works (e.g. ssh [email protected]). If you can connect using the public IP but not using the hostname that would confirm that you're having some problem with domain name resolution.

  2. Network issues: there might be some network issues preventing you from establishing a connection to your server. For example, there may be a misconfigured router in the path between you and your host, or you may be experiencing packet loss. While this is not frequent, it has happenned to me several times with Linode and can be very annoying. It could be a good idea to check this just in case. You can have a look at Diagnosing network issues with MTR (from the Linode library).

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:

<ul>
  <li>...</li>
  <li>...</li>
  <li>...</li>
</ul>

Thanks.

I get Access Forbidden (Error 403) when setting up new alias

This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.

First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...

    NameVirtualHost     local.webapp.org
    <VirtualHost local.webapp.org:80>
        ServerAdmin [email protected]
        DocumentRoot "E:/Project/my php webapp"
        ServerName local.webapp.org
    </VirtualHost>

Note the way DocumentRoot line is written.

Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.

    <Directory>
        AllowOverride none
        Require all denied
    </Directory>

Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.

    <Directory>
       Options Indexes FollowSymLinks Includes ExecCGI
       AllowOverride none
       Require all granted
    </Directory>

When to use std::size_t?

size_t is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc. It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t - something that unsigned int might not do (e.g. when should you use unsigned long

Laravel redirect back to original destination after login

For Laravel 5.5 and probably 5.4

In App\Http\Middleware\RedirectIfAuthenticated change redirect('/home') to redirect()->intended('/home') in the handle function:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/home');
    }

    return $next($request);
}

in App\Http\Controllers\Auth\LoginController create the showLoginForm() function as follows:

public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

This way if there was an intent for another page it will redirect there otherwise it will redirect home.

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

Select last row in MySQL

If you want the most recently added one, add a timestamp and select ordered in reverse order by highest timestamp, limit 1. If you want to go by ID, sort by ID. If you want to use the one you JUST added, use mysql_insert_id.

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.

Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).

Now, we can utilize Left Join to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:

SELECT child_table.* 
FROM child_table 
LEFT JOIN parent_table 
  ON parent_table.referenced_column = child_table.referencing_column 
WHERE parent_table.referenced_column IS NULL

Now, you can generally do one (or more) of the following steps to fix the data.

  1. Based on your "business logic", you will need to update/match these unmatching value(s), with the existing values in the parent table. You may sometimes need to set them null as well.
  2. Delete these rows having unmatching values.
  3. Add new rows in your parent table, corresponding to the unmatching values in the child table.

Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE syntax.

Which tool to build a simple web front-end to my database

For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

How do I check if an index exists on a table field in MySQL?

You can't run a specific show index query because it will throw an error if an index does not exist. Therefore, you have to grab all indexes into an array and loop through them if you want to avoid any SQL errors.

Heres how I do it. I grab all of the indexes from the table (in this case, leads) and then, in a foreach loop, check if the column name (in this case, province) exists or not.

$this->name = 'province';

$stm = $this->db->prepare('show index from `leads`');
$stm->execute();
$res = $stm->fetchAll();
$index_exists = false;

foreach ($res as $r) {
    if ($r['Column_name'] == $this->name) {
        $index_exists = true;
    }
}

This way you can really narrow down the index attributes. Do a print_r of $res in order to see what you can work with.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

An HTML response from the web server normally indicates that an error page has been served instead of the response from the WCF service. My first suggestion would be to check that the user you're running the WCF client under has access to the resource.

MAC addresses in JavaScript

If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.

Getting "Cannot call a class as a function" in my React Project

I received this error by making small mistake. My error was exporting the class as a function instead of as a class. At the bottom of my class file I had:

export default InputField();

when it should have been:

export default InputField;

Custom Adapter for List View

check this link, in very simple via the convertView, we can get the layout of a row which will be displayed in listview (which is the parentView).

View v = convertView;

if (v == null) {

    LayoutInflater vi;
    vi = LayoutInflater.from(getContext());
    v = vi.inflate(R.layout.itemlistrow, null);

}

using the position, you can get the objects of the List<Item>.

Item p = items.get(position);

after that we'll have to set the desired details of the object to the identified form widgets.

if (p != null) {

    TextView tt = (TextView) v.findViewById(R.id.id);
    TextView tt1 = (TextView) v.findViewById(R.id.categoryId);
    TextView tt3 = (TextView) v.findViewById(R.id.description);

    if (tt != null) {
        tt.setText(p.getId());
    }
    if (tt1 != null) {

        tt1.setText(p.getCategory().getId());
    }
    if (tt3 != null) {

        tt3.setText(p.getDescription());
    }
}

then it will return the constructed view which will be attached to the parentView (which is a ListView/GridView).

.gitignore is ignored by Git

Even if you haven't tracked the files so far, Git seems to be able to "know" about them even after you add them to .gitignore.

WARNING: First commit or stash your current changes, or you will lose them.

Then run the following commands from the top folder of your Git repository:

git rm -r --cached .
git add .
git commit -m "fixed untracked files"

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

Print array without brackets and commas

You can use join method from android.text.TextUtils class like:

TextUtils.join("",array);

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Pass a local file in to URL in Java

I tried it with Java on Linux. The following possibilities are OK:

file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html  (if current directory is /home/userId)

not working is:

file://aaaa.html

Get list of certificates from the certificate store in C#

Try this:

//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{

    X509Certificate2 certSelected = null;
    X509Store x509Store = new X509Store(store, location);
    x509Store.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection col = x509Store.Certificates;
    X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);

    if (sel.Count > 0)
    {
        X509Certificate2Enumerator en = sel.GetEnumerator();
        en.MoveNext();
        certSelected = en.Current;
    }

    x509Store.Close();

    return certSelected;
}

Border length smaller than div width?

I just accomplished the opposite of this using :after and ::after because I needed to make my bottom border exactly 1.3rem wider:

My element got super deformed when I used :before and :after at the same time because the elements are horizontally aligned with display: flex, flex-direction: row and align-items: center.

You could use this for making something wider or narrower, or probably any mathematical dimension mods:

a.nav_link-active {
  color: $e1-red;
  margin-top: 3.7rem;
}
a.nav_link-active:visited {
  color: $e1-red;
}
a.nav_link-active:after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-left: -$nav-spacer-margin;
  display: block;
}
a.nav_link-active::after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-right: -$nav-spacer-margin;
  display: block;
}

Sorry, this is SCSS, just multiply the numbers by 10 and change the variables with some normal values.

Round number to nearest integer

If you need (for example) a two digit approximation for A, then int(A*100+0.5)/100.0 will do what you are looking for.

If you need three digit approximation multiply and divide by 1000 and so on.

MVC DateTime binding with incorrect date format

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

Finding element's position relative to the document

http://www.quirksmode.org/js/findpos.html Explains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.

MySQL Event Scheduler on a specific time everyday

My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:

CREATE EVENT applog_clean_event
ON SCHEDULE 
    EVERY 1 DAY
    STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO 

javascript regex for special characters

a sleaker way to match special chars:

/\W|_/g

\W Matches any character that is not a word character (alphanumeric & underscore).

Underscore is considered a special character so add boolean to either match a special character or _

What's the most efficient way to erase duplicates and sort a vector?

You need to sort it before you call unique because unique only removes duplicates that are next to each other.

edit: 38 seconds...

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In Windows, I only managed to be able to delete the lock file after Ending Task for all Git Windows (32bit) processes in the Task Manager.

Solution (Win 10)

1. End Task for all Git Windows (32bit) processes in the Task Manager

2. Delete the .git/index.lock file

What is a mutex?

Mutual Exclusion. Here's the Wikipedia entry on it.

The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.

Specific details of how this is accomplished obviously varies greatly by programming language.

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")

Timeout:

Example (1 second):

TIMEOUT /T 1000 /NOBREAK

Sleep:

Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files

Example:

echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

How to make a link open multiple pages when clicked

HTML:

<a href="#" class="yourlink">Click Here</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('http://yoururl1.com');
    window.open('http://yoururl2.com');
});

window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.

Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.

Cannot change version of project facet Dynamic Web Module to 3.0?

What worked for me:

  1. Change the Java to 1.8 (or 1.7)

In your POM - you have to set compiler plugin to version 1.8 (or 1.7) in <build> section:

  <build>
    ...
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.6.0</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>  
      </plugins>    
  </build>

Ensure that change Java Build shows 1.8. If it does not - click EDIT and select what it should be.

enter image description here

  1. Modify web.xml so 3.0 is referenced in version and in the link

enter image description here

  1. Ensure you have Java set to 1.8 in Project Facets

enter image description here

  1. At this stage I still could not change Dynamic Web Module;

Instead of changing it:

a) uncheck the Dynamic Web Module

b) apply

c) check it again. New version 3.0 should be set.**

enter image description here

After applying and checking it again:

enter image description here

Hope this helps.

Save bitmap to file function

In kotlin :

private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
    outputStream().use { out ->
        bitmap.compress(format, quality, out)
        out.flush()
    }
}

usage example:

File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Open Android Studio, Go to Tools then Android and then SDK, uncheck NDK If you do not need this, and restart android studio.

Table and Index size in SQL Server

EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"

How to print an exception in Python 3?

Try

try:
    print undefined_var
except Exception as e:
    print(e)

this will print the representation given by e.__str__():

"name 'undefined_var' is not defined"

you can also use:

print(repr(e))

which will include the Exception class name:

"NameError("name 'undefined_var' is not defined",)"

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en

Iterating over dictionaries using 'for' loops

Iterating over dictionaries using 'for' loops

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    ...

How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

It's not just for loops. The important word here is "iterating".

A dictionary is a mapping of keys to values:

d = {'x': 1, 'y': 2, 'z': 3} 

Any time we iterate over it, we iterate over the keys. The variable name key is only intended to be descriptive - and it is quite apt for the purpose.

This happens in a list comprehension:

>>> [k for k in d]
['x', 'y', 'z']

It happens when we pass the dictionary to list (or any other collection type object):

>>> list(d)
['x', 'y', 'z']

The way Python iterates is, in a context where it needs to, it calls the __iter__ method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):

>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>

We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter:

>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>

Iterators have a __next__ method - but we call it with the builtin function, next:

>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When an iterator is exhausted, it raises StopIteration. This is how Python knows to exit a for loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration it will always raise it - if you want to iterate again, you need a new one.

>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']

Returning to dicts

We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:

If we change the variable name, we still get the keys. Let's try it:

>>> for each_key in d:
...     print(each_key, '=>', d[each_key])
... 
x => 1
y => 2
z => 3

If we want to iterate over the values, we need to use the .values method of dicts, or for both together, .items:

>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]

In the example given, it would be more efficient to iterate over the items like this:

for a_key, corresponding_value in d.items():
    print(a_key, corresponding_value)

But for academic purposes, the question's example is just fine.

Check whether user has a Chrome extension installed

Chrome now has the ability to send messages from the website to the extension.

So in the extension background.js (content.js will not work) add something like:

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        if (request) {
            if (request.message) {
                if (request.message == "version") {
                    sendResponse({version: 1.0});
                }
            }
        }
        return true;
    });

This will then let you make a call from the website:

var hasExtension = false;

chrome.runtime.sendMessage(extensionId, { message: "version" },
    function (reply) {
        if (reply) {
            if (reply.version) {
                if (reply.version >= requiredVersion) {
                    hasExtension = true;
                }
            }
        }
        else {
          hasExtension = false;
        }
    });

You can then check the hasExtension variable. The only drawback is the call is asynchronous, so you have to work around that somehow.

Edit: As mentioned below, you'll need to add an entry to the manifest.json listing the domains that can message your addon. Eg:

"externally_connectable": {
    "matches": ["*://localhost/*", "*://your.domain.com/*"]
},

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

Difference between View and table in sql

SQL Views:

View is a virtual table based on the result-set of an SQL statement and that is Stored in the database with some name.

SQL Table:

SQL table is database instance consists of fields (columns), and rows.

Check following post, author listed around seven differences between views and table

https://codechef4u.com/post/2015/09/03/sql-views-vs-tables

How to check if a function exists on a SQL database

I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:

IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1

This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.

The OBJECTPROPERTY function uses the following signature:

OBJECTPROPERTY ( id , property ) 

You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.

How do I use Assert.Throws to assert the type of the exception?

You can now use the ExpectedException attributes, e.g.

[Test]
[ExpectedException(typeof(InvalidOperationException), 
 ExpectedMessage="You can't do that!"]
public void MethodA_WithNull_ThrowsInvalidOperationException()
{
    MethodA(null);
}

(Deep) copying an array using jQuery

I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.

http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

Overflow Scroll css is not working in the div

The solution is to add height:100%; to all the parent elements of your .wrapper-div as well. So:

html{
    height: 100%;
}

body{ 
    margin:0;
    padding:0;
    overflow:hidden;
    height:100%;
}

#container{
    width:1000px;
    margin:0 auto;
    height:100%;
}

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

Exit a while loop in VBS/VBA

VBScript's While loops don't support early exit. Use the Do loop for that:

num = 0
do while (num < 10)
  if (status = "Fail") then exit do
  num = num + 1
loop

Checkout one file from Subversion

An update in case what you really need can be covered by having the file included in a checkout of another folder.

Since SVN 1.6 you can make file externals, a kind of svn links. It means that you can have another versioned folder that includes a single file. Committing changes to the file in a checkout of this folder is also possible.

It's very simple, checkout the folder you want to include the file, and simply add a property to the folder

svn propedit svn:externals .

with content like this:

file.txt /repos/path/to/file.txt

After you commit this, the file will appear in future checkouts of the folder. Basically it works, but there are some limitations as described in the documentation linked above.

Bash array with spaces in elements

I think the issue might be partly with how you're accessing the elements. If I do a simple for elem in $FILES, I experience the same issue as you. However, if I access the array through its indices, like so, it works if I add the elements either numerically or with escapes:

for ((i = 0; i < ${#FILES[@]}; i++))
do
    echo "${FILES[$i]}"
done

Any of these declarations of $FILES should work:

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

or

FILES=("2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg")

or

FILES[0]="2011-09-04 21.43.02.jpg"
FILES[1]="2011-09-05 10.23.14.jpg"
FILES[2]="2011-09-09 12.31.16.jpg"
FILES[3]="2011-09-11 08.43.12.jpg"

Get form data in ReactJS

No need to use refs, you can access using event

function handleSubmit(e) {
    e.preventDefault()
    const {username, password } = e.target.elements
    console.log({username: username.value, password: password.value })
}

<form onSubmit={handleSubmit}>
   <input type="text" id="username"/>
   <input type="text" id="password"/>
   <input type="submit" value="Login" />
</form>

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I would recommend to look at the error_logs, specifically at the upstream part where it shows specific upstream that is timing out.

Then based on that you can adjust proxy_read_timeout, fastcgi_read_timeout or uwsgi_read_timeout.

Also make sure your config is loaded.

More details here Nginx upstream timed out (why and how to fix)

Return from a promise then()

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

Hope this helps!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }

How to right-align and justify-align in Markdown?

If you want to use justify align in Jupyter Notebook use the following syntax:

<p style='text-align: justify;'> Your Text </p>

For right alignment:

<p style='text-align: right;'> Your Text </p>

Adding external library in Android studio

For the simplest way just follow these steps

  1. Go to File -> New -> Import Module -> choose library or project folder

  2. Add library to include section in settings.gradle file and sync the project (After that you can see new folder with library name is added in project structure)

    include ':mylibraryName'

  3. Go to File -> Project Structure -> app -> dependency tab -> click on plus button

  4. Select module dependency -> select library (your library name should appear there) and put scope (compile or implementation)

  5. Add this line in build.gradle in app level module in dependency section

    implementation project(':mylibraryName')

Removing duplicate values from a PowerShell array

This is how you get unique from an array with two or more properties. The sort is vital and the key to getting it to work correctly. Otherwise you just get one item returned.

PowerShell Script:

$objects = @(
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
)

Write-Host "Sorted on both properties with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message,MachineName -Unique | Out-Host

Write-Host "Sorted on just Message with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message -Unique | Out-Host

Write-Host "Sorted on just MachineName with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property MachineName -Unique | Out-Host

Output:

Sorted on both properties with -Unique

Message MachineName
------- -----------
1       1          
1       2          
2       1          
2       2          
3       1          
3       2          
4       1          
4       2          
5       1          
5       2          


Sorted on just Message with -Unique

Message MachineName
------- -----------
1       1          
2       1          
3       1          
4       1          
5       2          


Sorted on just MachineName with -Unique

Message MachineName
------- -----------
1       1          
3       2  

Source: https://powershell.org/forums/topic/need-to-unique-based-on-multiple-properties/

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

Create JPA EntityManager without persistence.xml configuration file

I was able to create an EntityManager with Hibernate and PostgreSQL purely using Java code (with a Spring configuration) the following:

@Bean
public DataSource dataSource() {
    final PGSimpleDataSource dataSource = new PGSimpleDataSource();

    dataSource.setDatabaseName( "mytestdb" );
    dataSource.setUser( "myuser" );
    dataSource.setPassword("mypass");

    return dataSource;
}

@Bean
public Properties hibernateProperties(){
    final Properties properties = new Properties();

    properties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
    properties.put( "hibernate.connection.driver_class", "org.postgresql.Driver" );
    properties.put( "hibernate.hbm2ddl.auto", "create-drop" );

    return properties;
}

@Bean
public EntityManagerFactory entityManagerFactory( DataSource dataSource, Properties hibernateProperties ){
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource( dataSource );
    em.setPackagesToScan( "net.initech.domain" );
    em.setJpaVendorAdapter( new HibernateJpaVendorAdapter() );
    em.setJpaProperties( hibernateProperties );
    em.setPersistenceUnitName( "mytestdomain" );
    em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    em.afterPropertiesSet();

    return em.getObject();
}

The call to LocalContainerEntityManagerFactoryBean.afterPropertiesSet() is essential since otherwise the factory never gets built, and then getObject() returns null and you are chasing after NullPointerExceptions all day long. >:-(

It then worked with the following code:

PageEntry pe = new PageEntry();
pe.setLinkName( "Google" );
pe.setLinkDestination( new URL( "http://www.google.com" ) );

EntityTransaction entTrans = entityManager.getTransaction();
entTrans.begin();
entityManager.persist( pe );
entTrans.commit();

Where my entity was this:

@Entity
@Table(name = "page_entries")
public class PageEntry {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String linkName;
    private URL linkDestination;

    // gets & setters omitted
}

For Loop on Lua

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end
  1. You're deleting your table and replacing it with an int
  2. You aren't pulling a value from the table

Try:

names = {'John','Joe','Steve'}
for i = 1,3 do
    print(names[i])
end

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

Oracle query to identify columns having special characters

You can use regular expressions for this, so I think this is what you want:

select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')

Automatically get loop index in foreach loop in Perl

I have tried like....

@array = qw /tomato banana papaya potato/;             # Example array
my $count;                                             # Local variable initial value will be 0.
print "\nBefore For loop value of counter is $count";  # Just printing value before entering the loop.

for (@array) { print "\n",$count++," $_" ; }           # String and variable seperated by comma to
                                                       # execute the value and print.
undef $count;                                          # Undefining so that later parts again it will
                                                       # be reset to 0.

print "\nAfter for loop value of counter is $count";   # Checking the counter value after for loop.

In short...

@array = qw /a b c d/;
my $count;
for (@array) { print "\n",$count++," $_"; }
undef $count;

"starting Tomcat server 7 at localhost has encountered a prob"

I was having the same problem when my workspace was in E:\ drive. Then I changed my workspace location to C:\User\\ location. The problem seems to be solved now.

RadioGroup: How to check programmatically

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(R.id.option1); b.setChecked(true);

throwing exceptions out of a destructor

Throwing an exception out of a destructor is dangerous.
If another exception is already propagating the application will terminate.

#include <iostream>

class Bad
{
    public:
        // Added the noexcept(false) so the code keeps its original meaning.
        // Post C++11 destructors are by default `noexcept(true)` and
        // this will (by default) call terminate if an exception is
        // escapes the destructor.
        //
        // But this example is designed to show that terminate is called
        // if two exceptions are propagating at the same time.
        ~Bad() noexcept(false)
        {
            throw 1;
        }
};
class Bad2
{
    public:
        ~Bad2()
        {
            throw 1;
        }
};


int main(int argc, char* argv[])
{
    try
    {
        Bad   bad;
    }
    catch(...)
    {
        std::cout << "Print This\n";
    }

    try
    {
        if (argc > 3)
        {
            Bad   bad; // This destructor will throw an exception that escapes (see above)
            throw 2;   // But having two exceptions propagating at the
                       // same time causes terminate to be called.
        }
        else
        {
            Bad2  bad; // The exception in this destructor will
                       // cause terminate to be called.
        }
    }
    catch(...)
    {
        std::cout << "Never print this\n";
    }

}

This basically boils down to:

Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions.

The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem).

So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business.

An example:

std::fstream

The close() method can potentially throw an exception. The destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor.

So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation.

Scott Myers has an excellent article about the subject in his book "Effective C++"

Edit:

Apparently also in "More Effective C++"
Item 11: Prevent exceptions from leaving destructors

Difference between dict.clear() and assigning {} in Python

In addition to @odano 's answer, it seems using d.clear() is faster if you would like to clear the dict for many times.

import timeit

p1 = ''' 
d = {}
for i in xrange(1000):
    d[i] = i * i
for j in xrange(100):
    d = {}
    for i in xrange(1000):
        d[i] = i * i
'''

p2 = ''' 
d = {}
for i in xrange(1000):
    d[i] = i * i
for j in xrange(100):
    d.clear()
    for i in xrange(1000):
        d[i] = i * i
'''

print timeit.timeit(p1, number=1000)
print timeit.timeit(p2, number=1000)

The result is:

20.0367929935
19.6444659233

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Inserting string at position x of another string

var output = a.substring(0, position) + b + a.substring(position);

Edit: replaced .substr with .substring because .substr is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)

Can constructors be async?

Some of the answers involve creating a new public method. Without doing this, use the Lazy<T> class:

public class ViewModel
{
    private Lazy<ObservableCollection<TData>> Data;

    async public ViewModel()
    {
        Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
    }

    public ObservableCollection<TData> GetDataTask()
    {
        Task<ObservableCollection<TData>> task;

        //Create a task which represents getting the data
        return task.GetAwaiter().GetResult();
    }
}

To use Data, use Data.Value.

I want to load another HTML page after a specific amount of time

use this JavaScript code:

<script>
    setTimeout(function(){
       window.location.href = 'form2.html';
    }, 5000);
</script>

python JSON only get keys in first level

for key in data.keys():
    print key

Better way to find control in ASP.NET

https://blog.codinghorror.com/recursive-pagefindcontrol/

Page.FindControl("DataList1:_ctl0:TextBox3");

OR

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

convert an enum to another type of enum

I wrote a set extension methods a while back that work for several different kinds of Enums. One in particular works for what you are trying to accomplish and handles Enums with the FlagsAttribute as well as Enums with different underlying types.

public static tEnum SetFlags<tEnum>(this Enum e, tEnum flags, bool set, bool typeCheck = true) where tEnum : IComparable
{
    if (typeCheck)
    {
        if (e.GetType() != flags.GetType())
            throw new ArgumentException("Argument is not the same type as this instance.", "flags");
    }

    var flagsUnderlyingType = Enum.GetUnderlyingType(typeof(tEnum));

    var firstNum = Convert.ToUInt32(e);
    var secondNum = Convert.ToUInt32(flags);

    if (set)
        firstNum |= secondNum;

    else
        firstNum &= ~secondNum;

    var newValue = (tEnum)Convert.ChangeType(firstNum, flagsUnderlyingType);

    if (!typeCheck)
    {
        var values = Enum.GetValues(typeof(tEnum));
        var lastValue = (tEnum)values.GetValue(values.Length - 1);

        if (newValue.CompareTo(lastValue) > 0)
            return lastValue;
    }

    return newValue;
}

From there you can add other more specific extension methods.

public static tEnum AddFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
    SetFlags(e, flags, true);
}

public static tEnum RemoveFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
    SetFlags(e, flags, false);
}

This one will change types of Enums like you are trying to do.

public static tEnum ChangeType<tEnum>(this Enum e) where tEnum : IComparable
{
    return SetFlags(e, default(tEnum), true, false);
}

Be warned, though, that you CAN convert between any Enum and any other Enum using this method, even those that do not have flags. For example:

public enum Turtle
{
    None = 0,
    Pink,
    Green,
    Blue,
    Black,
    Yellow
}

[Flags]
public enum WriteAccess : short
{
   None = 0,
   Read = 1,
   Write = 2,
   ReadWrite = 3
}

static void Main(string[] args)
{
    WriteAccess access = WriteAccess.ReadWrite;
    Turtle turtle = access.ChangeType<Turtle>();
}

The variable turtle will have a value of Turtle.Blue.

However, there is safety from undefined Enum values using this method. For instance:

static void Main(string[] args)
{
    Turtle turtle = Turtle.Yellow;
    WriteAccess access = turtle.ChangeType<WriteAccess>();
}

In this case, access will be set to WriteAccess.ReadWrite, since the WriteAccess Enum has a maximum value of 3.

Another side effect of mixing Enums with the FlagsAttribute and those without it is that the conversion process will not result in a 1 to 1 match between their values.

public enum Letters
{
    None = 0,
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

[Flags]
public enum Flavors
{
    None = 0,
    Cherry = 1,
    Grape = 2,
    Orange = 4,
    Peach = 8
}

static void Main(string[] args)
{
    Flavors flavors = Flavors.Peach;
    Letters letters = flavors.ChangeType<Letters>();
}

In this case, letters will have a value of Letters.H instead of Letters.D, since the backing value of Flavors.Peach is 8. Also, a conversion from Flavors.Cherry | Flavors.Grape to Letters would yield Letters.C, which can seem unintuitive.

Simple PowerShell LastWriteTime compare

I can't fault any of the answers here for the OP accepted one of them as resolving their problem. However, I found them flawed in one respect. When you output the result of the assignment to the variable, it contains numerous blank lines, not just the sought after answer. Example:

PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime

Friday, December 12, 2014 2:33:09 PM



PS C:\brh> 

I'm a fan of two things in code, succinctness and correctness. brianary has the right of it for succinctness with a tip of the hat to Roger Lipscombe but both miss correctness due to the extra lines in the result. Here's what I think the OP was looking for since it's what got me over the finish line.

PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM

PS C:\brh> 

Note the lack of extra lines, only the one that PowerShell uses to separate prompts. Now this can be assigned to a variable for comparison or, as in my case, stored in a file for reading and comparison in a later session.

How to monitor the memory usage of Node.js?

node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

How to get a dependency tree for an artifact?

If you'd like to get a graphical, searchable representation of the dependency tree (including all modules from your project, transitive dependencies and eviction information), check out UpdateImpact: https://app.updateimpact.com (free service).

Disclaimer: I'm one of the developers of the site

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I had the same problem with a stripes taglib uri showing as not found. I was using Indigo and Maven and when I checked Properties->Java Build Path->Order & Export Tab I found (on a fresh project checkout) that the "Maven Dependencies" checkbox was unchecked for some reason. Simply checking that box and doing a Maven clean install cleared all the errors.

I wonder why Eclipse doesn't assume I want my Maven dependencies in the build path...

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

How to write files to assets folder or raw folder in android?

You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

The report might want to access a DataSource or DataView where the AD user (or AD group) has insuficcient access rights.

Make sure you check out the following URLs:

  • http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSources
  • http://REPORTSERVERNAME/Reports/Pages/Folder.aspx?ItemPath=%2fDataSets

Then choose Folder Settings

Folder Settings

(or the appropriate individual DataSource or DataSet) and select Security. The user group needs to have the Browser permission.

enter image description here

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to atomically delete keys matching a pattern using Redis

I think what might help you is the MULTI/EXEC/DISCARD. While not 100% equivalent of transactions, you should be able to isolate the deletes from other updates.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Stop a gif animation onload, on mouseover start the activation

This answer builds on that of Sourabh, who pointed out an HTML/CSS/JavaScript combo at https://codepen.io/hoanghals/pen/dZrWLZ that did the job. I tried this, and made a complete web page including the CSS and JavaScript, which I tried on my site. As CodePens have a habit of disappearing, I decided to show it here. I'm also showing a simplified stripped-to-essentials version, to demonstrate the minimum that one needs to do.

I must also note one thing. The code at the above link, whose JavaScript Sourabh copies, refers to a JavaScript constructor SuperGif() . I don't think Sourabh explained that, and neither does the CodePen. An easy search showed that it's defined in buzzfeed / libgif-js , which can be downloaded from https://github.com/buzzfeed/libgif-js#readme . Look for the control that the red arrow below is pointing at, then click on the green "Code" button. (N.B. You won't see the red arrow: that's me showing you where to look.)

Screenshot of GitHub page for buzzfeed/libgif-js

A menu will pop up offering various options including to download a zip file. Download it, and extract it into your HTML directory or a subdirectory thereof.

Next, I'm going to show the two pages that I made. The first is derived from the CodePen. The second is stripped to its essentials, and shows the minimum you need in order to use SuperGif.

So here's the complete HTML, CSS, and JavaScript for the first page. In the head of the HTML is a link to libgif.js , which is the file you need from the zip file. Then, the body of the HTML starts with some text about cat pictures, and follows it with a link to an animated cat GIF at https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif .

It then continues with some CSS. The CodePen uses SCSS, which for anyone who doesn't know, has to be preprocessed into CSS. I've done that, so what's in the code below is genuine CSS.

Finally, there's the JavaScript.

<html>
<head>
<script src="libgif-js-master/libgif.js"></script> 
</head>

<body>

<div style="width: 600px; margin: auto; text-align: center; font-family: arial">
  <p>
And so, the unwritten law of the internet, that any 
experiment involving video/images must involve cats in 
one way or another, reared its head again. When would 
the internet's fascination with cats come to an end? 
Never. The answer is "Never".
</p> 
  <img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</div>

<style>
img.gif {
  visibility: hidden;
}

.jsgif {
  position: relative;
}

.gifcontrol {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: background 0.25s ease-in-out;
  z-index: 100;
}
.gifcontrol:after {
  transition: background 0.25s ease-in-out;
  position: absolute;
  content: "";
  display: block;
  left: calc(50% - 25px);
  top: calc(50% - 25px);
}
.gifcontrol.loading {
  background: rgba(255, 255, 255, 0.75);
}
.gifcontrol.loading:after {
  background: #FF9900;
  width: 50px;
  height: 50px;
  border-radius: 50px;
}
.gifcontrol.playing {
  /* Only show the 'stop' button on hover */
}
.gifcontrol.playing:after {
  opacity: 0;
  transition: opacity 0.25s ease-in-out;
  border-left: 20px solid #FF9900;
  border-right: 20px solid #FF9900;
  width: 50px;
  height: 50px;
  box-sizing: border-box;
}
.gifcontrol.playing:hover:after {
  opacity: 1;
}
.gifcontrol.paused {
  background: rgba(255, 255, 255, 0.5);
}
.gifcontrol.paused:after {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 25px 0 25px 50px;
  border-color: transparent transparent transparent #ff9900;
}
</style>

<script>
var gifElements = document.querySelectorAll('img.gif');

for(var e in gifElements) {
  
    var element = gifElements[e];
    
    if(element.nodeName == 'IMG') {
    
        var supergif = new SuperGif({
            gif: element,
            progressbar_height: 0,
            auto_play: false,
        });

        var controlElement = document.createElement("div");
        controlElement.className = "gifcontrol loading g"+e;

        supergif.load((function(controlElement) {
            controlElement.className = "gifcontrol paused";
            var playing = false;
            controlElement.addEventListener("click", function(){
                if(playing) {
                    this.pause();
                    playing = false;
                    controlElement.className = "gifcontrol paused";
                } else {
                    this.play();
                    playing = true;
                    controlElement.className = "gifcontrol playing";
                }
            }.bind(this, controlElement));
        
        }.bind(supergif))(controlElement));
    
        var canvas = supergif.get_canvas();     
        controlElement.style.width = canvas.width+"px";
        controlElement.style.height = canvas.height+"px";
    controlElement.style.left = canvas.offsetLeft+"px";
        var containerElement = canvas.parentNode;
        containerElement.appendChild(controlElement);
    
  }
}
</script>

</body>
</html>

When I put the page on my website and displayed it, the top looked like this:

Web page with paused animated GIF of cat

And when I pressed the pink button, the page changed to this, and the GIF started animating. (The cat laps water falling from a tap.)

Web page with running animated GIF of cat

To end, here's the second, simple, page. Unlike the first, this doesn't have a fancy Play/Pause control that changes shape: it just has two buttons. The only thing the code does that isn't essential is to disable whichever button is not relevant, and to insert some space between the buttons.

<html>

<head>
<script src="libgif-js-master/libgif.js"></script>
</head>

<body>

<button type="button" onclick="play()"
        id="play_button"
        style="margin-right:9px;"
>
Play
</button>
      
<button type="button" onclick="pause()"
        id="pause_button"
>
Pause
</button>

<img src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif" 
     id="gif" 
/>

<script>
var gif_element = document.getElementById( "gif" );
    
var supergif = new SuperGif( {
             gif: gif_element,
                          progressbar_height: 0,
                          auto_play: false
               } );

supergif.load();

function play()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = true;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = false;
 
  supergif.play();
}

function pause()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = false;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = true;

  supergif.pause();
}

pause_button.disabled = true;
</script>

</body>
</html>

This, plus the example.html file in libgif-js, should be enough to get anyone started.

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

Where can I get a virtual machine online?

Try this:

http://aws.amazon.com/free/

one year free. I do use this for a while.

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

Best way to remove duplicate entries from a data table

There is a simple way using Linq GroupBy Method.

var duplicateValues = dt.AsEnumerable() 

        .GroupBy(row => row[0]) 

        .Where(group => (group.Count() == 1 || group.Count() > 1)) 

        .Select(g => g.Key); 



foreach (var d in duplicateValues)

        Console.WriteLine(d);

What is the most useful script you've written for everyday life?

I wrote a simple Ruby script to help my wife and I when we were considering names for our first child. It generated all name combinations and checked the initials against a blacklist of initials I wanted to avoid, excluding any that didn't match my criteria. It felt like an appropriate thing for a nerdy dad to do and actually proved to be quite worthwhile and useful.

Other than that I've written a couple of Python scripts that serve as IRC bots which I use every day. One saves URLs, via regular expression matching, to delicious. Another serves as a simple IRC Twitter interface, allowing me to check my feed and post updates.

How to position two elements side by side using CSS

For your iframe give an outer div with style display:inline-block, And for your paragraph div also give display:inline-block

HTML

<div class="side">
    <iframe></iframe>
</div>
<div class="side">
    <p></p>
</div>

CSS

.side {
   display:inline-block;
}

Get model's fields in Django

If you need this for your admin site, there is also the ModelAdmin.get_fields method (docs), which returns a list of field name strings.

For example:

class MyModelAdmin(admin.ModelAdmin):
    # extending change_view, just as an example
    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        # get the model field names
        field_names = self.get_fields(request)
        # use the field names
        ...

Put content in HttpResponseMessage object?

You can create your own specialised content types. For example one for Json content and one for Xml content (then just assign them to the HttpResponseMessage.Content):

public class JsonContent : StringContent
{
    public JsonContent(string content)
        : this(content, Encoding.UTF8)
    {
    }

    public JsonContent(string content, Encoding encoding)
        : base(content, encoding, "application/json")
    {
    }
}

public class XmlContent : StringContent
{
    public XmlContent(string content) 
        : this(content, Encoding.UTF8)
    {
    }

    public XmlContent(string content, Encoding encoding)
        : base(content, encoding, "application/xml")
    {
    }
}

Entity framework linq query Include() multiple children entities

Use extension methods. Replace NameOfContext with the name of your object context.

public static class Extensions{
   public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country") ;
     }

     public static Company CompanyById(this NameOfContext context, int companyID){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country")
             .FirstOrDefault(c => c.Id == companyID) ;
      }

}

Then your code becomes

     Company company = 
          context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);

     //or if you want even more
     Company company = 
          context.CompanyById(companyID);

Set CSS property in Javascript?

It is important to understand that the code bellow does not change the stylesheet, but instead changes the DOM:

document.getElementById("p2").style.color = "blue";

The DOM stores a computed value of the stylesheet element properties, and when you dynamically change an elements style using Javascript you are changing the DOM. This is important to note, and understand because the way you write your code can affect your dynamics. If you try to obtain values that were not written directly into the element itself, like so...

let elem = document.getElementById('some-element');
let propertyValue = elem.style['some-property'];

...you will return an undefined value that will be stored in the code example's 'propertyValue' variable. If you are working with getting and setting properties that were written inside a CSS style-sheet and you want a SINGLE FUNCTION that gets, as well as sets style-property-values in this situation, which is a very common situation to be in, then you have got to use JQuery.

$(selector).css(property,value)

The only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery. If you want to get a CSS property that was computed from a style-sheet in pure JavaScript then you need to use.

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

The downside to this method is that the getComputedValue method only gets, it does not set. Mozilla's Take on Computed Values This link goes more into depth about what I have addressed here. Hope This Helps Someone!!!

What is the use of ByteBuffer in Java?

Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:

  • First advantage of a ByteBuffer irrespective of whether it is direct or indirect is efficient random access of structured binary data (e.g., low-level IO as stated in one of the answers). Prior to Java 1.4, to read such data one could use a DataInputStream, but without random access.

Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:

  1. Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.

  2. Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.

Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.

  1. Page sharing: Memory mapped files can be shared between processes as they are allocated in process's virtual memory space and can be shared across processes.

Logo image and H1 heading on the same line

I'd use bootstrap and set the html as:

<div class="row">
    <div class="col-md-4">
        <img src="img/logo.png" alt="logo" />
    </div>
    <div class="col-md-8">
        <h1>My website name</h1>
    </div>
</div>

Should I use px or rem value units in my CSS?

pt is similar to rem, in that it's relatively fixed, but almost always DPI-independent, even when non-compliant browsers treat px in a device-dependent fashion. rem varies with the font size of the root element, but you can use something like Sass/Compass to do this automatically with pt.

If you had this:

html {
    font-size: 12pt;
}

then 1rem would always be 12pt. rem and em are only as device-independent as the elements on which they rely; some browsers don't behave according to spec, and treat px literally. Even in the old days of the Web, 1 point was consistently regarded as 1/72 inch--that is, there are 72 points in an inch.

If you have an old, non-compliant browser, and you have:

html {
    font-size: 16px;
}

then 1rem is going to be device-dependent. For elements that would inherit from html by default, 1em would also be device-dependent. 12pt would be the hopefully guaranteed device-independent equivalent: 16px / 96px * 72pt = 12pt, where 96px = 72pt = 1in.

It can get pretty complicated to do the math if you want to stick to specific units. For example, .75em of html = .75rem = 9pt, and .66em of .75em of html = .5rem = 6pt. A good rule of thumb:

  • Use pt for absolute sizes. If you really need this to be dynamic relative to the root element, you're asking too much of CSS; you need a language that compiles to CSS, like Sass/SCSS.
  • Use em for relative sizes. It's pretty handy to be able to say, "I want the margin on the left to be about the maximum width of a letter," or, "Make this element's text just a bit bigger than its surroundings." <h1> is a good element on which to use a font size in ems, since it might appear in various places, but should always be bigger than nearby text. This way, you don't have to have a separate font size for every class that's applied to h1: the font size will adapt automatically.
  • Use px for very tiny sizes. At very small sizes, pt can get blurry in some browsers at 96 DPI, since pt and px don't quite line up. If you just want to create a thin, one-pixel border, say so. If you have a high-DPI display, this won't be obvious to you during testing, so be sure to test on a generic 96-DPI display at some point.
  • Don't deal in subpixels to make things fancy on high-DPI displays. Some browsers might support it--particularly on high-DPI displays--but it's a no-no. Most users prefer big and clear, though the web has taught us developers otherwise. If you want to add extended detail for your users with state-of-the-art screens, you can use vector graphics (read: SVG), which you should be doing anyway.

How to generate UML diagrams (especially sequence diagrams) from Java code?

I found Green plugin very simple to use and to generate class diagram from source code. Give it a try :). Just copy the plugin to your plugin dir.

Python Turtle, draw text with on screen with larger font

To add bold, italic and underline, just add the following to the font argument:

font=("Arial", 8, 'normal', 'bold', 'italic', 'underline')

How to check if an array element exists?

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

Copy map values to vector in STL

Old question, new answer. With C++11 we have the fancy new for loop:

for (const auto &s : schemas)
   names.push_back(s.first);

where schemas is a std::map and names is an std::vector.

This populates the array (names) with keys from the map (schemas); change s.first to s.second to get an array of values.

How to calculate a time difference in C++

Just a side note: if you're running on Windows, and you really really need precision, you can use QueryPerformanceCounter. It gives you time in (potentially) nanoseconds.

HTML / CSS Popup div on text click

For the sake of completeness, what you are trying to create is a "modal window".

Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.

I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/

Can't execute jar- file: "no main manifest attribute"

For me, none of the answers really helped - I had the manifest file in correct place, containing the Main-Class and everything. What tripped me over was this:

Warning: The text file from which you are creating the manifest must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

(source). Adding a newline at the end of the manifest fixed it.

Change working directory in my current shell context when running Node script

What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.

When you are on the commandline and you go to execute your Node script, your current process (bash, zsh, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.

There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &) and as it ran, it started changing your working directory or overriding your PATH. That would be a nightmare.

If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile:

do_cool_thing() {
  cd "/Users"
  echo "Hey, I'm in $PWD"
}

and then this cool thing is doable:

$ pwd
/Users/spike
$ do_cool_thing
Hey, I'm in /Users
$ pwd
/Users

If you need to do more complex things in addition, you could always call out to your nodejs script from that function.

This is the only way you can accomplish what you're trying to do.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

Convert stdClass object to array in PHP

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text

Centering a canvas

As to the CSS suggestion:

#myCanvas { 
 width: 100%;
 height: 100%;
}

By the standard, CSS does not size the canvas coordinate system, it scales the content. In Chrome, the CSS mentioned will scale the canvas up or down to fit the browser's layout. In the typical case where the coordinate system is smaller than the browser's dimensions in pixels, this effectively lowers the resolution of your drawing. It most likely results in non-proportional drawing as well.

File upload progress bar with jQuery

Kathir's answer is great as he solves that problem with just jQuery. I just wanted to make some additions to his answer to work his code with a beautiful HTML progress bar:

$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();

xhr.upload.addEventListener("progress", function(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    percentComplete = parseInt(percentComplete * 100);

    $('.progress-bar').width(percentComplete+'%');
    $('.progress-bar').html(percentComplete+'%');

  }
}, false);

return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});

Here is the HTML code of progress bar, I used Bootstrap 3 for the progress bar element:

<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped 
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>

Better naming in Tuple classes than "Item1", "Item2"

Just to add to @MichaelMocko answer. Tuples have couple of gotchas at the moment:

You can't use them in EF expression trees

Example:

public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        // Selecting as Tuple
        .Select(person => (person.Name, person.Surname))
        .First();
}

This will fail to compile with "An expression tree may not contain a tuple literal" error. Unfortunately, the expression trees API wasn't expanded with support for tuples when these were added to the language.

Track (and upvote) this issue for the updates: https://github.com/dotnet/roslyn/issues/12897

To get around the problem, you can cast it to anonymous type first and then convert the value to tuple:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => new { person.Name, person.Surname })
        .ToList()
        .Select(person => (person.Name, person.Surname))
        .First();
}

Another option is to use ValueTuple.Create:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname))
        .First();
}

References:

You can't deconstruct them in lambdas

There's a proposal to add the support: https://github.com/dotnet/csharplang/issues/258

Example:

public static IQueryable<(string name, string surname)> GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname));
}

// This won't work
ctx.GetPersonName(id).Select((name, surname) => { return name + surname; })

// But this will
ctx.GetPersonName(id).Select(t => { return t.name + t.surname; })

References:

They won't serialize nicely

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main() {
        var me = (age: 21, favoriteFood: "Custard");
        string json = JsonConvert.SerializeObject(me);

        // Will output {"Item1":21,"Item2":"Custard"}
        Console.WriteLine(json); 
    }
}

Tuple field names are only available at compile time and are completely wiped out at runtime.

References:

Running a Python script from PHP

I recommend using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 

Stratified Train/Test-split in scikit-learn

Here's an example for continuous/regression data (until this issue on GitHub is resolved).

min = np.amin(y)
max = np.amax(y)

# 5 bins may be too few for larger datasets.
bins     = np.linspace(start=min, stop=max, num=5)
y_binned = np.digitize(y, bins, right=True)

X_train, X_test, y_train, y_test = train_test_split(
    X, 
    y, 
    stratify=y_binned
)
  • Where start is min and stop is max of your continuous target.
  • If you don't set right=True then it will more or less make your max value a separate bin and your split will always fail because too few samples will be in that extra bin.

Python 3: ImportError "No Module named Setuptools"

Your setup.py file needs setuptools. Some Python packages used to use distutils for distribution, but most now use setuptools, a more complete package. Here is a question about the differences between them.

To install setuptools on Debian:

sudo apt-get install python3-setuptools

For an older version of Python (Python 2.x):

sudo apt-get install python-setuptools

How do I create a batch file timer to execute / call another batch throughout the day

I would use the scheduler (control panel) rather than a cmd line or other application.

Control Panel -> Scheduled tasks

What should my Objective-C singleton look like?

The accepted answer, although it compiles, is incorrect.

+ (MySingleton*)sharedInstance
{
    @synchronized(self)  <-------- self does not exist at class scope
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

Per Apple documentation:

... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.

Even if using self works, it shouldn't and this looks like a copy and paste mistake to me. The correct implementation for a class factory method would be:

+ (MySingleton*)getInstance
{
    @synchronized([MySingleton class]) 
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

What is an IIS application pool?

The application Pools element contains configuration settings for all application pools running on your IIS. An application pool defines a group of one or more worker processes, configured with common settings that serve requests to one or more applications that are assigned to that application pool.

Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer.

Process boundaries separate each worker process; therefore, application problems in one application pool do not affect Web sites or applications in other application pools. Application pools significantly increase both the reliability and manageability of your Web infrastructure.

Div with margin-left and width:100% overflowing on the right side

Just remove the width from both divs.

A div is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.

I have added an example with a textarea on jsfiddle.

Updated example with an input.

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

How to scroll table's "tbody" independent of "thead"?

The missing part is:

thead, tbody {
    display: block;
}

Demo

How to get the first item from an associative PHP array?

We can do $first = reset($array);

Instead of

reset($array);
$first = current($array);

As reset()

returns the first element of the array after reset;

Highest Salary in each department

If you just want to get the highest salary from that table, by department:

SELECT MAX(Salary) FROM TableName GROUP BY DeptID

Multiple Java versions running concurrently under Windows

Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like

java ...

This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable JAVA6HOME with the value C:\java\java6 (if Java 6 is installed in this directory) and change the batch file calling

%JAVA6HOME%\bin\java ...

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

No converter found capable of converting from type to type

Simple Solution::

use {nativeQuery=true} in your query.

for example

  @Query(value = "select d.id,d.name,d.breed,d.origin from Dog d",nativeQuery = true)
        
    List<Dog> findALL();

Warning as error - How to get rid of these

For Visual Studio Express 2013 to get rid of these problem you have to do the following.

Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General

In right side select

Treat Warning As Errors NO

and

SDL Checks NO

SqlDataAdapter vs SqlDataReader

Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.

Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.

Write string to text file and ensure it always overwrites the existing content.

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

from list of integers, get number closest to a given value

Expanding upon Gustavo Lima's answer. The same thing can be done without creating an entirely new list. The values in the list can be replaced with the differentials as the FOR loop progresses.

def f_ClosestVal(v_List, v_Number):
"""Takes an unsorted LIST of INTs and RETURNS INDEX of value closest to an INT"""
for _index, i in enumerate(v_List):
    v_List[_index] = abs(v_Number - i)
return v_List.index(min(v_List))

myList = [1, 88, 44, 4, 4, -2, 3]
v_Num = 5
print(f_ClosestVal(myList, v_Num)) ## Gives "3," the index of the first "4" in the list.

Using "If cell contains #N/A" as a formula condition.

"N/A" is not a string it is an error, try this:

=if(ISNA(A1),C1)

you have to place this fomula in cell B1 so it will get the value of your formula

UICollectionView Set number of columns

Here is the working code for Swift 3 or above, to have a two-columns layout :

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    
    let nbCol = 2
    
    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(nbCol - 1))
    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(nbCol))
    return CGSize(width: size, height: size)
}

Feel free to change "nbCol" to your desired number of columns.

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

Smooth GPS data

One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing

For example

Smoothing at five sample points A, B, C, D, E

ATOTAL = SUM of distances AB AC AD AE

BTOTAL = SUM of distances AB BC BD BE

CTOTAL = SUM of distances AC BC CD CE

DTOTAL = SUM of distances DA DB DC DE

ETOTAL = SUM of distances EA EB EC DE

If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }

This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.

How can I view an object with an alert()

You should really use Firebug or Webkit's console for debugging. Then you can just do console.debug(product); and examine the object.

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

width:auto for <input> fields

An <input>'s width is generated from its size attribute. The default size is what's driving the auto width.

You could try width:100% as illustrated in my example below.

Doesn't fill width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:auto' />
</form>

Fills width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:100%' />
</form>

Smaller size, smaller width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input size='5' />
</form>

UPDATE

Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)

<div style='padding:30px;width:200px;background:red'>
  <form action='' method='post' style='width:200px;background:blue;padding:3px'>
    <input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
    <br /><br />
    <input size='' style='width:100%' />
  </form>
</div>

Checking if an object is null in C#

As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...

catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.

Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.

Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.

Should I call Close() or Dispose() for stream objects?

For what it's worth, the source code for Stream.Close explains why there are two methods:

// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable.  However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern.  We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.

In short, Close is only there because it predates Dispose, and it can't be deleted for compatibility reasons.

Accessing dict keys like an attribute?

You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope help you:

class Map(dict):
    """
    Example:
    m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
    """
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.iteritems():
                    self[k] = v

        if kwargs:
            for k, v in kwargs.iteritems():
                self[k] = v

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]

Usage examples:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']

Access elements in json object like an array

I found a straight forward way of solving this, with the use of JSON.parse.

Let's assume the json below is inside the variable jsontext.

[
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  ["57.586174","16.521841"], ["57.893162","16.406090"]
]

The solution is this:

var parsedData = JSON.parse(jsontext);

Now I can access the elements the following way:

var cities = parsedData[0];

Do while loop in SQL Server 2008

I seem to recall reading this article more than once, and the answer is only close to what I need.

Usually when I think I'm going to need a DO WHILE in T-SQL it's because I'm iterating a cursor, and I'm looking largely for optimal clarity (vs. optimal speed). In T-SQL that seems to fit a WHILE TRUE / IF BREAK.

If that's the scenario that brought you here, this snippet may save you a moment. Otherwise, welcome back, me. Now I can be certain I've been here more than once. :)

DECLARE Id INT, @Title VARCHAR(50)
DECLARE Iterator CURSOR FORWARD_ONLY FOR
SELECT Id, Title FROM dbo.SourceTable
OPEN Iterator
WHILE 1=1 BEGIN
    FETCH NEXT FROM @InputTable INTO @Id, @Title
    IF @@FETCH_STATUS < 0 BREAK
    PRINT 'Do something with ' + @Title
END
CLOSE Iterator
DEALLOCATE Iterator

Unfortunately, T-SQL doesn't seem to offer a cleaner way to singly-define the loop operation, than this infinite loop.

Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

How to set a JVM TimeZone Properly

On windows 7 and for JDK6, I had to add -Duser.timezone="Europe/Sofia" to the JAVA_TOOL_OPTIONS system variable located under "My computer=>Properties=>Advanced System Settings=>Environment Variables".

If you already have some other property set for JAVA_TOOL_OPTIONS just append a space and then insert your property string.

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

Pylint "unresolved import" error in Visual Studio Code

In case of a Pylint error, install the following

pipenv install pylint-django

Then create a file, .pylintrc, in the root folder and write the following

load-plugins=pylint-django

How do you unit test private methods?

Declare them internal, and then use the InternalsVisibleToAttribute to allow your unit test assembly to see them.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

import sys
userinput = sys.stdin.readline()
betAmount = int(userinput)

print betAmount

This works on my system. I checked int('23\n') would result in 23.

How to implement static class member functions in *.cpp file?

Try this:

header.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};

class.cxx:

#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}

How do I escape a reserved word in Oracle?

From a quick search, Oracle appears to use double quotes (", eg "table") and apparently requires the correct case—whereas, for anyone interested, MySQL defaults to using backticks (`) except when set to use double quotes for compatibility.

Return Index of an Element in an Array Excel VBA

Here's another way:

Option Explicit

' Just a little test stub. 
Sub Tester()

    Dim pList(500) As Integer
    Dim i As Integer

    For i = 0 To UBound(pList)

        pList(i) = 500 - i

    Next i

    MsgBox "Value 18 is at array position " & FindInArray(pList, 18) & "."
    MsgBox "Value 217 is at array position " & FindInArray(pList, 217) & "."
    MsgBox "Value 1001 is at array position " & FindInArray(pList, 1001) & "."

End Sub

Function FindInArray(pList() As Integer, value As Integer)

    Dim i As Integer
    Dim FoundValueLocation As Integer

    FoundValueLocation = -1

    For i = 0 To UBound(pList)

        If pList(i) = value Then

            FoundValueLocation = i
            Exit For

        End If

    Next i

    FindInArray = FoundValueLocation

End Function

How to change my Git username in terminal?

If you have created a new Github account and you want to push commits with your new account instead of your previous account then the .gitconfig must be updated, otherwise, you will push with the already owned Github account to the new account.

In order to fix this, you have to navigate to your home directory and open the .gitconfig with an editor. The editor can be vim, notepad++, or even notepad.

Once you have the .gitconfig open, just modify the "name" with your new Github account username that you want to push with.

How to encode URL to avoid special characters in Java?

Here is my solution which is pretty easy:

Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)

String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
    review = URLEncoder.encode(review,"utf-8");
    review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile

<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />

If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).

For info, you can find the assembly and .NET version(s) from MSDN

Splitting applicationContext to multiple files

@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.

Otherwise the @kosoant configuration is fine.

Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :

In web.xml:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-context.xml</param-value>
</context-param>

Then, your application-context.xml will contain: <import resource="foo-services.xml"/> these import statements to load various application context files and put into main application-context.xml.

Thanks and hope this helps.

Print a div using javascript in angularJS single page application

I done this way:

$scope.printDiv = function (div) {
  var docHead = document.head.outerHTML;
  var printContents = document.getElementById(div).outerHTML;
  var winAttr = "location=yes, statusbar=no, menubar=no, titlebar=no, toolbar=no,dependent=no, width=865, height=600, resizable=yes, screenX=200, screenY=200, personalbar=no, scrollbars=yes";

  var newWin = window.open("", "_blank", winAttr);
  var writeDoc = newWin.document;
  writeDoc.open();
  writeDoc.write('<!doctype html><html>' + docHead + '<body onLoad="window.print()">' + printContents + '</body></html>');
  writeDoc.close();
  newWin.focus();
}

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

Jquery sortable 'change' event element position

UPDATED: 26/08/2016 to use the latest jquery and jquery ui version plus bootstrap to style it.

$(function() {
    $('#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        change: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var index = ui.placeholder.index();
            if (start_pos < index) {
                $('#sortable li:nth-child(' + index + ')').addClass('highlights');
            } else {
                $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
            }
        },
        update: function(event, ui) {
            $('#sortable li').removeClass('highlights');
        }
    });
});

array.select() in javascript

There is Array.filter():

var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });

// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);

Note that Array.filter() is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).

Nov 2020 Update: Array.filter is now supported across all major browsers.

How can I include a YAML file inside another?

I make some examples for your reference.

import yaml

main_yaml = """
Package:
 - !include _shape_yaml    
 - !include _path_yaml
"""

_shape_yaml = """
# Define
Rectangle: &id_Rectangle
    name: Rectangle
    width: &Rectangle_width 20
    height: &Rectangle_height 10
    area: !product [*Rectangle_width, *Rectangle_height]

Circle: &id_Circle
    name: Circle
    radius: &Circle_radius 5
    area: !product [*Circle_radius, *Circle_radius, pi]

# Setting
Shape:
    property: *id_Rectangle
    color: red
"""

_path_yaml = """
# Define
Root: &BASE /path/src/

Paths: 
    a: &id_path_a !join [*BASE, a]
    b: &id_path_b !join [*BASE, b]

# Setting
Path:
    input_file: *id_path_a
"""


# define custom tag handler
def yaml_import(loader, node):
    other_yaml_file = loader.construct_scalar(node)
    return yaml.load(eval(other_yaml_file), Loader=yaml.SafeLoader)


def yaml_product(loader, node):
    import math
    list_data = loader.construct_sequence(node)
    result = 1
    pi = math.pi
    for val in list_data:
        result *= eval(val) if isinstance(val, str) else val
    return result


def yaml_join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])


def yaml_ref(loader, node):
    ref = loader.construct_sequence(node)
    return ref[0]


def yaml_dict_ref(loader: yaml.loader.SafeLoader, node):
    dict_data, key, const_value = loader.construct_sequence(node)
    return dict_data[key] + str(const_value)


def main():
    # register the tag handler
    yaml.SafeLoader.add_constructor(tag='!include', constructor=yaml_import)
    yaml.SafeLoader.add_constructor(tag='!product', constructor=yaml_product)
    yaml.SafeLoader.add_constructor(tag='!join', constructor=yaml_join)
    yaml.SafeLoader.add_constructor(tag='!ref', constructor=yaml_ref)
    yaml.SafeLoader.add_constructor(tag='!dict_ref', constructor=yaml_dict_ref)

    config = yaml.load(main_yaml, Loader=yaml.SafeLoader)

    pk_shape, pk_path = config['Package']
    pk_shape, pk_path = pk_shape['Shape'], pk_path['Path']
    print(f"shape name: {pk_shape['property']['name']}")
    print(f"shape area: {pk_shape['property']['area']}")
    print(f"shape color: {pk_shape['color']}")

    print(f"input file: {pk_path['input_file']}")


if __name__ == '__main__':
    main()

output

shape name: Rectangle
shape area: 200
shape color: red
input file: /path/src/a

Update 2

and you can combine it, like this

# xxx.yaml
CREATE_FONT_PICTURE:
  PROJECTS:
    SUNG: &id_SUNG
      name: SUNG
      work_dir: SUNG
      output_dir: temp
      font_pixel: 24


  DEFINE: &id_define !ref [*id_SUNG]  # you can use config['CREATE_FONT_PICTURE']['DEFINE'][name, work_dir, ... font_pixel]
  AUTO_INIT:
    basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # SUNG30

# ? This is not correct.
# basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # It will build by Deep-level. id_define is Deep-level: 2. So you must put it after 2. otherwise, it can't refer to the correct value.

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You need to do this in transaction to ensure two simultaneous clients won't insert same fieldValue twice:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
    DECLARE @id AS INT
    SELECT @id = tableId FROM table WHERE fieldValue=@newValue
    IF @id IS NULL
    BEGIN
       INSERT INTO table (fieldValue) VALUES (@newValue)
       SELECT @id = SCOPE_IDENTITY()
    END
    SELECT @id
COMMIT TRANSACTION

you can also use Double-checked locking to reduce locking overhead

DECLARE @id AS INT
SELECT @id = tableID FROM table (NOLOCK) WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    BEGIN TRANSACTION
        SELECT @id = tableID FROM table WHERE fieldValue=@newValue
        IF @id IS NULL
        BEGIN
           INSERT INTO table (fieldValue) VALUES (@newValue)
           SELECT @id = SCOPE_IDENTITY()
        END
    COMMIT TRANSACTION
END
SELECT @id

As for why ISOLATION LEVEL SERIALIZABLE is necessary, when you are inside a serializable transaction, the first SELECT that hits the table creates a range lock covering the place where the record should be, so nobody else can insert the same record until this transaction ends.

Without ISOLATION LEVEL SERIALIZABLE, the default isolation level (READ COMMITTED) would not lock the table at read time, so between SELECT and UPDATE, somebody would still be able to insert. Transactions with READ COMMITTED isolation level do not cause SELECT to lock. Transactions with REPEATABLE READS lock the record (if found) but not the gap.

How to convert from int to string in objective c: example code

Dot grammar maybe more swift!

@(intValueDemo).stringValue 

for example

int intValueDemo  = 1;
//or
NSInteger intValueDemo = 1;

//So you can use dot grammar 
NSLog(@"%@",@(intValueDemo).stringValue);

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

Laravel csrf token mismatch for ajax POST Request

I just added headers: in ajax call:

  headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

in view:

<div id = 'msg'>
     This message will be replaced using Ajax. Click the button to replace the message.
</div>

{{ Form::submit('Change', array('id' => 'ajax')) }}

ajax function:

<script>
 $(document).ready(function() {
    $(document).on('click', '#ajax', function () {
      $.ajax({
         type:'POST',
         url:'/ajax',
         headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
         success:function(data){
            $("#msg").html(data.msg);
         }
      });
    });
});
</script>

in controller:

public function call(){
    $msg = "This is a simple message.";
    return response()->json(array('msg'=> $msg), 200);
}

in routes.php

Route::post('ajax', 'AjaxController@call');

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

How do I fix the indentation of an entire file in Vi?

You can use tidy application/utility to indent HTML & XML files and it works pretty well in indenting those files.

Prettify an XML file

:!tidy -mi -xml %

Prettify an HTML file

:!tidy -mi -html %

How to access host port from docker container

I've explored the various solution and I find this the least hacky solution:

  1. Define a static IP address for the bridge gateway IP.
  2. Add the gateway IP as an extra entry in the extra_hosts directive.

The only downside is if you have multiple networks or projects doing this, you have to ensure that their IP address range do not conflict.

Here is a Docker Compose example:

version: '2.3'

services:
  redis:
    image: "redis"
    extra_hosts:
      - "dockerhost:172.20.0.1"

networks:
  default:
    ipam:
      driver: default
      config:
      - subnet: 172.20.0.0/16
        gateway: 172.20.0.1

You can then access ports on the host from inside the container using the hostname "dockerhost".

New lines (\r\n) are not working in email body

"\n\r" produces 2 new lines while "\n","\r" & "\r\n" produce single lines if, in the Header, you use content-type: text/plain.

Beware: If you do the Following php code:

    $message='ab<br>cd<br>e<br>f';
print $message.'<br><br>';
    $message=str_replace('<br>',"\r\n",$message);
print $message;

you get the following in the Windows browser:

ab
cd
e
f

ab cd e f

and with content-type: text/plain you get the following in an email output;

ab
cd
e
f

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is an application framework which deals with IOC (Inversion of Control).

Struts 2 is a web application MVC framework which deals with actions.

Hibernate is an ORM (Object-Relational Mapping) that deals with persistent data.

Get list from pandas DataFrame column headers

There is a built in method which is the most performant:

my_dataframe.columns.values.tolist()

.columns returns an Index, .columns.values returns an array and this has a helper function .tolist to return a list.

If performance is not as important to you, Index objects define a .tolist() method that you can call directly:

my_dataframe.columns.tolist()

The difference in performance is obvious:

%timeit df.columns.tolist()
16.7 µs ± 317 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit df.columns.values.tolist()
1.24 µs ± 12.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

For those who hate typing, you can just call list on df, as so:

list(df)

Edit line thickness of CSS 'underline' attribute

Recently I had to deal with FF which underlines were too thick and too far from the text in FF, and found a better way to deal with it using a pair of box-shadows:

.custom-underline{
    box-shadow: inset 0 0px 0 white, inset 0 -1px 0 black
}

First shadow is put on top of the second one and that's how you can control the second one by varying the 'px' value of both.

Plus: various colors, thickness and underline position

Minus: can not use on non-solid backgrounds

Here I made couple of examples: http://jsfiddle.net/xsL6rktx/

How to open the Chrome Developer Tools in a new window?

As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:

enter image description here

Select the icon on the left to open the Chrome Developer Tools in a new window: multiple windows icon


Previously

Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.

enter image description here

Note: A "press" is not enough in that state.

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Make sure you have enough space left in /var. If Mysql demon is not able to write additional info to the drive the mysql server won't start and it leads to the error Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Consider using

expire_logs_days = 10
max_binlog_size = 100M

This will help you keep disk usage down.

Randomize numbers with jQuery?

function rollDice(){
   return (Math.floor(Math.random()*6)+1);
}

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.

grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:

grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

Plotting of 1-dimensional Gaussian distribution function

With the excellent matplotlib and numpy packages

from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

will produce something like plot showing one-dimensional gaussians produced by matplotlib

IIS: Display all sites and bindings in PowerShell

If you just want to list all the sites (ie. to find a binding)

Change the working directory to "C:\Windows\system32\inetsrv"

cd c:\Windows\system32\inetsrv

Next run "appcmd list sites" (plural) and output to a file. e.g c:\IISSiteBindings.txt

appcmd list sites > c:\IISSiteBindings.txt

Now open with notepad from your command prompt.

notepad c:\IISSiteBindings.txt