Programs & Examples On #Associative table

Regex to match string containing two names in any order

You can do checks using lookarounds:

^(?=.*\bjack\b)(?=.*\bjames\b).*$

Test it.

This approach has the advantage that you can easily specify multiple conditions.

^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$

What is the best way to implement "remember me" for a website?

Investigating persistent sessions myself I have found that it's simply not worth the security risk. Use it if you absolutely have to, but you should consider such a session only weakly authenticated and force a new login for anything that could be of value to an attacker.

The reason being of course is that your cookies containing your persistent session are so easily stolen.

4 ways to steal your cookies (from a comment by Jens Roland on the page @splattne based his answer on):

  1. By intercepting it over an unsecure line (packet sniffing / session hijacking)
  2. By directly accessing the user's browser (via either malware or physical access to the box)
  3. By reading it from the server database (probably SQL Injection, but could be anything)
  4. By an XSS hack (or similar client-side exploit)

ExpressJS - throw er Unhandled error event

events.js:183 throw er; // Unhandled 'error' event

I also got the same kind of problem and tried many ways but finally got this, this works well:

npm install [email protected] --save-dev --save-exact

Refer to this link for more clarifications https://github.com/ionic-team/ionic-cli/issues/2922

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How to change or add theme to Android Studio?

  • Go to File > Settings,
  • now under IDE settings click on appearance and select the theme of your choice from the dropdown.
  • you can also install themes, they are the jar files by
  • File > Import Settings, select the file or your choice and select ok a pop up to restart the studio will open up click yes and studio will restart and your theme will be applied.

How to change context root of a dynamic web project in Eclipse?

After changing the context root in project properties you have to remove your web application from Tomcat (using Add and Remove... on the context menu of the server), redeploy, then re-add your application and redeploy. It worked for me.

If you are struck you have another choice: select the Tomcat server in the Servers view. Double clicking on that server (or selecting Open in the context menu) brings a multipage editor where there is a Modules page. Here you can change the root context of your module (called Path on this page).

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

How to use cURL to send Cookies?

This worked for me:

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/

I could see the value in backend using

print request.cookies

What are the ways to sum matrix elements in MATLAB?

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

Is there a simple JavaScript slider?

Here is a simple slider object for easy to use

pagecolumn_webparts_sliders

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

upstream sent too big header while reading response header from upstream

If you're using Symfony framework: Before messing with Nginx config, try to disable ChromePHP first.

1 - Open app/config/config_dev.yml

2 - Comment these lines:

#chromephp:
    #type:   chromephp
    #level:  info

ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.

Source: https://github.com/symfony/symfony/issues/8413#issuecomment-20412848

How to get duplicate items from a list using LINQ?

All mentioned solutions until now perform a GroupBy. Even if I only need the first Duplicate all elements of the collections are enumerated at least once.

The following extension function stops enumerating as soon as a duplicate has been found. It continues if a next duplicate is requested.

As always in LINQ there are two versions, one with IEqualityComparer and one without it.

public static IEnumerable<TSource> ExtractDuplicates(this IEnumerable<TSource> source)
{
    return source.ExtractDuplicates(null);
}
public static IEnumerable<TSource> ExtractDuplicates(this IEnumerable<TSource source,
    IEqualityComparer<TSource> comparer);
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (comparer == null)
        comparer = EqualityCompare<TSource>.Default;

    HashSet<TSource> foundElements = new HashSet<TSource>(comparer);
    foreach (TSource sourceItem in source)
    {
        if (!foundElements.Contains(sourceItem))
        {   // we've not seen this sourceItem before. Add to the foundElements
            foundElements.Add(sourceItem);
        }
        else
        {   // we've seen this item before. It is a duplicate!
            yield return sourceItem;
        }
    }
}

Usage:

IEnumerable<MyClass> myObjects = ...

// check if has duplicates:
bool hasDuplicates = myObjects.ExtractDuplicates().Any();

// or find the first three duplicates:
IEnumerable<MyClass> first3Duplicates = myObjects.ExtractDuplicates().Take(3)

// or find the first 5 duplicates that have a Name = "MyName"
IEnumerable<MyClass> myNameDuplicates = myObjects.ExtractDuplicates()
    .Where(duplicate => duplicate.Name == "MyName")
    .Take(5);

For all these linq statements the collection is only parsed until the requested items are found. The rest of the sequence is not interpreted.

IMHO that is an efficiency boost to consider.

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

Android Spinner: Get the selected item change event

spinner.setOnItemSelectedListener(
            new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {

                    // TODO Auto-generated method stub
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub

                }
                //add some code here
            }
        );

Check difference in seconds between two times

This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):

var seconds = System.Math.Abs((date1 - date2).TotalSeconds);

What's the difference between faking, mocking, and stubbing?

To illustrate the usage of stubs and mocks, I would like to also include an example based on Roy Osherove's "The Art of Unit Testing".

Imagine, we have a LogAnalyzer application which has the sole functionality of printing logs. It not only needs to talk to a web service, but if the web service throws an error, LogAnalyzer has to log the error to a different external dependency, sending it by email to the web service administrator.

Here’s the logic we’d like to test inside LogAnalyzer:

if(fileName.Length<8)
{
 try
  {
    service.LogError("Filename too short:" + fileName);
  }
 catch (Exception e)
  {
    email.SendEmail("a","subject",e.Message);
  }
}

How do you test that LogAnalyzer calls the email service correctly when the web service throws an exception? Here are the questions we’re faced with:

  • How can we replace the web service?

  • How can we simulate an exception from the web service so that we can test the call to the email service?

  • How will we know that the email service was called correctly or at all?

We can deal with the first two questions by using a stub for the web service. To solve the third problem, we can use a mock object for the email service.

A fake is a generic term that can be used to describe either a stub or a mock.In our test, we’ll have two fakes. One will be the email service mock, which we’ll use to verify that the correct parameters were sent to the email service. The other will be a stub that we’ll use to simulate an exception thrown from the web service. It’s a stub because we won’t be using the web service fake to verify the test result, only to make sure the test runs correctly. The email service is a mock because we’ll assert against it that it was called correctly.

[TestFixture]
public class LogAnalyzer2Tests
{
[Test]
 public void Analyze_WebServiceThrows_SendsEmail()
 {
   StubService stubService = new StubService();
   stubService.ToThrow= new Exception("fake exception");
   MockEmailService mockEmail = new MockEmailService();

   LogAnalyzer2 log = new LogAnalyzer2();
   log.Service = stubService
   log.Email=mockEmail;
   string tooShortFileName="abc.ext";
   log.Analyze(tooShortFileName);

   Assert.AreEqual("a",mockEmail.To); //MOCKING USED
   Assert.AreEqual("fake exception",mockEmail.Body); //MOCKING USED
   Assert.AreEqual("subject",mockEmail.Subject);
 }
}

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

How to check Django version

If you have pip, you can also do a

pip freeze
and it will show your all component version including Django .

You can pipe it through grep to get just the Django version. That is,

josh@villaroyale:~/code/djangosite$ pip freeze | grep Django
Django==1.4.3

How do I work with a git repository within another repository?

Consider using subtree instead of submodules, it will make your repo users life much easier. You may find more detailed guide in Pro Git book.

Printing with "\t" (tabs) does not result in aligned columns

In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -

public String rpad(String inStr, int finalLength)
{
    return (inStr + "                          " // typically a sufficient length spaces string.
        ).substring(0, finalLength);
}

similarly you can have a lpad() as well

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How can I get the day of a specific date with PHP

$date = strtotime('2016-2-3');
$date = date('l', $date);
var_dump($date)

(i added format 'l' so it will return full name of day)

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

Access Enum value using EL with JSTL

So to get my problem fully resolved I needed to do the following:

<% pageContext.setAttribute("old", Status.OLD); %>

Then I was able to do:

<c:when test="${someModel.status == old}"/>...</c:when>

which worked as expected.

How to refer environment variable in POM.xml?

Can't we use

<properties>
    <my.variable>${env.MY_VARIABLE}</my.variable>
</properties>

Package php5 have no installation candidate (Ubuntu 16.04)

Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.

Mine PHP version is 7.0, so i tried the below command.

apt-get install php-pgsql

Remember to restart Apache.

/etc/init.d/apache2 restart

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

Soft hyphen in HTML (<wbr> vs. &shy;)

Feb 2015 summary (partially updated Nov 2017)

They all perform pretty well, &#173; edges it as Google can still index of words containing it.

  • In browsers: &shy; and &#173; both display as expected in major browsers (even old IE!). <wbr> isn't supported in recent versions of IE (10 or 11) and doesn't work properly in Edge.
  • When copied and pasted from browsers: (tested 2015) as expected for &shy; and &#173; for Chrome and Firefox on Mac, on Windows (10), it keeps the characters and pastes hard hyphens into Notepad and invisible soft hyphens into applications that support them. IE (win7) always pastes with hyphens, even in IE10, and Safari (Mac) copies in a way which pastes as hyphens in some applications (e.g. MS Word), but not others
  • Find on page works for &shy; and &#173; on all browsers except IE which only matches exact copied-and-pasted matches (even up to IE11)
  • Search engines: Google matches words containing &#173; with words typed normally. As of 2017 it appears to no longer match words containing &shy;. Yandex appers to be the same. Bing and Baidu seem to not match either.

Test it

For up-to-date live testing, here are some examples of unique words with soft hyphens.

  • &shy; - confumbabbl&shy;ication&shy;ism - confumbabbl­ication­ism
    • ..............................................................................................................confumbabbl­ication­ism
    • ..................................................................................................................confumbabbl­ication­ism

<wbr> - donfounbabbl<wbr>ication<wbr>ism. This site removes <wbr/> from output. Here's a jsbin.com snippet for testing.

  • &#173; - eonfulbabbl&#173;ication&#173;ism - eonfulbabbl­ication­ism
    • .................................................................................................................eonfulbabbl­ication­ism
    • ....................................................................................................................eonfulbabbl­ication­ism

Here they are with no shy hyphens (this is for copying and pasting into find-on-page testing; written in a way which won't break the search engine tests):

ZZZconfumbabblicationismZZZdonfounbabblicationismZZZeonfulbabblicationismZZZ

Display across browsers

Success: displaying as a normal word, except where it should break, when it breaks and hyphenates in the specified place.

Failure: displaying unusually, or failing to break in the intended place.

  • Chrome (40.0.2214.115, Mac): &shy; success, <wbr> success, &#173; success
  • Firefox (35.0.1, Mac): &shy; success, <wbr> success, &#173; success
  • Safari (6.1.2, Mac): &shy; success, <wbr> not tested yet, &#173; success
  • Edge (Windows 10): &shy; success, <wbr> fail (break but no hyphen), &#173; success
  • IE11 (Windows 10): &shy; success, <wbr> fail (no break), &#173; success
  • IE10 (Windows 10): &shy; success, <wbr> fail (no break), &#173; success
  • IE8 (Windows 7): erratic - sometimes, none of them work at all and they all just follow css word-wrap. Sometimes, they seem to all work. Not yet found any clear pattern as to why.
  • IE7 (Windows 7): &shy; success, <wbr> success, &#173; success

Copy-paste across browsers

Success: copying and pasting the whole word, unhyphenated. (tested on Mac pasting into browser search, MS Word 2011, and Sublime Text)

Failure: pasting with a hyphen, space, line break, or with junk characters.

  • Chrome (40.0.2214.115, Mac): &shy; success, <wbr> success, &#173; success
  • Firefox (35.0.1, Mac): &shy; success, <wbr> success, &#173; success
  • Safari (6.1.2, Mac): &shy; fail into MS Word (pastes all as hyphens), success in other applications <wbr> fail, &#173; fail into MS Word (pastes all as hyphens), success in other applications
  • IE10 (Win7): &shy; fail pastes all as hyphens, <wbr> fail, &#173; fail pastes all as hyphens
  • IE8 (Win7): &shy; fail pastes all as hyphens, <wbr> fail, &#173; fail pastes all as hyphens
  • IE7 (Win7): &shy; fail pastes all as hyphens, <wbr> fail, &#173; fail pastes all as hyphens

Search engine matching

Updated in November 2017. <wbr> not tested because StackOverflow's CMS stripped it out.

Success: searches on the whole, non-hyphenated word find this page.

Failure: search engines only find this page on searches for the broken segments of the words, or a word with hyphens.

  • Google: &shy; fails, &#173; succeeds
  • Bing: &shy; fails, &#173; fails
  • Baidu: &shy; fails, &#173; fails (can match fragments within longer strings but not the words on their own containing a &#173; or &shy;)
  • Yandex: &shy; fails, &#173; succeeds (though it's possible it's matching a string fragment like Baidu, not 100% sure)

Find on page across browsers

Success and failure as search engine matching.

  • Chrome (40.0.2214.115, Mac): &shy; success, <wbr> success, &#173; success
  • Firefox (35.0.1, Mac): &shy; success, <wbr> success, &#173; success
  • Safari (6.1.2, Mac): &shy; success, <wbr> success, &#173; success
  • IE10 (Win7): &shy; fail only matches when both contain shy hyphens, <wbr> success, &#173; fail only matches when both contain shy hyphens
  • IE8 (Win7): &shy; fail only matches when both contain shy hyphens, <wbr> success, &#173; fail only matches when both contain shy hyphens
  • IE7 (Win7): &shy; fail only matches when both contain shy hyphens, <wbr> success, &#173; fail only matches when both contain shy hyphens

How to know function return type and argument types?

For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?

Um... There is no "concise" description of this. It's complex. You've designed it to be complex. And it requires complex documentation in the docstring.

Sorry, but complexity is -- well -- complex.

What does "select count(1) from table_name" on any database tables mean?

SELECT COUNT(1) from <table name>

should do the exact same thing as

SELECT COUNT(*)  from <table name>

There may have been or still be some reasons why it would perform better than SELECT COUNT(*)on some database, but I would consider that a bug in the DB.

SELECT COUNT(col_name) from <table name>

however has a different meaning, as it counts only the rows with a non-null value for the given column.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

Composer update memory limit

How large is your aws server? If it only has 1gb of ram, setting the memory limit of 2gb in php.ini won't help.

If you can't/don't want to also increase the server side to get more RAM available, you can enable SWAP as well.

See here for how to enable swap. It enables 4gb, although I typically only do 1GB myself.

Source: Got from laracast site

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..

Happy Coding :)

Call of overloaded function is ambiguous

The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.

As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.

The easiest solution is to just cast the 0 to the right type.
Another option is to ensure the int overload is preferred, for example by making the other one a template:

class huge
{
 private:
  unsigned char data[BYTES];
 public:
  void setval(unsigned int);
  template <class T> void setval(const T *); // not implemented
  template <> void setval(const char*);
};

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

Remove or uninstall library previously added : cocoapods

None of these worked for me. I have pod version 1.5.3 and the correct method was to remove the pods that were not longer needed from the Podfile and then run:

pod update

This updates your Podfile.lock file from your Podfile, removes libraries that have been removed and updates all of your libraries.

Reading binary file and looping over each byte

Reading binary file in Python and looping over each byte

New in Python 3.5 is the pathlib module, which has a convenience method specifically to read in a file as bytes, allowing us to iterate over the bytes. I consider this a decent (if quick and dirty) answer:

import pathlib

for byte in pathlib.Path(path).read_bytes():
    print(byte)

Interesting that this is the only answer to mention pathlib.

In Python 2, you probably would do this (as Vinay Sajip also suggests):

with open(path, 'b') as file:
    for byte in file.read():
        print(byte)

In the case that the file may be too large to iterate over in-memory, you would chunk it, idiomatically, using the iter function with the callable, sentinel signature - the Python 2 version:

with open(path, 'b') as file:
    callable = lambda: file.read(1024)
    sentinel = bytes() # or b''
    for chunk in iter(callable, sentinel): 
        for byte in chunk:
            print(byte)

(Several other answers mention this, but few offer a sensible read size.)

Best practice for large files or buffered/interactive reading

Let's create a function to do this, including idiomatic uses of the standard library for Python 3.5+:

from pathlib import Path
from functools import partial
from io import DEFAULT_BUFFER_SIZE

def file_byte_iterator(path):
    """given a path, return an iterator over the file
    that lazily loads the file
    """
    path = Path(path)
    with path.open('rb') as file:
        reader = partial(file.read1, DEFAULT_BUFFER_SIZE)
        file_iterator = iter(reader, bytes())
        for chunk in file_iterator:
            yield from chunk

Note that we use file.read1. file.read blocks until it gets all the bytes requested of it or EOF. file.read1 allows us to avoid blocking, and it can return more quickly because of this. No other answers mention this as well.

Demonstration of best practice usage:

Let's make a file with a megabyte (actually mebibyte) of pseudorandom data:

import random
import pathlib
path = 'pseudorandom_bytes'
pathobj = pathlib.Path(path)

pathobj.write_bytes(
  bytes(random.randint(0, 255) for _ in range(2**20)))

Now let's iterate over it and materialize it in memory:

>>> l = list(file_byte_iterator(path))
>>> len(l)
1048576

We can inspect any part of the data, for example, the last 100 and first 100 bytes:

>>> l[-100:]
[208, 5, 156, 186, 58, 107, 24, 12, 75, 15, 1, 252, 216, 183, 235, 6, 136, 50, 222, 218, 7, 65, 234, 129, 240, 195, 165, 215, 245, 201, 222, 95, 87, 71, 232, 235, 36, 224, 190, 185, 12, 40, 131, 54, 79, 93, 210, 6, 154, 184, 82, 222, 80, 141, 117, 110, 254, 82, 29, 166, 91, 42, 232, 72, 231, 235, 33, 180, 238, 29, 61, 250, 38, 86, 120, 38, 49, 141, 17, 190, 191, 107, 95, 223, 222, 162, 116, 153, 232, 85, 100, 97, 41, 61, 219, 233, 237, 55, 246, 181]
>>> l[:100]
[28, 172, 79, 126, 36, 99, 103, 191, 146, 225, 24, 48, 113, 187, 48, 185, 31, 142, 216, 187, 27, 146, 215, 61, 111, 218, 171, 4, 160, 250, 110, 51, 128, 106, 3, 10, 116, 123, 128, 31, 73, 152, 58, 49, 184, 223, 17, 176, 166, 195, 6, 35, 206, 206, 39, 231, 89, 249, 21, 112, 168, 4, 88, 169, 215, 132, 255, 168, 129, 127, 60, 252, 244, 160, 80, 155, 246, 147, 234, 227, 157, 137, 101, 84, 115, 103, 77, 44, 84, 134, 140, 77, 224, 176, 242, 254, 171, 115, 193, 29]

Don't iterate by lines for binary files

Don't do the following - this pulls a chunk of arbitrary size until it gets to a newline character - too slow when the chunks are too small, and possibly too large as well:

    with open(path, 'rb') as file:
        for chunk in file: # text newline iteration - not for bytes
            yield from chunk

The above is only good for what are semantically human readable text files (like plain text, code, markup, markdown etc... essentially anything ascii, utf, latin, etc... encoded) that you should open without the 'b' flag.

dereferencing pointer to incomplete type

Outside of possible scenarios involving whole-program optimization, the code code generated for something like:

struct foo *bar;
struct foo *test(struct foo *whatever, int blah)
{
  return blah ? whatever: bar;
}

will be totally unaffected by what members struct foo might contain. Because make utilities will generally recompile any compilation unit in which the complete definition of a structure appears, even when such changes couldn't actually affect the code generated for them, it's common to omit complete structure definitions from compilation units that don't actually need them, and such omission is generally not worthy of a warning.

A compiler needs to have a complete structure or union definition to know how to handle declarations objects of the type with automatic or static duration, declarations of aggregates containing members of the type, or code which accesses members of the structure or union. If the compiler doesn't have the information needed to perform one of the above operations, it will have no choice but to squawk about it.

Incidentally, there's one more situation where the Standard would allow a compiler to require a complete union definition to be visible but would not require a diagnostic: if two structures start with a Common Initial Sequence, and a union type containing both is visible when the compiler is processing code that uses a pointer of one of the structure types to inspects a member of that Common Initial Sequence, the compiler is required to recognize that such code might be accessing the corresponding member of a structure of the other type. I don't know what compilers if any comply with the Standard when the complete union type is visible but not when it isn't [gcc is prone to generate non-conforming code in either case unless the -fno-strict-aliasing flag is used, in which case it will generate conforming code in both cases] but if one wants to write code that uses the CIS rule in such a fashion as to guarantee correct behavior on conforming compilers, one may need to ensure that complete union type definition is visible; failure to do so may result in a compiler silently generating bogus code.

Bootstrap: Open Another Modal in Modal

Update for 2019 -- Using Bootstrap 4

I found most of the answers seem to have a lot of unnecessary jQuery. To open a modal from another modal can be done simply by using the events that Bootstrap provides such as show.bs.modal. You may also want some CSS to handle the backdrop overlays. Here are the 3 open modal from another scenarios...

Open modal from another modal (keep 1st modal open)

<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>

<div class="modal" id="myModal">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Modal title</h4>    
              <button type="button" class="close" data-dismiss="modal">×</button>
            </div><div class="container"></div>
            <div class="modal-body">
              ...
              <a data-toggle="modal" href="#myModal2" class="btn btn-primary">Open modal2</a>
            </div>
            <div class="modal-footer">
              <a href="#" data-dismiss="modal" class="btn">Close</a>
            </div>
          </div>
        </div>
</div>
<div class="modal" id="myModal2" data-backdrop="static">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">2nd Modal title</h4>
              <button type="button" class="close" data-dismiss="modal">×</button>
            </div><div class="container"></div>
            <div class="modal-body">
              ..
            </div>
            <div class="modal-footer">
              <a href="#" data-dismiss="modal" class="btn">Close</a>
              <a href="#" class="btn btn-primary">Save changes</a>
            </div>
          </div>
        </div>
</div>

A potential issue in this case is that the backdrop from the 2nd modal hides the 1st modal. To prevent this, make the 2nd modal data-backdrop="static", and add some CSS to fix the z-indexes of the backdrops...

/* modal backdrop fix */
.modal:nth-of-type(even) {
    z-index: 1052 !important;
}
.modal-backdrop.show:nth-of-type(even) {
    z-index: 1051 !important;
}

https://www.codeply.com/go/NiFzSCukVl


Open modal from another modal (close 1st modal)

This is similar to the above scenario, but since we are closing the 1st modal when the 2nd is opened, there is no need for the backdrop CSS fix. A simple function that handles the 2nd modals show.bs.modal event closes the 1st modal.

$("#myModal2").on('show.bs.modal', function (e) {
    $("#myModal1").modal("hide");
});

https://codeply.com/go/ejaUJ4YANz


Open modal inside another modal

The last multiple modals scenario is opening the 2nd modal inside the 1st modal. In this case the markup for the 2nd is placed inside the 1st. No extra CSS or jQuery is needed.

<div class="modal" id="myModal1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Modal title</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>
            <div class="container"></div>
            <div class="modal-body">
                ...
                <a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal 2</a>
            </div>
            <div class="modal-footer">
                <a href="#" data-dismiss="modal" class="btn">Close</a>
            </div>
        </div>
    </div>

    <div class="modal" id="myModal2">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">2nd Modal title</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="container"></div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <a href="#" data-dismiss="modal" class="btn">Close</a>
                    <a href="#" class="btn btn-primary">Save changes</a>
                </div>
            </div>
        </div>
    </div>
</div>

https://codeply.com/go/iSbjqubiyn

Reading a file line by line in Go

In the code bellow, I read the interests from the CLI until the user hits enter and I'm using Readline:

interests := make([]string, 1)
r := bufio.NewReader(os.Stdin)
for true {
    fmt.Print("Give me an interest:")
    t, _, _ := r.ReadLine()
    interests = append(interests, string(t))
    if len(t) == 0 {
        break;
    }
}
fmt.Println(interests)

Set up a scheduled job?

I use celery to create my periodical tasks. First you need to install it as follows:

pip install django-celery

Don't forget to register django-celery in your settings and then you could do something like this:

from celery import task
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from celery.utils.log import get_task_logger
@periodic_task(run_every=crontab(minute="0", hour="23"))
def do_every_midnight():
 #your code

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Set cursor position on contentEditable <div>

I took Nico Burns's answer and made it using jQuery:

  • Generic: For every div contentEditable="true"
  • Shorter

You'll need jQuery 1.6 or higher:

savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
    var s = window.getSelection();
    var t = $('div[contenteditable="true"]').index(this);
    if (typeof(savedRanges[t]) === "undefined"){
        savedRanges[t]= new Range();
    } else if(s.rangeCount > 0) {
        s.removeAllRanges();
        s.addRange(savedRanges[t]);
    }
}).bind("mouseup keyup",function(){
    var t = $('div[contenteditable="true"]').index(this);
    savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
    if(!$(this).is(":focus")){
        e.stopPropagation();
        e.preventDefault();
        $(this).focus();
    }
});

_x000D_
_x000D_
savedRanges = new Object();_x000D_
$('div[contenteditable="true"]').focus(function(){_x000D_
    var s = window.getSelection();_x000D_
    var t = $('div[contenteditable="true"]').index(this);_x000D_
    if (typeof(savedRanges[t]) === "undefined"){_x000D_
        savedRanges[t]= new Range();_x000D_
    } else if(s.rangeCount > 0) {_x000D_
        s.removeAllRanges();_x000D_
        s.addRange(savedRanges[t]);_x000D_
    }_x000D_
}).bind("mouseup keyup",function(){_x000D_
    var t = $('div[contenteditable="true"]').index(this);_x000D_
    savedRanges[t] = window.getSelection().getRangeAt(0);_x000D_
}).on("mousedown click",function(e){_x000D_
    if(!$(this).is(":focus")){_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $(this).focus();_x000D_
    }_x000D_
});
_x000D_
div[contenteditable] {_x000D_
    padding: 1em;_x000D_
    font-family: Arial;_x000D_
    outline: 1px solid rgba(0,0,0,0.5);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>
_x000D_
_x000D_
_x000D_

How to instantiate, initialize and populate an array in TypeScript?

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

How do you give iframe 100% height

The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp

Finding three elements in an array whose sum is closest to a given number

Here is the program in java which is O(N^2)

import java.util.Stack;


public class GetTripletPair {

    /** Set a value for target sum */
    public static final int TARGET_SUM = 32;

    private Stack<Integer> stack = new Stack<Integer>();

    /** Store the sum of current elements stored in stack */
    private int sumInStack = 0;
    private int count =0 ;


    public void populateSubset(int[] data, int fromIndex, int endIndex) {

        /*
        * Check if sum of elements stored in Stack is equal to the expected
        * target sum.
        * 
        * If so, call print method to print the candidate satisfied result.
        */
        if (sumInStack == TARGET_SUM) {
            print(stack);
        }

        for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {

            if (sumInStack + data[currentIndex] <= TARGET_SUM) {
                ++count;
                stack.push(data[currentIndex]);
                sumInStack += data[currentIndex];

                /*
                * Make the currentIndex +1, and then use recursion to proceed
                * further.
                */
                populateSubset(data, currentIndex + 1, endIndex);
                --count;
                sumInStack -= (Integer) stack.pop();
            }else{
            return;
        }
        }
    }

    /**
    * Print satisfied result. i.e. 15 = 4+6+5
    */

    private void print(Stack<Integer> stack) {
        StringBuilder sb = new StringBuilder();
        sb.append(TARGET_SUM).append(" = ");
        for (Integer i : stack) {
            sb.append(i).append("+");
        }
        System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
    }

    private static final int[] DATA = {4,13,14,15,17};

    public static void main(String[] args) {
        GetAllSubsetByStack get = new GetAllSubsetByStack();
        get.populateSubset(DATA, 0, DATA.length);
    }
}

pip installing in global site-packages instead of virtualenv

The same problem. Python3.5 and pip 8.0.2 installed from Linux rpm's.

I did not find a primary cause and cannot give a proper answer. It looks like there are multiple possible causes.

However, I hope I can help with sharing my observation and a workaround.

  1. pyvenv with --system-site-packages

    • ./bin does not contain pip, pip is available from system site packages
    • packages are installed globally (BUG?)
  2. pyvenv without --system-site-packages

    • pip gets installed into ./bin, but it's a different version (from ensurepip)
    • packages are installed within the virtual environment (OK)

Obvious workaround for pyvenv with --system-site-packages:

  • create it without the --system-site-packages option
  • change include-system-site-packages = false to true in pyvenv.cfg file

how to display employee names starting with a and then b in sql

Oracle: Just felt to do it in different way. Disadvantage: It doesn't perform full index scan. But still gives the result and can use this in substring.

select employee_name 
from employees
where lpad(employee_name,1) ='A'
 OR lpad(employee_name,1) = 'B'
order by employee_name

We can use LEFT in SQL Server instead of lpad . Still suggest not a good idea to use this method.

Assets file project.assets.json not found. Run a NuGet package restore

To those with the same issue as me in Azure DevOps / VSTS environment encountering a similar message:

C:\Program Files\dotnet\sdk\2.2.104\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(208,5): Error NETSDK1004: Assets file '...\obj\project.assets.json' not found. Run a NuGet package restore to generate this file

Add /t:Restore to your MSBuild Arguments in Build Solution.

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

JavaScript Nested function

It's perfectly normal in Javascript (and many languages) to have functions inside functions.

Take the time to learn the language, don't use it on the basis that it's similar to what you already know. I'd suggest watching Douglas Crockford's series of YUI presentations on Javascript, with special focus on Act III: Function the Ultimate (link to video download, slides, and transcript)

Importing Maven project into Eclipse

Maven have a Eclipse plugin and Eclipse have a Maven plugin we are going to discus those things.when we using maven with those command line stuffs and etc when we are going through eclipse we don't want to that command line codes it have very much helpful, Maven and eclipse giving good integration ,they will work very well together thanks for that plugins

Step 1: Go to the maven project. Here my project is FirstApp.(Example my project is FirstApp)

There you can see one pom.xml file, now what we want is to generate an eclipse project using that pom.xml.

Step 2: Use mvn eclipse:eclipse command

Step 3: Verify the project

after execution of this command notice that two new files have been created

Note:- both these files are created for Eclipse. When you open those files you will notice a "M2_REPO" class variable is generate. You want to add that class path in eclipse, otherwise eclipse will show a error.

Step 4: Importing eclipse project

File -> Import -> General -> Existing Projects in Workspace -> Select root directory -> Done

More details here

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

Remove all newlines from inside a string

As mentioned by @john, the most robust answer is:

string = "a\nb\rv"
new_string = " ".join(string.splitlines())

How to kill all processes with a given partial name?

This is the way:

kill -9 $(pgrep -d' ' -f chrome)

Java: Clear the console

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

IE6/IE7 css border on select element

IE < 8 does not render the dropdown list itself it just uses the windows control which cannot be styled this way. Beginning from IE 8 this has changed and the styling is now applied. Of course, its market share is rather negligible yet.

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

How does one output bold text in Bash?

The most compatible way of doing this is using tput to discover the right sequences to send to the terminal:

bold=$(tput bold)
normal=$(tput sgr0)

then you can use the variables $bold and $normal to format things:

echo "this is ${bold}bold${normal} but this isn't"

gives

this is bold but this isn't

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

use -n parameter to install like for cocoapods:

sudo gem install cocoapods -n /usr/local/bin

Confirmation before closing of tab/browser

Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle

Is there any simple way to convert .xls file to .csv file? (Excel)

I need to do the same thing. I ended up with something similar to Kman

       static void ExcelToCSVCoversion(string sourceFile,  string targetFile)
    {
        Application rawData = new Application();

        try
        {
            Workbook workbook = rawData.Workbooks.Open(sourceFile);
            Worksheet ws = (Worksheet) workbook.Sheets[1];
            ws.SaveAs(targetFile, XlFileFormat.xlCSV);
            Marshal.ReleaseComObject(ws);
        }

        finally
        {
            rawData.DisplayAlerts = false;
            rawData.Quit();
            Marshal.ReleaseComObject(rawData);
        }


        Console.WriteLine();
        Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
        Console.WriteLine();
    }

If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Filtering Table rows using Jquery

Have a look at this jsfiddle.

The idea is to filter rows with function which will loop through words.

jo.filter(function (i, v) {
    var $t = $(this);
    for (var d = 0; d < data.length; ++d) {
        if ($t.is(":contains('" + data[d] + "')")) {
            return true;
        }
    }
    return false;
})
//show the rows that match.
.show();

EDIT: Note that case insensitive filtering cannot be achieved using :contains() selector but luckily there's text() function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1). Look at this jsfiddle.

How to Lazy Load div background images

I had to deal with this for my responsive website. I have many different backgrounds for the same elements to deal with different screen widths. My solution is very simple, keep all your images scoped to a css selector, like "zoinked".

The logic:

If user scrolls, then load in styles with background images associated with them. Done!

Here's what I wrote in a library I call "zoinked" I dunno why. It just happened ok?

(function(window, document, undefined) {   var Z = function() {
    this.hasScrolled = false;

    if (window.addEventListener) {
      window.addEventListener("scroll", this, false);
    } else {
      this.load();
    }   };
     Z.prototype.handleEvent = function(e) {
    if ($(window).scrollTop() > 2) {
      this.hasScrolled = true;
      window.removeEventListener("scroll", this);
      this.load();
    }   };
     Z.prototype.load = function() {
    $(document.body).addClass("zoinked");   };
     window.Zoink = Z; 
})(window, document);

For the CSS I'll have all my styles like this:

.zoinked #graphic {background-image: url(large.jpg);}

@media(max-width: 480px) {.zoinked #graphic {background-image: url(small.jpg);}}

My technique with this is to load all the images after the top ones as soon as the user starts to scroll. If you wanted more control you could make the "zoinking" more intelligent.

How to edit Docker container files from the host?

Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can.

Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do:

$ docker run --name="test" -v /volume-test debian echo "test"

The directory /volume-test inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with:

$ docker inspect -f "{{.Volumes}}" test
map[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895]

If you really need to just make a quick edit to a file to test something, either use docker exec to get a shell in the container and edit directly, or use docker cp to copy the file out, edit on the host and copy back in.

Under which circumstances textAlign property works in Flutter?

Set alignment: Alignment.centerRight in Container:

Container(
    alignment: Alignment.centerRight,
    child:Text(
       "Hello",
    ),
)

Passing arguments to require (when loading module)

I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.

class MyClass { 
  constructor ( arg1, arg2, arg3 )
  myFunction1 () {...}
  myFunction2 () {...}
  myFunction3 () {...}
}

module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }

And then you get your expected behaviour.

var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )

How can I convert my Java program to an .exe file?

You could make a batch file with the following code:

start javaw -jar JarFile.jar

and convert the .bat to an .exe using any .bat to .exe converter.

"Are you missing an assembly reference?" compile error - Visual Studio

Right-click the assembly reference in the solution explorer, properties, disable the "Specific Version" option.

How to add an element to the beginning of an OrderedDict?

You have to make a new instance of OrderedDict. If your keys are unique:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("d",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)])

But if not, beware as this behavior may or may not be desired for you:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("b",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('b', 2), ('a', 1)])

Practical uses of git reset --soft?

While I really like the answers in this thread, I use git reset --soft for a slightly different, but a very practical scenario nevertheless.

I use an IDE for development which has a good diff tool for showing changes (staged and unstaged) after my last commit. Now, most of my tasks involve multiple commits. For example, let's say I make 5 commits to complete a particular task. I use the diff tool in the IDE during every incremental commit from 1-5 to look at my changes from the last commit. I find it a very helpful way to review my changes before committing.

But at the end of my task, when I want to see all my changes together (from before 1st commit), to do a self code-review before making a pull request, I would only see the changes from my previous commit (after commit 4) and not changes from all the commits of my current task.

So I use git reset --soft HEAD~4 to go back 4 commits. This lets me see all the changes together. When I am confident of my changes, I can then do git reset HEAD@{1} and push it to remote confidently.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

How to use if-else logic in Java 8 stream forEach

I think it's possible in Java 9:

animalMap.entrySet().stream()
                .forEach(
                        pair -> Optional.ofNullable(pair.getValue())
                                .ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
                );

Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)

Getting path of captured image in Android using camera intent

try this

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

for capturing image:

    String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();

how to delete default values in text field using selenium?

driver.findElement(locator).clear() - This command will work in all cases

Fixed position but relative to container

Yes, according to the specs, there is a way.

While I agree that Graeme Blackwood's should be the accepted answer, because it practically solves the issue, it should be noted that a fixed element can be positioned relatively to its container.

I noticed by accident that when applying

-webkit-transform: translateZ(0);

to the body, it made a fixed child relative to it (instead of the viewport). So my fixed elements left and top properties were now relative to the container.

So I did some research, and found that the issue was already been covered by Eric Meyer and even if it felt like a "trick", turns out that this is part of the specifications:

For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

http://www.w3.org/TR/css3-transforms/

So, if you apply any transformation to a parent element, it will become the containing block.

But...

The problem is that the implementation seems buggy/creative, because the elements also stop behaving as fixed (even if this bit doesn't seem to be part of specification).

The same behavior will be found in Safari, Chrome and Firefox, but not in IE11 (where the fixed element will still remain fixed).

Another interesting (undocumented) thing is that when a fixed element is contained inside a transformed element, while its top and left properties will now be related to the container, respecting the box-sizing property, its scrolling context will extend over the border of the element, as if box-sizing was set to border-box. For some creative out there, this could possibly become a plaything :)

TEST

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.

You can check this by running in Windows PowerShell:

> Get-Service ssh-agent

And then check the output of status is not running.

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then check that the service has been disabled by running

> Get-Service ssh-agent | Select StartType

StartType
---------
Disabled

I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:

 > Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Alternatively, you can set it through the GUI if you prefer.

services.msc showing the properties of the OpenSSH Agent

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

function is not defined error in Python

Yes, but in what file is pyth_test's definition declared in? Is it also located before it's called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's see what happens:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.

Now then, if we run the interactive python session:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

Convert string to Color in C#

System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");

(Use my method if you want to accept HTML-style hex colors.)

DateTime vs DateTimeOffset

This piece of code from Microsoft explains everything:

// Find difference between Date.Now and Date.UtcNow
  date1 = DateTime.Now;
  date2 = DateTime.UtcNow;
  difference = date1 - date2;
  Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);

  // Find difference between Now and UtcNow using DateTimeOffset
  dateOffset1 = DateTimeOffset.Now;
  dateOffset2 = DateTimeOffset.UtcNow;
  difference = dateOffset1 - dateOffset2;
  Console.WriteLine("{0} - {1} = {2}", 
                    dateOffset1, dateOffset2, difference);
  // If run in the Pacific Standard time zone on 4/2/2007, the example
  // displays the following output to the console:
  //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
  //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00

What is the keyguard in Android?

In a nutshell, it is your lockscreen.

PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

List<Person> list = new ArrayList<Person>();
Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(Person.class);
for (final Object o : criteria.list()) {
    list.add((Person) o);
}

How to Diff between local uncommitted changes and origin

Given that the remote repository has been cached via git fetch it should be possible to compare against these commits. Try the following:

$ git fetch origin
$ git diff origin/master

How to set a default entity property value with Hibernate

<property name="age" type="integer">
<column name="age" not-null="false" default="null" />
</property>

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Really it's interesting. You need just use javax-mail.jar of "com.sun" not "javax.mail".
dwonload com.sun mail jar

Defined Edges With CSS3 Filter Blur

If you are using background image, the best way I found is:

filter: blur(5px);
margin-top: -5px;
padding-bottom: 10px;
margin-left: -5px;
padding-right: 10px;

PHP fopen() Error: failed to open stream: Permission denied

[function.fopen]: failed to open stream

If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

allow_url_fopen = off
should bee this 
allow_url_fopen = On

And add this line below it:
allow_url_include = off
should bee this 
allow_url_include = on

Compare two objects' properties to find differences?

As many mentioned the recursive approach, this is the function you can pass the searched name and the property to begin with to:

    public static void loopAttributes(PropertyInfo prop, string targetAttribute, object tempObject)
    {
        foreach (PropertyInfo nestedProp in prop.PropertyType.GetProperties())
        {
            if(nestedProp.Name == targetAttribute)
            {
                //found the matching attribute
            }
            loopAttributes(nestedProp, targetAttribute, prop.GetValue(tempObject);
        }
    }

//in the main function
foreach (PropertyInfo prop in rootObject.GetType().GetProperties())
{
    loopAttributes(prop, targetAttribute, rootObject);
}

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

REASON

This happens because for now they only ship 64bit JRE with Android Studio for Windows which produces glitches in 32 bit systems.

SOLUTION

  • do not use the embedded JDK: Go to File -> Project Structure dialog, uncheck "Use embedded JDK" and select the 32-bit JRE you've installed separately in your system
  • decrease the memory footprint for Gradle in gradle.properties(Project Properties), for eg set it to -Xmx768m.

For more details: https://code.google.com/p/android/issues/detail?id=219524

How to print without newline or space?

Note: The title of this question used to be something like "How to printf in python?"

Since people may come here looking for it based on the title, Python also supports printf-style substitution:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

And, you can handily multiply string values:

>>> print "." * 10
..........

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

How to get an object's property's value by property name?

$com1 = new-object PSobject                                                         #Task1
$com2 = new-object PSobject                                                         #Task1
$com3 = new-object PSobject                                                         #Task1



$com1 | add-member noteproperty -name user -value jindpal                           #Task2
$com1 | add-member noteproperty -name code -value IT01                              #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com2 | add-member noteproperty -name user -value singh                             #Task2
$com2 | add-member noteproperty -name code -value IT02                              #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com3 | add-member noteproperty -name user -value dhanoa                             #Task2
$com3 | add-member noteproperty -name code -value IT03                               #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}        #Task3


$arr += $com1, $com2, $com3                                                          #Task4


write-host "windows version of computer1 is: "$com1.ver()                            #Task3
write-host "user name of computer1 is: "$com1.user                                   #Task6
write-host "code of computer1 is: "$com1,code                                        #Task5
write-host "windows version of computer2 is: "$com2.ver()                            #Task3
write-host "user name of computer2 is: "$com2.user                                   #Task6
write-host "windows version of computer3 is: "$com3.ver()                            #Task3
write-host "user name of computer3 is: "$com1.user                                   #Task6
write-host "code of computer3 is: "$com3,code                                        #Task5

read-host

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This error occurs when versions of NodeJS and Node Sass are not matched.

you can resolve your issue by doing as below:

- Step 1: Remove Nodejs from your computer

- Step 2: Reinstall Nodejs version 14.15.1.

- Step 3: Uninstall Node sass by run the command npm uninstall node-sass

- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]

After all steps, you can run command ng serve -o to run your application.

Node sass version 5.0.0 is incompatible with ^4.0.0.

Set UIButton title UILabel font size programmatically

This should get you going

[btn_submit.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];

Onchange open URL via select - jQuery

JS Fiddle Example

$('#userNav').change(function() {
window.location = $(':selected',this).attr('href')
});




<select id="userNav">
<option></option>
<option href="http://google.com">Goolge</option>
<option href="http://duckduckgo.com">Go Go duck</option>
</select>

This works for the href in an option that is selected

Calculating Distance between two Latitude and Longitude GeoCoordinates

Based on Elliot Wood's function, and if anyone is interested in a C function, this one is working...

#define SIM_Degree_to_Radian(x) ((float)x * 0.017453292F)
#define SIM_PI_VALUE                         (3.14159265359)

float GPS_Distance(float lat1, float lon1, float lat2, float lon2)
{
   float theta;
   float dist;

   theta = lon1 - lon2;

   lat1 = SIM_Degree_to_Radian(lat1);
   lat2 = SIM_Degree_to_Radian(lat2);
   theta = SIM_Degree_to_Radian(theta);

   dist = (sin(lat1) * sin(lat2)) + (cos(lat1) * cos(lat2) * cos(theta));
   dist = acos(dist);

//   dist = dist * 180.0 / SIM_PI_VALUE;
//   dist = dist * 60.0 * 1.1515;
//   /* Convert to km */
//   dist = dist * 1.609344;

   dist *= 6370.693486F;

   return (dist);
}

You may change it to double. It returns the value in km.

Rails: How to run `rails generate scaffold` when the model already exists?

For the ones starting a rails app with existing database there is a cool gem called schema_to_scaffold to generate a scaffold script. it outputs:

rails g scaffold users fname:string lname:string bdate:date email:string encrypted_password:string

from your schema.rb our your renamed schema.rb. Check it

Appending a byte[] to the end of another byte[]

I wrote the following procedure for concatenation of several array:

  static public byte[] concat(byte[]... bufs) {
    if (bufs.length == 0)
        return null;
    if (bufs.length == 1)
        return bufs[0];
    for (int i = 0; i < bufs.length - 1; i++) {
        byte[] res = Arrays.copyOf(bufs[i], bufs[i].length+bufs[i + 1].length);
        System.arraycopy(bufs[i + 1], 0, res, bufs[i].length, bufs[i + 1].length);
        bufs[i + 1] = res;
    }
    return bufs[bufs.length - 1];
}

It uses Arrays.copyOf

Ideal way to cancel an executing AsyncTask

If you're doing computations:

  • You have to check isCancelled() periodically.

If you're doing a HTTP request:

  • Save the instance of your HttpGet or HttpPost somewhere (eg. a public field).
  • After calling cancel, call request.abort(). This will cause IOException be thrown inside your doInBackground.

In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests method to that class and called this method directly after calling cancel.

Should I use scipy.pi, numpy.pi, or math.pi?

One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:

import math
import numpy
import scipy
import sympy

print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I looked around for a solution to this for a while. It appears that the JDK doesn't have the Mozilla plugins (which is what Chrome uses) in it's installation. It is only in the JRE installation. There are a couple of DLLs that make up the plugin and they all start with np*

Rails 4: assets not loading in production

I'm running Ubuntu Server 14.04, Ruby 2.2.1 and Rails 4.2.4 I have followed a deploy turorial from DigitalOcean and everything went well but when I go to the browser and enter the IP address of my VPS my app is loaded but without styles and javascript.

The app is running with Unicorn and Nginx. To fix this problem I entered my server using SSH with my user 'deployer' and go to my app path which is '/home/deployer/apps/blog' and run the following command:

RAILS_ENV=production bin/rake assets:precompile

Then I just restart the VPS and that's it! It works for me!

Hope it could be useful for somebody else!

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

SharePoint : How can I programmatically add items to a custom list instance

You can create an item in your custom SharePoint list doing something like this:

using (SPSite site = new SPSite("http://sharepoint"))
{
    using (SPWeb web = site.RootWeb)
    {
        SPList list = web.Lists["My List"];
        SPListItem listItem = list.AddItem();
        listItem["Title"] = "The Title";
        listItem["CustomColumn"] = "I am custom";
        listItem.Update();
     }
}

Using list.AddItem() should save the lists items being enumerated.

git push rejected: error: failed to push some refs

git push -f if you have permission, but that will screw up anyone else who pulls from that repo, so be careful.

If that is denied, and you have access to the server, as canzar says below, you can allow this on the server with

git config receive.denyNonFastForwards false

How to read first N lines of a file?

If you want to read the first lines quickly and you don't care about performance you can use .readlines() which returns list object and then slice the list.

E.g. for the first 5 lines:

with open("pathofmyfileandfileandname") as myfile:
    firstNlines=myfile.readlines()[0:5] #put here the interval you want

Note: the whole file is read so is not the best from the performance point of view but it is easy to use, fast to write and easy to remember so if you want just perform some one-time calculation is very convenient

print firstNlines

One advantage compared to the other answers is the possibility to select easily the range of lines e.g. skipping the first 10 lines [10:30] or the lasts 10 [:-10] or taking only even lines [::2].

How to initialize const member variable in a class?

There are couple of ways to initialize the const members inside the class..

Definition of const member in general, needs initialization of the variable too..

1) Inside the class , if you want to initialize the const the syntax is like this

static const int a = 10; //at declaration

2) Second way can be

class A
{
  static const int a; //declaration
};

const int A::a = 10; //defining the static member outside the class

3) Well if you don't want to initialize at declaration, then the other way is to through constructor, the variable needs to be initialized in the initialization list(not in the body of the constructor). It has to be like this

class A
{
  const int b;
  A(int c) : b(c) {} //const member initialized in initialization list
};

Search and replace a line in a file in Python

Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

How to resize a VirtualBox vmdk file

Tried all the solutions here, but nothing seemed to work. After hours of digging I found this blog post and like magic everything works. I had to make little adjustments so here is the modified version. Tested with Docker version 17.06.0-ce, build 02c1d87.

Once developers really start containerising their applications, they often generate a large number of images and quickly fill up the 20GB hard drive space allocated to the Docker virtual machine by default. To make sure the Docker virtual machine has plenty of disk space, we should resize /dev/sda1 to a number that is more reasonable.

  1. Download GParted Live CD/USB/HD/PXE Bootable Image.
  2. Stop the Docker virtual machine docker-machine stop default.

  3. Boot2Docker package installer ships with a VMDK volume, which VirtualBox’s native tools cannot resize. In order to resize the Docker disk volume, first clone the VDI volume from the default VMDK volume vboxmanage clonehd /full/path/to/disk.vmdk /full/path/to/disk_resized.vdi --format VDI --variant Standard.

  4. Resize the newly cloned VDI volume to the desired capacity. We recommend at least 64GB vboxmanage modifyhd /full/path/to/disk_resized.vdi --resize <size in MB>.
  5. Launch the VirtualBox application, select default VM and click on the “Settings” gear on top.VirtualBox Manager
  6. Click on the “Storage” icon. Remove the default VMDK volume.enter image description here
  7. Add a new IDE controller.IDE controller
  8. Mount the GParted ISO via the “Add CD/DVD Device” option.Add CD/DVD Device
  9. Mount the cloned VDI volume via the “Add CD/DVD Device” option.Mount volume
  10. If you are running Docker on a computer with a solid-state hard drive, please make sure the “Solid-state Drive” option is selected for the cloned VDI volume.Solid-state Drive
  11. Click on the “Start” icon to boot up the Docker virtual machine, which will launch the GParted ISO. Select “GParted Live (Default settings)”.GParted Live (Default settings)
  12. Set the policy for handling keymaps to “Don’t touch keymap”.keymaps
  13. Set language preference to option “33”, which maps to “US English”.US English
  14. Select option “1” to run “Forcevideo” and configure X manually.Forcevideo
  15. Keep the default resolution of “1024×760” by selecting option “2”.1024×760
  16. Keep the default “vesa” as the VGA card.Leave blank if default is desired
  17. Keep the default colour depth of “24” by selecting option “0”. Colour depth
  18. Once GParted launches, click on the “Resize/Move” icon.GParted
  19. Set the new disk volume size to desired size by dragging the slider. In this example, the maximum size is 127,035MB. Click on the “Resize/Move” button to start the process.Disk volume size
  20. Confirm the resizing operation by clicking on the “Apply” button.Bake it
  21. Power off the machine after the resizing operation finishes.Hard reset, np :)
  22. Remove the GParted ISO.Your almost done
  23. Log into the Docker virtual machine to verify that the volume resizing was successful by starting machine docker-machine start default
  24. If you experience network issues, restart the docker-machine

Printing Batch file results to a text file

There's nothing wrong with your redirection of standard out to a file. Move and mkdir commands do not output anything. If you really need to have a log trail of those commands, then you'll need to explicitly echo to standard out indicating what you just executed.

The batch file, example:

@ECHO OFF
cd bob
ECHO I just did this: cd bob

Run from command line:

myfile.bat >> out.txt

or

myfile.bat > out.txt

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Jquery : Refresh/Reload the page on clicking a button

You can also use window.location.href=window.location.href;

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

If WorkSheet("wsName") Exists

A version without error-handling:

Function sheetExists(sheetToFind As String) As Boolean
    sheetExists = False
    For Each sheet In Worksheets
        If sheetToFind = sheet.name Then
            sheetExists = True
            Exit Function
        End If
    Next sheet
End Function

php pdo: get the columns name of a table

My 2 cents:

$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));

And you will get the column names as an array in the var $fields.

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Change SVN repository URL

If you are using TortoiseSVN client then you can follow the below steps

Right-click in the source directory and then click on SVN Relocate Image#1

After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.Image#2

PHP Array to CSV

Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Best way to pretty print a hash

Easy to do with json if you trust your keys to be sane:

JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
  gsub(": null", ": nil").
  gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\\1\\2:"). # "foo": 1 -> foo: 1
  gsub(/(^\s*)(".*?"):/, "\\1\\2 =>") # "123": 1 -> "123" => 1

{
  a: 1,
  "2" => 3,
  "3" => nil
}

'NoneType' object is not subscriptable?

Don't use list as a variable name for it shadows the builtin.

And there is no need to determine the length of the list. Just iterate over it.

def printer(data):
    for element in data:
        print(element[0])

Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

Styling the arrow on bootstrap tooltips

This one worked for me!

.tooltip .tooltip-arrow {
border-top: 5px solid red !important;}

Kubernetes service external ip pending

If running on minikube, don't forget to mention namespace if you are not using default.

minikube service << service_name >> --url --namespace=<< namespace_name >>

Reading a resource file from within jar

If you are using spring, then you can use the the following method to read file from src/main/resources:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.core.io.ClassPathResource;

  public String readFileToString(String path) throws IOException {

    StringBuilder resultBuilder = new StringBuilder("");
    ClassPathResource resource = new ClassPathResource(path);

    try (
        InputStream inputStream = resource.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

      String line;

      while ((line = bufferedReader.readLine()) != null) {
        resultBuilder.append(line);
      }

    }

    return resultBuilder.toString();
  }

What's the difference between 'git merge' and 'git rebase'?

While the accepted and most upvoted answer is great, I additionally find it useful trying to explain the difference only by words:

merge

  • “okay, we got two differently developed states of our repository. Let's merge them together. Two parents, one resulting child.”

rebase

  • “Give the changes of the main branch (whatever its name) to my feature branch. Do so by pretending my feature work started later, in fact on the current state of the main branch.”
  • “Rewrite the history of my changes to reflect that.” (need to force-push them, because normally versioning is all about not tampering with given history)
  • “Likely —if the changes I raked in have little to do with my work— history actually won't change much, if I look at my commits diff by diff (you may also think of ‘patches’).“

summary: When possible, rebase is almost always better. Making re-integration into the main branch easier.

Because? ? your feature work can be presented as one big ‘patch file’ (aka diff) in respect to the main branch, not having to ‘explain’ multiple parents: At least two, coming from one merge, but likely many more, if there were several merges. Unlike merges, multiple rebases do not add up. (another big plus)

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

Better way to get type of a Javascript variable?

You can apply Object.prototype.toString to any object:

var toString = Object.prototype.toString;

console.log(toString.call([]));
//-> [object Array]

console.log(toString.call(/reg/g));
//-> [object RegExp]

console.log(toString.call({}));
//-> [object Object]

This works well in all browsers, with the exception of IE - when calling this on a variable obtained from another window it will just spit out [object Object].

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

I had this problem when running sudo ionic run android as root as these environmental variables were not persisted. Fixed by running sudo -E ionic run android.

turn typescript object into json string

Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You can use Bit DataType in SQL Server to store boolean data.

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

Get next / previous element using JavaScript?

Really depends on the overall structure of your document.

If you have:

<div></div>
<div></div>
<div></div>

it may be as simple as traversing through using

mydiv.nextSibling;
mydiv.previousSibling;

However, if the 'next' div could be anywhere in the document you'll need a more complex solution. You could try something using

document.getElementsByTagName("div");

and running through these to get where you want somehow.

If you are doing lots of complex DOM traversing such as this I would recommend looking into a library such as jQuery.

How to list AD group membership for AD users using input list?

Everything in one line:

get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof  -join ";"  } } | export-csv membership.csv

How to call javascript function from code-behind

This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg", 
    "$(document).ready(function(){EnableControls();
    alert('Overrides successfully Updated.');
    DisableControls();});", 
true);

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

Calculate date from week number

I simplified the code Mikael Svensson provided which is correct for many countries in Europe.

public static DateTime FirstDateOfWeekIso8601(int year, int week)
{
        var firstThursdayOfYear = new DateTime(year, 1, 1);
        while (firstThursdayOfYear.DayOfWeek != DayOfWeek.Thursday)
        {
            firstThursdayOfYear = firstThursdayOfYear.AddDays(1);
        }

        var startDateOfWeekOne = firstThursdayOfYear.AddDays(-(DayOfWeek.Thursday - DayOfWeek.Monday));

        return startDateOfWeekOne.AddDays(7 * (week - 1));        
}

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

$(document).ready equivalent without jQuery

This question was asked quite a long time ago. For anyone just seeing this question, there is now a site called "you might not need jquery" which breaks down - by level of IE support required - all the functionality of jquery and provides some alternative, smaller libraries.

IE8 document ready script according to you might not need jquery

function ready(fn) {
    if (document.readyState != 'loading')
        fn();
    else if (document.addEventListener)
        document.addEventListener('DOMContentLoaded', fn);
    else
        document.attachEvent('onreadystatechange', function() {
            if (document.readyState != 'loading')
                fn();
        });
}

Get Number of Rows returned by ResultSet in Java

You could count with sql and retrieve the answer from the resultset like so:

Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                     ResultSet.CONCUR_READ_ONLY);
ResultSet ct = stmt.executeQuery("SELECT COUNT(*) FROM [table_name]");
if(ct.next()){
   td.setTotalNumRows(ct.getInt(1));
}

Here I'm counting everything but you can easily modify the SQL to count based on a criteria.

How to use boolean 'and' in Python

In python, use and instead of && like this:

#!/usr/bin/python
foo = True;
bar = True;
if foo and bar:
    print "both are true";

This prints:

both are true

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This works:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time" // or "runtime"
)

func cleanup() {
    fmt.Println("cleanup")
}

func main() {
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        cleanup()
        os.Exit(1)
    }()

    for {
        fmt.Println("sleeping...")
        time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
    }
}

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

How to set Java environment path in Ubuntu

I have a Linux Lite 3.8 (It bases on Ubuntu 16.04 LTS) and a path change in the following file (with root privileges) with restart has helped.

/etc/profile.d/jdk.sh

Implements vs extends: When to use? What's the difference?

Those two keywords are directly attached with Inheritance it is a core concept of OOP. When we inherit some class to another class we can use extends but when we are going to inherit some interfaces to our class we can't use extends we should use implements and we can use extends keyword to inherit interface from another interface.

Google Map API v3 — set bounds and center

Got everything sorted - see the last few lines for code - (bounds.extend(myLatLng); map.fitBounds(bounds);)

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(
    document.getElementById("map_canvas"),
    myOptions);
  setMarkers(map, beaches);
}

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 161.259052, 5],
  ['Cronulla Beach', -36.028249, 153.157507, 3],
  ['Manly Beach', -31.80010128657071, 151.38747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.159302, 1]
];

function setMarkers(map, locations) {
  var image = new google.maps.MarkerImage('images/beachflag.png',
    new google.maps.Size(20, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
    new google.maps.Size(37, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shape = {
    coord: [1, 1, 1, 20, 18, 20, 18 , 1],
    type: 'poly'
  };
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      shadow: shadow,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
    bounds.extend(myLatLng);
  }
  map.fitBounds(bounds);
}

SQL Server, division returns zero

if you declare it as float or any decimal format it will display

0

only

E.g :

declare @weight float;

SET @weight= 47 / 638; PRINT @weight

Output : 0

If you want the output as

0.073667712

E.g

declare @weight float;

SET @weight= 47.000000000 / 638.000000000; PRINT @weight

default select option as blank

Maybe this will be helpful

<select>
    <option disabled selected value> -- select an option -- </option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

-- select an option -- Will be displayed by default. But if you choose an option,you will not be able select it back.

You can also hide it using by adding an empty option

<option style="display:none">

so it won't show up in the list anymore.

Option 2

If you don't want to write CSS and expect the same behaviour of the solution above, just use:

<option hidden disabled selected value> -- select an option -- </option>

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Assuming you're looking for a quick tactical fix, what you need to do is make sure the cell image is initialized and also that the cell's row is still visible, e.g:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                    if (updateCell)
                        updateCell.poster.image = image;
                });
            }
        }
    }];
    [task resume];

    return cell;
}

The above code addresses a few problems stemming from the fact that the cell is reused:

  1. You're not initializing the cell image before initiating the background request (meaning that the last image for the dequeued cell will still be visible while the new image is downloading). Make sure to nil the image property of any image views or else you'll see the flickering of images.

  2. A more subtle issue is that on a really slow network, your asynchronous request might not finish before the cell scrolls off the screen. You can use the UITableView method cellForRowAtIndexPath: (not to be confused with the similarly named UITableViewDataSource method tableView:cellForRowAtIndexPath:) to see if the cell for that row is still visible. This method will return nil if the cell is not visible.

    The issue is that the cell has scrolled off by the time your async method has completed, and, worse, the cell has been reused for another row of the table. By checking to see if the row is still visible, you'll ensure that you don't accidentally update the image with the image for a row that has since scrolled off the screen.

  3. Somewhat unrelated to the question at hand, I still felt compelled to update this to leverage modern conventions and API, notably:

    • Use NSURLSession rather than dispatching -[NSData contentsOfURL:] to a background queue;

    • Use dequeueReusableCellWithIdentifier:forIndexPath: rather than dequeueReusableCellWithIdentifier: (but make sure to use cell prototype or register class or NIB for that identifier); and

    • I used a class name that conforms to Cocoa naming conventions (i.e. start with the uppercase letter).

Even with these corrections, there are issues:

  1. The above code is not caching the downloaded images. That means that if you scroll an image off screen and back on screen, the app may try to retrieve the image again. Perhaps you'll be lucky enough that your server response headers will permit the fairly transparent caching offered by NSURLSession and NSURLCache, but if not, you'll be making unnecessary server requests and offering a much slower UX.

  2. We're not canceling requests for cells that scroll off screen. Thus, if you rapidly scroll to the 100th row, the image for that row could be backlogged behind requests for the previous 99 rows that aren't even visible anymore. You always want to make sure you prioritize requests for visible cells for the best UX.

The simplest fix that addresses these issues is to use a UIImageView category, such as is provided with SDWebImage or AFNetworking. If you want, you can write your own code to deal with the above issues, but it's a lot of work, and the above UIImageView categories have already done this for you.

Add hover text without javascript like we hover on a user's reputation

You're looking for tooltip

For the basic tooltip, you want:

<div title="This is my tooltip">

For a fancier javascript version, you can look into:

http://www.designer-daily.com/jquery-prototype-mootool-tooltips-12632

The above link gives you 12 options for tooltips.

Storing Images in PostgreSQL

Update from 10 years later In 2008 the hard drives you would run a database on would have much different characteristics and much higher cost than the disks you would store files on. These days there are much better solutions for storing files that didn't exist 10 years ago and I would revoke this advice and advise readers to look at some of the other answers in this thread.

Original

Don't store in images in the database unless you absolutely have to. I understand that this is not a web application, but if there isn't a shared file location that you can point to save the location of the file in the database.

//linuxserver/images/imagexxx.jpg

then perhaps you can quickly set up a webserver and store the web urls in the database (as well as the local path). While databases can handle LOB's and 3000 images (4-6 Megapixels, assuming 500K an image) 1.5 Gigs isn't a lot of space file systems are much better designed for storing large files than a database is.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;
   }
}

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;
   }
}

http://www.codeply.com/go/0TU586QNlV


Bootstrap 4 Breakpoints demo

MSIE and addEventListener Problem in Javascript?

Internet Explorer (IE8 and lower) doesn't support addEventListener(...). It has its own event model using the attachEvent method. You could use some code like this:

var element = document.getElementById('container');
if (document.addEventListener){
    element .addEventListener('copy', beforeCopy, false); 
} else if (el.attachEvent){
    element .attachEvent('oncopy', beforeCopy);
}

Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.

By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.

PHP date() format when inserting into datetime in MySQL

$date_old = '23-5-2016 23:15:23'; 
//Date for database
$date_for_database = date ('Y-m-d H:i:s'", strtotime($date_old));

//Format should be like 'Y-m-d H:i:s'`enter code here`

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

startForeground fail after upgrade to Android 8.1

Works properly on Andorid 8.1:

Updated sample (without any deprecated code):

public NotificationBattery(Context context) {
    this.mCtx = context;

    mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(context.getString(R.string.notification_title_battery))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setChannelId(CHANNEL_ID)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis() + 500)
            .setGroup(GROUP)
            .setOngoing(true);

    mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);

    initBatteryNotificationIntent();

    mBuilder.setContent(mRemoteViews);

    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
                    NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(false);
            channel.setSound(null, null);
            mNotificationManager.createNotificationChannel(channel);
        }
    } else {
        mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
    }
}

Old snipped (it's a different app - not related to the code above):

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    Log.d(TAG, "onStartCommand");

    String CHANNEL_ONE_ID = "com.kjtech.app.N1";
    String CHANNEL_ONE_NAME = "Channel One";
    NotificationChannel notificationChannel = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setShowBadge(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(notificationChannel);
    }

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Notification notification = new Notification.Builder(getApplicationContext())
            .setChannelId(CHANNEL_ONE_ID)
            .setContentTitle(getString(R.string.obd_service_notification_title))
            .setContentText(getString(R.string.service_notification_content))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(icon)
            .build();

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startForeground(START_FOREGROUND_ID, notification);

    return START_STICKY;
}

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)
end

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

sys.argv[1] meaning in script

sys.argv[1] contains the first command line argument passed to your script.

For example, if your script is named hello.py and you issue:

$ python3.1 hello.py foo

or:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

Your script will print:

Hello there foo

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. Set align-self to center.

align-self: center;

See documentation here: align-self

ImportError: No module named psycopg2

I faced same problem and waste almost a day to resolve this issue . I have done 2 things 1- use python 3.6 instead of 3.8 2- change django 2.2 version(may be working some higher but i change to 2.2)

Now its working fine

Javascript Confirm popup Yes, No button instead of OK and Cancel

The featured (but small and simple) library you can use is JSDialog: js.plus/products/jsdialog

Here is a sample for creating a dialog with Yes and No buttons:

JSDialog.showConfirmDialog(
    "Save document before it will be closed?\nIf you press `No` all unsaved changes will be lost.",
    function(result) {
        // check result here
    },
    "warning",
    "yes|no|cancel"
);

JS Dialog demo screenshot

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

Cleanest way to write retry logic?

Exponential backoff is a good retry strategy than simply trying x number of times. You can use a library like Polly to implement it.

Why does the order in which libraries are linked sometimes cause errors in GCC?

Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).

Add Variables to Tuple

Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

And, of course, build them from existing values:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.

I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.

Hopefully this answer will help someone in the future.

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Is a GUID unique 100% of the time?

From http://www.guidgenerator.com/online-guid-generator.aspx

What is a GUID?

GUID (or UUID) is an acronym for 'Globally Unique Identifier' (or 'Universally Unique Identifier'). It is a 128-bit integer number used to identify resources. The term GUID is generally used by developers working with Microsoft technologies, while UUID is used everywhere else.

How unique is a GUID?

128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%. Or if every human on Earth generated 600,000,000 GUIDs there would only be a 50% probability of a duplicate.

Setting attribute disabled on a SPAN element does not prevent click events

There is a dirty trick, what I have used:

I am using bootstrap, so I just added .disabled class to the element which I want to disable. Bootstrap handles the rest of the things.

Suggestion are heartily welcome towards this.

Adding class on run time:

$('#element').addClass('disabled');

Parse string to DateTime in C#

DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

string s = "2011-03-21 13:26";

DateTime dt = 
    DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)

Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).

Another useful resource for C# format strings is String Formatting in C#

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

Connect Android Studio with SVN

Android Studio is based on IntelliJ, and it comes with support for SVN (along with git and mercurial) bundled in. Check http://www.jetbrains.com/idea/features/version_control.html for more info.

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

$('input[type=submit]').closest("form");

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

Old Question, but for angular 6, this needs to be done when you are using HttpClient I am exposing token data publicly here but it would be good if accessed via read-only properties.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { Router } from '@angular/router';


@Injectable()
export class AuthService {
    isLoggedIn: boolean = false;
    url = "token";

    tokenData = {};
    username = "";
    AccessToken = "";

    constructor(private http: HttpClient, private router: Router) { }

    login(username: string, password: string): Observable<object> {
        let model = "username=" + username + "&password=" + password + "&grant_type=" + "password";

        return this.http.post(this.url, model).pipe(
            tap(
                data => {
                    console.log('Log In succesful')
                    //console.log(response);
                    this.isLoggedIn = true;
                    this.tokenData = data;
                    this.username = data["username"];
                    this.AccessToken = data["access_token"];
                    console.log(this.tokenData);
                    return true;

                },
                error => {
                    console.log(error);
                    return false;

                }
            )
        );
    }
}

Do you use NULL or 0 (zero) for pointers in C++?

I think the standard guarantees that NULL == 0, so you can do either. I prefer NULL because it documents your intent.

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

How can I strip HTML tags from a string in ASP.NET?

I've looked at the Regex based solutions suggested here, and they don't fill me with any confidence except in the most trivial cases. An angle bracket in an attribute is all it would take to break, let alone mal-formmed HTML from the wild. And what about entities like &amp;? If you want to convert HTML into plain text, you need to decode entities too.

So I propose the method below.

Using HtmlAgilityPack, this extension method efficiently strips all HTML tags from an html fragment. Also decodes HTML entities like &amp;. Returns just the inner text items, with a new line between each text item.

public static string RemoveHtmlTags(this string html)
{
        if (String.IsNullOrEmpty(html))
            return html;

        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);

        if (doc.DocumentNode == null || doc.DocumentNode.ChildNodes == null)
        {
            return WebUtility.HtmlDecode(html);
        }

        var sb = new StringBuilder();

        var i = 0;

        foreach (var node in doc.DocumentNode.ChildNodes)
        {
            var text = node.InnerText.SafeTrim();

            if (!String.IsNullOrEmpty(text))
            {
                sb.Append(text);

                if (i < doc.DocumentNode.ChildNodes.Count - 1)
                {
                    sb.Append(Environment.NewLine);
                }
            }

            i++;
        }

        var result = sb.ToString();

        return WebUtility.HtmlDecode(result);
}

public static string SafeTrim(this string str)
{
    if (str == null)
        return null;

    return str.Trim();
}

If you are really serious, you'd want to ignore the contents of certain HTML tags too (<script>, <style>, <svg>, <head>, <object> come to mind!) because they probably don't contain readable content in the sense we are after. What you do there will depend on your circumstances and how far you want to go, but using HtmlAgilityPack it would be pretty trivial to whitelist or blacklist selected tags.

If you are rendering the content back to an HTML page, make sure you understand XSS vulnerability & how to prevent it - i.e. always encode any user-entered text that gets rendered back onto an HTML page (> becomes &gt; etc).

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

What's wrong with overridable method calls in constructors?

If you call methods in your constructor that subclasses override, it means you are less likely to be referencing variables that don’t exist yet if you divide your initialization logically between the constructor and the method.

Have a look on this sample link http://www.javapractices.com/topic/TopicAction.do?Id=215

UDP vs TCP, how much faster is it?

UDP is slightly quicker in my experience, but not by much. The choice shouldn't be made on performance but on the message content and compression techniques.

If it's a protocol with message exchange, I'd suggest that the very slight performance hit you take with TCP is more than worth it. You're given a connection between two end points that will give you everything you need. Don't try and manufacture your own reliable two-way protocol on top of UDP unless you're really, really confident in what you're undertaking.

How to hide a div with jQuery?

$("#myDiv").hide();

will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

$("#myDiv").css({
  display: "none",
  visibility: "hidden"
});

Want to show/hide div based on dropdown box selection

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("select").change(function(){_x000D_
        $(this).find("option:selected").each(function(){_x000D_
            var optionValue = $(this).attr("value");_x000D_
            if(optionValue){_x000D_
                $(".box").not("." + optionValue).hide();_x000D_
                $("." + optionValue).show();_x000D_
            } else{_x000D_
                $(".box").hide();_x000D_
            }_x000D_
        });_x000D_
    }).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
    .box{_x000D_
        color: #fff;_x000D_
        padding: 50px;_x000D_
        display: none;_x000D_
        margin-top: 10px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div>_x000D_
        <select>_x000D_
            <option>Choose Color</option>_x000D_
            <option value="red">Red</option>_x000D_
            <option value="green">Green</option>_x000D_
            <option value="blue">Blue</option>_x000D_
        </select>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_