Programs & Examples On #Entry point

For questions concerning the "entry point" of an application or library. The entry point is a special function or location in the code where control is passed from the operating system to the program.

sudo: docker-compose: command not found

On Ubuntu 16.04

Here's how I fixed this issue: Refer Docker Compose documentation

  1. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

  2. sudo chmod +x /usr/local/bin/docker-compose

After you do the curl command , it'll put docker-compose into the

/usr/local/bin

which is not on the PATH. To fix it, create a symbolic link:

  1. sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

And now if you do: docker-compose --version

You'll see that docker-compose is now on the PATH

How to specify the port an ASP.NET Core application is hosted on?

I fixed the port issue in Net core 3.1 by using the following

In the Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
        .ConfigureWebHost(x => x.UseUrls("https://localhost:4000", "http://localhost:4001"))
        .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

You can access the application using

http://localhost:4000

https://localhost:4001

Error: Cannot find module 'webpack'

Link globally installed package to your project

npm link webpack

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

The module ".dll" was loaded but the entry-point was not found

What solved it for me was using :

regasm.exe 'xx.dll' /tlb /codebase /register

It is however, important to understand the difference between regasm.exe and regsvr.exe:

What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

How to establish a connection pool in JDBC?

Pool

  • Pooling Mechanism is the way of creating the Objects in advance. When a class is loaded.
  • It improves the application performance [By re using same object's to perform any action on Object-Data] & memory [allocating and de-allocating many objects creates a significant memory management overhead].
  • Object clean-up is not required as we are using same Object, reducing the Garbage collection load.

« Pooling [ Object pool, String Constant Pool, Thread Pool, Connection pool]

String Constant pool

  • String literal pool maintains only one copy of each distinct string value. which must be immutable.
  • When the intern method is invoked, it check object availability with same content in pool using equals method. « If String-copy is available in the Pool then returns the reference. « Otherwise, String object is added to the pool and returns the reference.

Example: String to verify Unique Object from pool.

public class StringPoolTest {
    public static void main(String[] args) { // Integer.valueOf(), String.equals()
        String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();

        String s1 = "Yash".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
        String s2 = "Yas"+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
        String s3 = "Yas".intern()+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
        String s4 = "Yas"+"h";
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
    }
}

Connection pool using Type-4 Driver using 3rd party libraries[ DBCP2, c3p0, Tomcat JDBC]

Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora]. wiki

In Connection pool mechanism, when the class is loaded it get's the physical JDBC connection objects and provides a wrapped physical connection object to user. PoolableConnection is a wrapper around the actual connection.

  • getConnection() pick one of the free wrapped-connection form the connection objectpool and returns it.
  • close() instead of closing it returns the wrapped-connection back to pool.

Example: Using ~ DBCP2 Connection Pool with Java 7[try-with-resources]

public class ConnectionPool {
    static final BasicDataSource ds_dbcp2 = new BasicDataSource();
    static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
    static final DataSource ds_JDBC = new DataSource();

    static Properties prop = new Properties();
    static {
        try {
            prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));

            ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
            ds_dbcp2.setUrl( prop.getProperty("URL") );
            ds_dbcp2.setUsername( prop.getProperty("UserName") );
            ds_dbcp2.setPassword( prop.getProperty("Password") );
            ds_dbcp2.setInitialSize( 5 );

            ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
            ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
            ds_c3p0.setUser( prop.getProperty("UserName") );
            ds_c3p0.setPassword( prop.getProperty("Password") );
            ds_c3p0.setMinPoolSize(5);
            ds_c3p0.setAcquireIncrement(5);
            ds_c3p0.setMaxPoolSize(20);

            PoolProperties pool = new PoolProperties();
            pool.setUrl( prop.getProperty("URL") );
            pool.setDriverClassName( prop.getProperty("DriverClass") );
            pool.setUsername( prop.getProperty("UserName") );
            pool.setPassword( prop.getProperty("Password") );
            pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)

            pool.setInitialSize(5);
            pool.setMaxActive(3);
            ds_JDBC.setPoolProperties( pool );
        } catch (IOException e) {   e.printStackTrace();
        } catch (PropertyVetoException e) { e.printStackTrace(); }
    }

    public static Connection getDBCP2Connection() throws SQLException {
        return ds_dbcp2.getConnection();
    }

    public static Connection getc3p0Connection() throws SQLException {
        return ds_c3p0.getConnection();
    }

    public static Connection getJDBCConnection() throws SQLException {
        return ds_JDBC.getConnection();
    }
}
public static boolean exists(String UserName, String Password ) throws SQLException {
    boolean exist = false;
    String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
    try ( Connection connection = ConnectionPool.getDBCP2Connection();
          PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
        pstmt.setString(1, UserName );
        pstmt.setString(2, Password );

        try (ResultSet resultSet = pstmt.executeQuery()) {
            exist = resultSet.next(); // Note that you should not return a ResultSet here.
        }
    }
    System.out.println("User : "+exist);
    return exist;
}

jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName> jdbc:oracle:thin:@localhost:1521:myDBName jdbc:mysql://localhost:3306/myDBName

connectionpool.properties

URL         : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName    : root
Password    :

Web Application: To avoid connection problem when all the connection's are closed[MySQL "wait_timeout" default 8 hours] in-order to reopen the connection with underlying DB.

You can do this to Test Every Connection by setting testOnBorrow = true and validationQuery= "SELECT 1" and donot use autoReconnect for MySQL server as it is deprecated. issue

===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
    <Resource name="jdbc/MyAppDB" auth="Container" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        type="javax.sql.DataSource" 

        initialSize="5" minIdle="5" maxActive="15" maxIdle="10"

        testWhileIdle="true"
            timeBetweenEvictionRunsMillis="30000"

        testOnBorrow="true"
            validationQuery="SELECT 1"
            validationInterval="30000"


        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/myDBName" 
        username="yash" password="777"
    />
</Context>

===== ===== web.xml ===== =====
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/MyAppDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet «   init() {}
Normal call used by sevlet  « static {}

static DataSource ds;
static {
    try {
        Context ctx=new InitialContext();
        Context envContext = (Context)ctx.lookup("java:comp/env");
        ds  =   (DataSource) envContext.lookup("jdbc/MyAppDB");
    } catch (NamingException e) {   e.printStackTrace();    }
}

See these also:

What is the best way to modify a list in a 'foreach' loop?

The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T> and a T[] can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.

For example, suppose you have a List<string> and wish to have every string in the list which starts with T be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:

int srcPtr,destPtr;
string[] arr;

srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
  string st = arr[srcPtr];
  char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
  if (ch != 'U')
    arr[destPtr++] = st;
  if (ch == 'T')
    arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
  theList = new List<String>(arr); // Adds extra elements
  if (destPtr != arr.Length)
    theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
  Array.Resize(ref arr, destPtr);
  theList = new List<String>(arr); // Adds extra elements
}

It would have been helpful if List<T> provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.

CodeIgniter: Load controller within controller

Just use

..............

self::index();

..............

How to create a new database after initally installing oracle database 11g Express Edition?

If you wish to create a new schema in XE, you need to create an USER and assign its privileges. Follow these steps:

  • Open the SQL*Plus Command-line
SQL> connect sys as sysdba
  • Enter the password
SQL> CREATE USER myschema IDENTIFIED BY Hga&dshja;
SQL> ALTER USER myschema QUOTA unlimited ON SYSTEM;
SQL> GRANT CREATE SESSION, CONNECT, RESOURCE, DBA TO myschema;
SQL> GRANT ALL PRIVILEGES TO myschema;

Now you can connect via Oracle SQL Developer and create your tables.

Max parallel http connections in a browser?

Max Number of default simultaneous persistent connections per server/proxy:

Firefox 2:  2
Firefox 3+: 6
Opera 9.26: 4
Opera 12:   6
Safari 3:   4
Safari 5:   6
IE 7:       2
IE 8:       6
IE 10:      8
Edge:       6
Chrome:     6

The limit is per-server/proxy, so your wildcard scheme will work.

FYI: this is specifically related to HTTP 1.1; other protocols have separate concerns and limitations (i.e., SPDY, TLS, HTTP 2).

Calling UserForm_Initialize() in a Module

From a module:

UserFormName.UserForm_Initialize

Just make sure that in your userform, you update the sub like so:

Public Sub UserForm_Initialize() so it can be called from outside the form.

Alternately, if the Userform hasn't been loaded:

UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

Finding sum of elements in Swift array

Swift 3+ one liner to sum properties of objects

var totalSum = scaleData.map({$0.points}).reduce(0, +)

Where points is the property in my custom object scaleData that I am trying to reduce

HtmlSpecialChars equivalent in Javascript?

OWASP recommends that "[e]xcept for alphanumeric characters, [you should] escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of [an] attribute."

So here's a function that does that, with a usage example:

_x000D_
_x000D_
function escapeHTML(unsafe) {
  return unsafe.replace(
    /[\u0000-\u002F]|[\u003A-\u0040]|[\u005B-\u00FF]/g,
    c => '&#' + ('000' + c.charCodeAt(0)).substr(-4, 4) + ';'
  )
}
document.querySelector('div').innerHTML =
  '<span class=' +
  escapeHTML('this should break it! " | / % * + , - / ; < = > ^') +
  '>' +
  escapeHTML('<script>alert("inspect the attributes")\u003C/script>') +
  '</span>'
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Disclaimer: You should verify the entity ranges I have provided to validate the safety yourself.

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

How can I write these variables into one line of code in C#?

 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.

set memory_limit to -1 works for me ;) (vim /etc/php/7.2/cli/php.ini)

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

How to open a website when a Button is clicked in Android application?

You can wrap the buttons in anchors that href to the appropriate website.

<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>

When the user clicks the button (input) they are directed to the destination specified in the href property of the anchor.

Edit: Oops, I didn't read "Eclipse" in the question title. My mistake.

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

Laravel check if collection is empty

To determine if there are any results you can do any of the following:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }

Notes / References

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty() https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) works because the Collection implements Countable and an internal count() method:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

So what you can do is :

if (!$mentors->intern->employee->isEmpty()) { }

Check that Field Exists with MongoDB

Suppose we have a collection like below:

{ 
  "_id":"1234"
  "open":"Yes"
  "things":{
             "paper":1234
             "bottle":"Available"
             "bottle_count":40
            } 
}

We want to know if the bottle field is present or not?

Ans:

db.products.find({"things.bottle":{"$exists":true}})

Get a list of dates between two dates

Borrowing an idea from this answer, you can set up a table with 0 through 9 and use that to generate your list of dates.

CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

select adddate('2009-01-01', numlist.id) as `date` from
(SELECT n1.i + n10.i*10 + n100.i*100 AS id
   FROM num n1 cross join num as n10 cross join num as n100) as numlist
where adddate('2009-01-01', numlist.id) <= '2009-01-13';

This will allow you to generate a list of up to 1000 dates. If you need to go larger, you can add another cross join to the inner query.

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

a href link for entire div in HTML/CSS

UPDATE 06/10/2014: using div's inside a's is semantically correct in HTML5.

You'll need to choose between the following scenarios:

<a href="http://google.com">
    <div>
        Hello world
    </div>
</a>

which is semantically incorrect, but it will work.

<div style="cursor: pointer;" onclick="window.location='http://google.com';">
    Hello world
</div>

which is semantically correct but it involves using JS.

<a href="http://google.com">
    <span style="display: block;">
        Hello world
    </span>
</a>

which is semantically correct and works as expected but is not a div any more.

Run Batch File On Start-up

To start the batch file at the start of your system, you can also use a registry key.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Here you can create a string. As name you can choose anything and the data is the full path to your file.

There is also the registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

to run something at only the next start of your system.

Correctly ignore all files recursively under a specific folder except for a specific file type

This might look stupid, but check if you haven't already added the folder/files you are trying to ignore to the index before. If you did, it does not matter what you put in your .gitignore file, the folders/files will still be staged.

How to store a large (10 digits) integer?

In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:

long l1 = 9999999999;  // this won't compile
long l2 = 9999999999L; // this will work

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

How do I count occurrence of duplicate items in array

If you have a multi-dimensional array you can use on PHP 5.5+ this:

array_count_values(array_column($array, 'key'))

which returns e.g.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

How to pass values arguments to modal.show() function in Bootstrap

I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.

Here is my modal code:

<div class="modal fade" id="editGroupNameModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div id="editGroupName" class="modal-header">Enter new name for group </div>
        <div class="modal-body">
          <%= form_tag( { action: 'update_group', port: portnum } ) do %>
          <%= text_field_tag( :gid, "", { type: "hidden" })  %>
          <div class="input-group input-group-md">
          <span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
          <%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}})  %>
        </div>
        <div class="modal-footer">
          <%= submit_tag("Submit") %>
        </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

And here is the simple javascript to change the gid, and gname input values:

function editGroupName(id, name) {
    $('input#gid').val(id);
    $('input#gname.form-control').val(name);
  }

I just used the onclick event in a link:

//                                                                              &#39; is single quote
//                                                                                   ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName(&#39;1&#39;, &#39;admin&#39;); return false;" href="#">edit</a>

The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.

I hope this helps someone someday. Cheers.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

How to check status of PostgreSQL server Mac OS X

You can run the following command to determine if postgress is running:

$ pg_ctl status

You'll also want to set the PGDATA environment variable.

Here's what I have in my ~/.bashrc file for postgres:

export PGDATA='/usr/local/var/postgres'
export PGHOST=localhost
alias start-pg='pg_ctl -l $PGDATA/server.log start'
alias stop-pg='pg_ctl stop -m fast'
alias show-pg-status='pg_ctl status'
alias restart-pg='pg_ctl reload'

To get them to take effect, remember to source it like so:

$ . ~/.bashrc

Now, try it and you should get something like this:

$ show-pg-status
pg_ctl: server is running (PID: 11030)
/usr/local/Cellar/postgresql/9.2.4/bin/postgres

How do I get Fiddler to stop ignoring traffic to localhost?

Fiddler's website addresses this question directly.

There are several suggested workarounds, but the most straightforward is simply to use the machine name rather than "localhost" or "127.0.0.1":

http://machinename/mytestpage.aspx

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

SQL Server convert select a column and convert it to a string

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon                |
| cat  | Purz                 |
| dog  | Fido                 |
| dog  | Beethoven            |
| dog  | Buddy                |
| bird | Tweety               |
+------+----------------------+

select group_concat(name) from Pets
group by type

Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values

Result:

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon,Purz           |
| dog  | Fido,Beethoven,Buddy |
| bird | Tweety               |
+------+----------------------+

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

Selenium Webdriver move mouse to Point

Got it working with

Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

Limit Decimal Places in Android EditText

Slightly improved @Pinhassi solution.

Works very well. It validates concatenated strings.

public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter() {
    mPattern = Pattern.compile("([1-9]{1}[0-9]{0,2}([0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)");

}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    String formatedSource = source.subSequence(start, end).toString();

    String destPrefix = dest.subSequence(0, dstart).toString();

    String destSuffix = dest.subSequence(dend, dest.length()).toString();

    String result = destPrefix + formatedSource + destSuffix;

    result = result.replace(",", ".");

    Matcher matcher = mPattern.matcher(result);

    if (matcher.matches()) {
        return null;
    }

    return "";
}

 }

batch script - run command on each file in directory

for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"

a couple have people have asked me to explain this, so:

Part 1: for /r %%v in (*.xls)

This part returns an array of files in the current directory that have the xls extension. The %% may look a little curious. This is basically the special % character from command line as used in %PATH% or %TEMP%. To use it in a batch file we need to escape it like so: %%PATH%% or %%TEMP%%. In this case we are simply escaping the temporary variable v, which will hold our array of filenames.

We are using the /r switch to search for files recursively, so any matching files in child folders will also be located.

Part 2: do ssconvert "%%v" "%%vx"

This second part is what will get executed once per matching filename, so if the following files were present in the current folder:

c:\temp\mySheet.xls, c:\temp\mySheet_yesterday.xls, c:\temp\mySheet_20160902.xls

the following commands would be executed:

ssconvert "c:\temp\mySheet.xls" "c:\temp\mySheet.xlsx" ssconvert "c:\temp\mySheet_yesterday.xls" "c:\temp\mySheet_yesterday.xlsx" ssconvert "c:\temp\mySheet_20160902.xls" "c:\temp\mySheet_20160902.xlsx"

How to get root view controller?

As suggested here by @0x7fffffff, if you have UINavigationController it can be easier to do:

YourViewController *rootController =
    (YourViewController *)
        [self.navigationController.viewControllers objectAtIndex: 0];

The code in the answer above returns UINavigation controller (if you have it) and if this is what you need, you can use self.navigationController.

How to initialize a nested struct?

Define your Proxy struct separately, outside of Configuration, like this:

type Proxy struct {
    Address string
    Port    string
}

type Configuration struct {
    Val string
    P   Proxy
}

c := &Configuration{
    Val: "test",
    P: Proxy{
        Address: "addr",
        Port:    "80",
    },
}

See http://play.golang.org/p/7PELCVsQIc

Get current time as formatted string in Go?

Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)

t := time.Now()
fmt.Println(t.Format("20060102150405"))

Online demo (with date fixed in the past in the playground, never mind)

Use of def, val, and var in scala

There are three ways of defining things in Scala:

  • def defines a method
  • val defines a fixed value (which cannot be modified)
  • var defines a variable (which can be modified)

Looking at your code:

def person = new Person("Kumar",12)

This defines a new method called person. You can call this method only without () because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:

person

then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:

person.age = 20

what happens is that you first call the person method, and on the return value (an instance of class Person) you are changing the age member variable.

And the last line:

println(person.age)

Here you are again calling the person method, which returns a new instance of class Person (with age set to 12). It's the same as this:

println(person().age)

JavaScript chop/slice/trim off last character in string

You can use the substring method of JavaScript string objects:

s = s.substring(0, s.length - 4)

It unconditionally removes the last four characters from string s.

However, if you want to conditionally remove the last four characters, only if they are exactly _bar:

var re = /_bar$/;
s.replace(re, "");

How do I vertically align text in a paragraph?

Alternative solution which scales for multi-line text:

Set vertical and horizontal padding to be (height - line-height) / 2

p.event_desc {
    font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 14px;
    padding: 10.5px 0;
    margin: 0px;
}

Maximum call stack size exceeded error

you can find your recursive function in crome browser,press ctrl+shift+j and then source tab, which gives you code compilation flow and you can find using break point in code.

How to set width of mat-table column in angular?

Just need to update the width of the th tag.

th {
  width: 100px;
}

count number of characters in nvarchar column

You can find the number of characters using system function LEN. i.e.

SELECT LEN(Column) FROM TABLE

python object() takes no parameters error

I too got this error. Incidentally, i typed __int__ instead of __init__.

I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.

Problems using Maven and SSL behind proxy

I had the same problem with SSL and maven. My companies IT policy restricts me to make any changes to the computers configuration, so I copied the entire .m2 from my other computer and pasted it .m2 folder and it worked.

.m2 folder is usually found under c\user\admin

Correct way to write line to file?

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

Making the main scrollbar always visible

An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.

html { width: 100vw; }

Creating a generic method in C#

I know, I know, but...

public static bool TryGetQueryString<T>(string key, out T queryString)

Copy output of a JavaScript variable to the clipboard

Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.

IE11 has its own API.

And the workaround in the accepted answer can be used for unsecure hosts.

function copyToClipboard (text) {
  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}

Note: it uses Hyperscript to create the input element (but should be easy to adapt)

There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.

How to check if all inputs are not empty with jQuery

I just wanted to point out my answer since I know for loop is faster then $.each loop here it is:

just add class="required" to inputs you want to be required and then in jquery do:

$('#signup_form').submit(function(){
    var fields = $('input.required');
    for(var i=0;i<fields.length;i++){
        if($(fields[i]).val() != ''){
            //whatever
        }
    }
});

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

How do I load a file from resource folder?

Here is one quick solution with the use of Guava:

import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws IOException {
        return Resources.toString(Resources.getResource(fileName), charset);
}

Usage:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)

What is the correct way of reading from a TCP socket in C/C++?

1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:

#define BUFFER_SIZE 4096
char buffer[BUFFER_SIZE]

This saves you the worry of ensuring that you delete[] the buffer should an exception be thrown.

But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.

2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).

How can you float: right in React Native?

You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.

In your case, you will probably want the container to have an attribute

justifyContent: 'flex-end'

And about the text taking the whole space, again, you need to take a look at your container.

Here is a link to really great guide on flexbox: A Complete Guide to Flexbox

BAT file to open CMD in current directory

I'm thinking that if you are creating a batch script that relies on the Current Directory being set to the folder that contains the batch file, that you are setting yourself up for trouble when you try to execute the batch file using a fully qualified path as you would from a scheduler.

Better to add this line to your batch file too:

REM Change Current Directory to the location of this batch file 
CD /D %~dp0

unless you are fully qualifying all of your paths.

Correct way of getting Client's IP Addresses from http.Request

In PHP there are a lot of variables that I should check. Is it the same on Go?

This has nothing to do with Go (or PHP for that matter). It just depends on what the client, proxy, load-balancer, or server is sending. Get the one you need depending on your environment.

http.Request.RemoteAddr contains the remote IP address. It may or may not be your actual client.

And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))

No, why not try it yourself? http://play.golang.org/p/YMf_UBvDsH

XAMPP Apache won't start

I had this problem as well in XAMPP [XAMPP Control Panel v3.2.1] on Windows 8 64bit.

The first thing I done was to use the "Take Ownership" command (see below for a link) and this created a better error message.

From the error message above it changed to: 5:49:08 p.m. [Apache] Problem detected! 5:49:08 p.m. [Apache] Port 80 in use by "C:\Program Files (x86)\Skype\Phone\Skype.exe" with PID 4968! 5:49:08 p.m. [Apache] Apache WILL NOT start without the configured ports free! 5:49:08 p.m. [Apache] You need to uninstall/disable/reconfigure the blocking application 5:49:08 p.m. [Apache] or reconfigure Apache and the Control Panel to listen on a different port

Closing skype fixes this, reopening skype allows it to change the port number itself.

Adding this only because Google finds this error as the best result for "xampp apache wont start". Sorry for posting on an older issue.

Take Ownership Command: http://www.eightforums.com/tutorials/2814-take-ownership-add-context-menu-windows-8-a.html

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Add alternating row color to SQL Server Reporting services report

When using row and column groups both, I had an issue where the colors would alternate between the columns even though it was the same row. I resolved this by using a global variable that alternates only when the row changes:

Public Dim BGColor As String = "#ffffff"

Function AlternateColor() As String
  If BGColor = "#cccccc" Then
    BGColor = "#ffffff"
    Return "#cccccc"
  Else
    BGColor = "#cccccc"
    Return "#ffffff"
  End  If
End Function

Now, in the first column of the row you want to alternate, set the color expression to:

=Code.AlternateColor()

-

In the remaining columns, set them all to:

=Code.BGColor

This should make the colors alternate only after the first column is drawn.

This may (unverifiably) improve performance, too, since it does not need to do a math computation for each column.

Import pfx file into particular certificate store from command line

In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.

Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""

Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""

For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]

How do you modify the web.config appSettings at runtime?

And if you want to avoid the restart of the application, you can move out the appSettings section:

<appSettings configSource="Config\appSettings.config"/>

to a separate file. And in combination with ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

Polygon Drawing and Getting Coordinates with Google Map API v3

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

how to change namespace of entire project?

I tried everything but I found a solution which really works. It creates independed solution with a new namespace name an so on.

  1. In main form find namespace name -> right click -> Refactor -> Rename and select a new name. Check all boxes and click OK.

  2. In the solution explorer rename solution name to a new name.

  3. In the solution explorer rename project name to a new name.

  4. Close VS and rename folder (in total commander for example) in the solution folder to a new name.

  5. In .sln file rename old name to a new name.

  6. Delete old .suo files (hidden)

  7. Start VS and load project

  8. Project -> properties -> change Assembly name and default namespace to a new name.

Rails: call another controller action from a controller

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.

Cutting the videos based on start and end time using ffmpeg

    ffmpeg -i movie.mp4 -vf trim=3:8 cut.mp4

Drop everything except from second 3 to second 8.

MySQL DROP all tables, ignoring foreign keys

DB="your database name" \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=0" \
    && mysqldump --add-drop-table --no-data $DB | grep 'DROP TABLE' | grep -Ev "^$" | mysql $DB \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=1"

Fastest way to convert JavaScript NodeList to Array?

Some optimizations:

  • save the NodeList's length in a variable
  • explicitly set the new array's length before setting.
  • access the indices, rather than pushing or unshifting.

Code (jsPerf):

var arr = [];
for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {
 arr[i] = nl[i];
}

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

Detect Windows version in .net

I used this when I had to determine various Microsoft Operating System versions:

string getOSInfo()
{
   //Get Operating system information.
   OperatingSystem os = Environment.OSVersion;
   //Get version information about the os.
   Version vs = os.Version;

   //Variable to hold our return value
   string operatingSystem = "";

   if (os.Platform == PlatformID.Win32Windows)
   {
       //This is a pre-NT version of Windows
       switch (vs.Minor)
       {
           case 0:
               operatingSystem = "95";
               break;
           case 10:
               if (vs.Revision.ToString() == "2222A")
                   operatingSystem = "98SE";
               else
                   operatingSystem = "98";
               break;
           case 90:
               operatingSystem = "Me";
               break;
           default:
               break;
       }
   }
   else if (os.Platform == PlatformID.Win32NT)
   {
       switch (vs.Major)
       {
           case 3:
               operatingSystem = "NT 3.51";
               break;
           case 4:
               operatingSystem = "NT 4.0";
               break;
           case 5:
               if (vs.Minor == 0)
                   operatingSystem = "2000";
               else
                   operatingSystem = "XP";
               break;
           case 6:
               if (vs.Minor == 0)
                   operatingSystem = "Vista";
               else if (vs.Minor == 1)
                   operatingSystem = "7";
               else if (vs.Minor == 2)
                   operatingSystem = "8";
               else
                   operatingSystem = "8.1";
               break;
           case 10:
               operatingSystem = "10";
               break;
           default:
               break;
       }
   }
   //Make sure we actually got something in our OS check
   //We don't want to just return " Service Pack 2" or " 32-bit"
   //That information is useless without the OS version.
   if (operatingSystem != "")
   {
       //Got something.  Let's prepend "Windows" and get more info.
       operatingSystem = "Windows " + operatingSystem;
       //See if there's a service pack installed.
       if (os.ServicePack != "")
       {
           //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
           operatingSystem += " " + os.ServicePack;
       }
       //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
       //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
   }
   //Return the information we've gathered.
   return operatingSystem;
}

Source: here

Reasons for using the set.seed function

set.seed is a base function that it is able to generate (every time you want) together other functions (rnorm, runif, sample) the same random value.

Below an example without set.seed

> set.seed(NULL)
> rnorm(5)
[1]  1.5982677 -2.2572974  2.3057461  0.5935456  0.1143519
> rnorm(5)
[1]  0.15135371  0.20266228  0.95084266  0.09319339 -1.11049182
> set.seed(NULL)
> runif(5)
[1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
> runif(5)
[1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
> set.seed(NULL)
> sample(5)
[1] 5 4 3 1 2
> sample(5)
[1] 2 1 5 4 3

Below an example with set.seed

> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1

How to test if a list contains another list?

Here is my version:

def contains(small, big):
    for i in xrange(len(big)-len(small)+1):
        for j in xrange(len(small)):
            if big[i+j] != small[j]:
                break
        else:
            return i, i+len(small)
    return False

It returns a tuple of (start, end+1) since I think that is more pythonic, as Andrew Jaffe points out in his comment. It does not slice any sublists so should be reasonably efficient.

One point of interest for newbies is that it uses the else clause on the for statement - this is not something I use very often but can be invaluable in situations like this.

This is identical to finding substrings in a string, so for large lists it may be more efficient to implement something like the Boyer-Moore algorithm.

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

CURRENT_DATE/CURDATE() not working as default DATE value

----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----

Support for DEFAULT with expressions (MDEV-10134).

----- 2018-10-22 8.0.13 General Availability -- -- -----

MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

How to pass data from child component to its parent in ReactJS?

I found the approach how to get data from child component in parents when i need it.

Parent:

class ParentComponent extends Component{
  onSubmit(data) {
    let mapPoint = this.getMapPoint();
  }

  render(){
    return (
      <form onSubmit={this.onSubmit.bind(this)}>
        <ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
        <input type="submit" value="Submit" />
      </form>
    )
  }
}

Child:

class ChildComponent extends Component{
  constructor(props){
    super(props);

    if (props.getCurrentPoint){
      props.getCurrentPoint(this.getMapPoint.bind(this));
    }
  }

  getMapPoint(){
    return this.Point;
  }
}

This example showing how to pass function from child component to parent and use this function to get data from child.

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

  • NOLOCK is local to the table (or views etc)
  • READ UNCOMMITTED is per session/connection

As for guidelines... a random search from StackOverflow and the electric interweb...

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so

Using msbuild to execute a File System Publish Profile

Actually I merged all your answers to my own solution how to solve the above problem:

  1. I create the pubxml file according my needs
  2. Then I copy all the parameters from pubxml file to my own list of parameters "/p:foo=bar" for msbuild.exe
  3. I throw away the pubxml file

The result is like that:

msbuild /t:restore /t:build /p:WebPublishMethod=FileSystem /p:publishUrl=C:\builds\MyProject\ /p:DeleteExistingFiles=True /p:LastUsedPlatform="Any CPU" /p:Configuration=Release

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Lists: Count vs Count()

Always prefer Count and Length properties on a type over the extension method Count(). The former is an O(1) for every type which contains them. The Count() extension method has some type check optimizations that can cause it to run also in O(1) time but will degrade to O(N) if the underlying collection is not one of the few types it knows about.

MISCONF Redis is configured to save RDB snapshots

Check your Redis log before taking any action. Some of the solutions in this thread may erase your Redis data, so be careful about what you are doing.

In my case, the machine was running out of RAM. This also can happen when there is no more free disk space on the host.

Excel VBA Run Time Error '424' object required

Simply remove the .value from your code.

Set envFrmwrkPath = ActiveSheet.Range("D6").Value

instead of this, use:

Set envFrmwrkPath = ActiveSheet.Range("D6")

What's the difference between a temp table and table variable in SQL Server?

For all of you who believe the myth that temp variables are in memory only

First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.

Read the article here: TempDB:: Table variable vs local temporary table

What is the difference between __str__ and __repr__?

One important thing to keep in mind is that container's __str__ uses contained objects' __repr__.

>>> from datetime import datetime
>>> from decimal import Decimal
>>> print (Decimal('52'), datetime.now())
(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 51, 26, 185000))
>>> str((Decimal('52'), datetime.now()))
"(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 52, 22, 176000))"

Python favors unambiguity over readability, the __str__ call of a tuple calls the contained objects' __repr__, the "formal" representation of an object. Although the formal representation is harder to read than an informal one, it is unambiguous and more robust against bugs.

ASP.NET 2.0 - How to use app_offline.htm

I ran into an issue very similar to the original question that took me a little while to resolve.

Just incase anyone else is working on an MVC application and finds their way into this thread, make sure that you have a wildcard mapping to the appropriate .Net aspnet_isapi.dll defined. As soon as I did this, my app_offline.htm started behaving as expected.


IIS 6 Configuration Steps

On IIS Application Properties, select virtual Directory tab.

Under Application Settings, click the Configuration button.

Under Wildcard application maps, click the Insert button.

Enter C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll, click OK.

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

What is the largest Safe UDP Packet Size on the Internet

UDP is not "safe", so the question is not great - however -

  • if you are on a Mac the max size you can send by default is 9216 bytes.
  • if you are on Linux (CentOS/RedHat) or Windows 7 the max is 65507 bytes.

If you send 9217 or more (mac) or 65508+ (linux/windows), the socket send function returns with an error.

The above answers discussing fragmentation and MTU and so on are off topic - that all takes place at a lower level, is "invisible" to you, and does not affect "safety" on typical connections to a significant degree.

To answer the actual question meaning though - do not use UDP - use raw sockets so you get better control of everything; since you're writing a game, you need to delve into the flags to get priority into your traffic anyhow, so you may as well get rid of UDP issues at the same time.

Google Chrome form autofill and its yellow background

This helped me, a CSS only version.

input:-webkit-autofill { -webkit-box-shadow: 0 0 0px 1000px white inset; }

where white can be any color you want.

When should I use GET or POST method? What's the difference between them?

The reason for using POST when making changes to data:

  • A web accelerator like Google Web Accelerator will click all (GET) links on a page and cache them. This is very bad if the links make changes to things.
  • A browser caches GET requests so even if the user clicks the link it may not send a request to the server to execute the change.
  • To protect your site/application against CSRF you must use POST. To completely secure your app you must then also generate a unique identifier on the server and send that along in the request.

Also, don't put sensitive information in the query string (only option with GET) because it shows up in the address bar, bookmarks and server logs.

Hopefully this explains why people say POST is 'secure'. If you are transmitting sensitive data you must use SSL.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Powershell: Get FQDN Hostname

How about: "$env:computername.$env:userdnsdomain"

This actually only works if the user is logged into a domain (i.e. no local accounts), logged into the same domain as the server, and doesn't work with disjointed name space AD configurations.

Use this as referenced in another answer:

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain ; Write-Host $myFQDN

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

Count immediate child div elements using jQuery

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/

Best way to require all files from a directory in ruby?

If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):

Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }

Edit: Based on comments below, an updated version:

Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }

Entity Framework Refresh context?

Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

or in alternative dispose your current context and create a new one.

Change Text Color of Selected Option in a Select Box

JQuery Code:

$('#mySelect').change(function () {
    $('#mySelect').css("background", $("select option:selected").css("background-color"));
});

This will replace the select's background-color with selected option's background-color.

Here is an example fiddle.

Unable to copy a file from obj\Debug to bin\Debug

Rename the assembly to a different name to solve this issue.

Is it possible to display my iPhone on my computer monitor?

This is a tool that will help you, i installed it myself

Here is the link

How to get PID by process name?

Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():

>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)

Also, since Python 3.7, you can use the capture_output=true parameter to capture stdout and stderr:

>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)

Function ereg_replace() is deprecated - How to clear this bug?

Here is more information regarding replacing ereg_replace with preg_replace

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

How to sort a list of lists by a specific index of the inner list?

Like this:

import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))

Truncate a string straight JavaScript

Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:

function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

What is difference between @RequestBody and @RequestParam?

It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.

Searching for UUIDs in text with regex

[\w]{8}(-[\w]{4}){3}-[\w]{12} has worked for me in most cases.

Or if you want to be really specific [\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}.

Capturing a single image from my webcam in Java or Python

I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.

You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:

from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave

graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()

ng-repeat :filter by single field

See the example on the filter page. Use an object, and set the color in the color property:

Search by color: <input type="text" ng-model="search.color">
<div ng-repeat="product in products | filter:search"> 

MySQL Data Source not appearing in Visual Studio

The Connector 6.7.x does not integrate the native data provider anymore. For "Visual Studio 2012" or less, you have to install "MySQL for Visual Studio". If you are using "Visual Studio 2013" there is no possibility to integrate MySQL for the "Entity Framework" yet. A solution should be available on 10/2013!

C convert floating point to int

my_var = (int)my_var;

As simple as that. Basically you don't need it if the variable is int.

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

Where do I find the Instagram media ID of a image

Here is python solution to do this without api call.

def media_id_to_code(media_id):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    short_code = ''
    while media_id > 0:
        remainder = media_id % 64
        media_id = (media_id-remainder)/64
        short_code = alphabet[remainder] + short_code
    return short_code


def code_to_media_id(short_code):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    media_id = 0;
    for letter in short_code:
        media_id = (media_id*64) + alphabet.index(letter)

    return media_id

X11/Xlib.h not found in Ubuntu

A quick search using...

apt search Xlib.h

Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?

You can add Xlib.h to your system by running the following...

sudo apt install libx11-dev

How best to determine if an argument is not sent to the JavaScript function

Why not using the !! operator? This operator, placed before the variable, turn it to a boolean (if I've understood well), so !!undefined and !!null (and even !!NaN, which can be quite interesting) will return false.

Here is an exemple:

function foo(bar){
    console.log(!!bar);
}

foo("hey") //=> will log true

foo() //=> will log false

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You should use the Chartjs API function toBase64Image() instead and call it after the animation is complete. Therefore:

var pieChart, URI;

var options = {
    animation : {
        onComplete : function(){    
            URI = pieChart.toBase64Image();
        }
    }
};

var content = {
    type: 'pie', //whatever, not relevant for this example
    data: {
        datasets: dataset //whatever, not relevant for this example
    },
    options: options        
};    

pieChart = new Chart(pieChart, content);

Example

You can check this example and run it

_x000D_
_x000D_
var chart = new Chart(ctx, {_x000D_
   type: 'bar',_x000D_
   data: {_x000D_
      labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
      // create 12 datasets, since we have 12 items_x000D_
      // data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
      // put 0, if there is no data for the particular bar_x000D_
      datasets: [{_x000D_
         label: 'Washing and cleaning',_x000D_
         data: [0, 8],_x000D_
         backgroundColor: '#22aa99'_x000D_
      }, {_x000D_
         label: 'Traffic tickets',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#994499'_x000D_
      }, {_x000D_
         label: 'Tolls',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#316395'_x000D_
      }, {_x000D_
         label: 'Parking',_x000D_
         data: [5, 2],_x000D_
         backgroundColor: '#b82e2e'_x000D_
      }, {_x000D_
         label: 'Car tax',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#66aa00'_x000D_
      }, {_x000D_
         label: 'Repairs and improvements',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#dd4477'_x000D_
      }, {_x000D_
         label: 'Maintenance',_x000D_
         data: [6, 1],_x000D_
         backgroundColor: '#0099c6'_x000D_
      }, {_x000D_
         label: 'Inspection',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#990099'_x000D_
      }, {_x000D_
         label: 'Loan interest',_x000D_
         data: [0, 3],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Depreciation of the vehicle',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Fuel',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#dc3912'_x000D_
      }, {_x000D_
         label: 'Insurance and Breakdown cover',_x000D_
         data: [4, 0],_x000D_
         backgroundColor: '#3366cc'_x000D_
      }]_x000D_
   },_x000D_
   options: {_x000D_
      responsive: false,_x000D_
      legend: {_x000D_
         position: 'right' // place legend on the right side of chart_x000D_
      },_x000D_
      scales: {_x000D_
         xAxes: [{_x000D_
            stacked: true // this should be set to make the bars stacked_x000D_
         }],_x000D_
         yAxes: [{_x000D_
            stacked: true // this also.._x000D_
         }]_x000D_
      },_x000D_
      animation : {_x000D_
         onComplete : done_x000D_
      }      _x000D_
   }_x000D_
});_x000D_
_x000D_
function done(){_x000D_
    alert(chart.toBase64Image());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
<canvas id="ctx" width="700"></canvas>
_x000D_
_x000D_
_x000D_

What is the difference between HTML tags and elements?

<p>Here is a quote from WWF's website:</p>.

In this part <p> is a tag.

<blockquote cite="www.facebook.com">facebook is the world's largest socialsite..</blockquote>

in this part <blockquote> is an element.

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

try:
    width = input()
    height = input()
    def rectanglePerimeter(width, height):
       return ((width + height)*2)
    print(rectanglePerimeter(width, height))
except EOFError as e:
    print(end="")

Directly export a query to CSV using SQL Developer

After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

Exit while loop by user hitting ENTER key

Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.

  1. If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
  2. If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.

Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link

I think the following links would also help you to understand in much better way.

  1. python cross platform listening for keypresses

  2. How do I get a single keypress at a time

  3. Useful routines from the MS VC++ runtime

I hope this helps you to get your job done.

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

How to copy multiple files in one layer using a Dockerfile?

COPY <all> <the> <things> <last-arg-is-destination>

But here is an important excerpt from the docs:

If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy

remove kernel on jupyter notebook

If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

~/.local/share/jupyter/kernels/

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

After installation of Oracle Client 11.02.04, reboot the server and make sure USERS(Local Computer) is added with Full Control on Root folder for eg WWW

Tested, it worked.

Convert php array to Javascript

u can also do in this way

<script>  
    <?php 
        $php_array = array('abc','def','ghi');
    ?>  
    var array_code = <?php echo json_encode($php_array); ?>;
    console.log(array_code);
</script>

Android: show/hide a view using an animation

Set the attribute android:animateLayoutChanges="true" inside the parent layout .

Put the view in a layout if its not and set android:animateLayoutChanges="true" for that layout.

NOTE: This works only from API Level 11+ (Android 3.0)

Nesting CSS classes

Not directly. But you can use extensions such as LESS to help you achieve the same.

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

Split output of command by columns using Bash?

Instead of doing all these greps and stuff, I'd advise you to use ps capabilities of changing output format.

ps -o cmd= -p 12345

You get the cmmand line of a process with the pid specified and nothing else.

This is POSIX-conformant and may be thus considered portable.

Collection that allows only unique items in .NET?

Just to add my 2 cents...

if you need a ValueExistingException-throwing HashSet<T> you can also create your collection easily:

public class ThrowingHashSet<T> : ICollection<T>
{
    private HashSet<T> innerHash = new HashSet<T>();

    public void Add(T item)
    {
        if (!innerHash.Add(item))
            throw new ValueExistingException();
    }

    public void Clear()
    {
        innerHash.Clear();
    }

    public bool Contains(T item)
    {
        return innerHash.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        innerHash.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return innerHash.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        return innerHash.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return innerHash.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

this can be useful for example if you need it in many places...

How to get all count of mongoose model?

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });

Export a list into a CSV or TXT file in R

I think the most straightforward way to do this is using capture.output, thus;

capture.output(summary(mylist), file = "My New File.txt")

Easy!

How can I stage and commit all files, including newly added files, using a single command?

I have in my config two aliases:

alias.foo=commit -a -m 'none'
alias.coa=commit -a -m

if I am too lazy I just commit all changes with

git foo

and just to do a quick commit

git coa "my changes are..."

coa stands for "commit all"

Sending the bearer token with axios

By using Axios interceptor:

const service = axios.create({
  timeout: 20000 // request timeout
});

// request interceptor

service.interceptors.request.use(
  config => {
    // Do something before request is sent

    config.headers["Authorization"] = "bearer " + getToken();
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

Stretch background image css?

You can't stretch a background image (until CSS 3).

You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.

_x000D_
_x000D_
table {_x000D_
  width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
  text-align: center;_x000D_
  height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
  <tr>_x000D_
    <td class="style1">_x000D_
      <div class="bg">_x000D_
        <img src="http://placekitten.com/20/20" alt="" />_x000D_
        <div class="linkcontainer">_x000D_
          <a class="link" href="#">_x000D_
            <span>Answer</span>_x000D_
          </a>_x000D_
        </div>_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How does data binding work in AngularJS?

AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

$watch() :-

This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$digest() -

This function iterates through all the watches in the $scope object, and its child $scope objects
(if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

$apply() -

Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

Awaiting multiple Tasks with different results

If you're using C# 7, you can use a handy wrapper method like this...

public static class TaskEx
{
    public static async Task<(T1, T2)> WhenAll<T1, T2>(Task<T1> task1, Task<T2> task2)
    {
        return (await task1, await task2);
    }
}

...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.

var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());

However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.

Comparing two input values in a form validation with AngularJS

Thanks for the great example @Jacek Ciolek. For angular 1.3.x this solution breaks when updates are made to the reference input value. Building on this example for angular 1.3.x, this solution works just as well with Angular 1.3.x. It binds and watches for changes to the reference value.

angular.module('app', []).directive('sameAs', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      sameAs: '='
    },
    link: function(scope, elm, attr, ngModel) {
      if (!ngModel) return;

      attr.$observe('ngModel', function(value) {
        // observes changes to this ngModel
        ngModel.$validate();
      });

      scope.$watch('sameAs', function(sameAs) {
        // watches for changes from sameAs binding
        ngModel.$validate();
      });

      ngModel.$validators.sameAs = function(value) {
        return scope.sameAs == value;
      };
    }
  };
});

Here is my pen: http://codepen.io/kvangrae/pen/BjxMWR

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

Of the options you asked about:

  • float:left;
    I dislike floats because of the need to have additional markup to clear the float. As far as I'm concerned, the whole float concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.

The additional markup for clearing may not be necessary if you use the :after selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.

  • display:inline;
    This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1 is a fall-back hack for the broken support for inline-block.

  • display:inline-block;
    This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.

The other big caveat with inline-block is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)

  • display:table-cell;
    Another one where you'll have problems with browser compatibility. Older IEs won't work with this at all. But even for other browsers, it's worth noting that table-cell is designed to be used in a context of being inside elements that are styled as table and table-row; using table-cell in isolation is not the intended way to do it, so you may experience different browsers treating it differently.

Other techniques you may have missed? Yes.

  • Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.

  • There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox

Hope that helps.

How to run Spyder in virtual environment?

There is an option to create virtual environments in Anaconda with required Python version.

conda create -n myenv python=3.4

To activate it :

source activate myenv   # (in linux, you can use . as a shortcut for "source")
activate myenv          # (in windows - note that you should be in your c:\anaconda2 directory)

UPDATE. I have tested it with Ubuntu 18.04. Now you have to install spyder additionally for the new environment with this command (after the activation of the environment with the command above):

conda install spyder

(I have also tested the installation with pip, but for Python 3.4 or older versions, it breaks with the library dependencies error that requires manual installation.)

And now to run Spyder with Python 3.4 just type:

spyder

Spyder with Python 3.4

EDIT from a reader:

For a normal opening, use "Anaconda Prompt" > activate myenv > spyder (then the "Anaconda Prompt" must stay open, you cannot use it for other commands, and a force-close will shut down Spyder). This is of course faster than the long load of "Anaconda Navigator" > switch environment > launch Spyder (@adelriosantiago's answer).

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

How to convert JSONObjects to JSONArray?

Your response should be something like this to be qualified as Json Array.

{
  "songs":[
    {"2562862600": {"id":"2562862600", "pos":1}},  
    {"2562862620": {"id":"2562862620", "pos":1}},  
    {"2562862604": {"id":"2562862604", "pos":1}},  
    {"2573433638": {"id":"2573433638", "pos":1}}
  ]
}

You can parse your response as follows

String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);  
JSONArray arr = ob.getJSONArray("songs");

for(int i=0; i<arr.length(); i++){   
  JSONObject o = arr.getJSONObject(i);  
  System.out.println(o);  
}

Best way to test exceptions with Assert to ensure they will be thrown

As an alternative to using ExpectedException attribute, I sometimes define two helpful methods for my test classes:

AssertThrowsException() takes a delegate and asserts that it throws the expected exception with the expected message.

AssertDoesNotThrowException() takes the same delegate and asserts that it does not throw an exception.

This pairing can be very useful when you want to test that an exception is thrown in one case, but not the other.

Using them my unit test code might look like this:

ExceptionThrower callStartOp = delegate(){ testObj.StartOperation(); };

// Check exception is thrown correctly...
AssertThrowsException(callStartOp, typeof(InvalidOperationException), "StartOperation() called when not ready.");

testObj.Ready = true;

// Check exception is now not thrown...
AssertDoesNotThrowException(callStartOp);

Nice and neat huh?

My AssertThrowsException() and AssertDoesNotThrowException() methods are defined on a common base class as follows:

protected delegate void ExceptionThrower();

/// <summary>
/// Asserts that calling a method results in an exception of the stated type with the stated message.
/// </summary>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
/// <param name="expectedExceptionType">The expected type of the exception, e.g. typeof(FormatException).</param>
/// <param name="expectedExceptionMessage">The expected exception message (or fragment of the whole message)</param>
protected void AssertThrowsException(ExceptionThrower exceptionThrowingFunc, Type expectedExceptionType, string expectedExceptionMessage)
{
    try
    {
        exceptionThrowingFunc();
        Assert.Fail("Call did not raise any exception, but one was expected.");
    }
    catch (NUnit.Framework.AssertionException)
    {
        // Ignore and rethrow NUnit exception
        throw;
    }
    catch (Exception ex)
    {
        Assert.IsInstanceOfType(expectedExceptionType, ex, "Exception raised was not the expected type.");
        Assert.IsTrue(ex.Message.Contains(expectedExceptionMessage), "Exception raised did not contain expected message. Expected=\"" + expectedExceptionMessage + "\", got \"" + ex.Message + "\"");
    }
}

/// <summary>
/// Asserts that calling a method does not throw an exception.
/// </summary>
/// <remarks>
/// This is typically only used in conjunction with <see cref="AssertThrowsException"/>. (e.g. once you have tested that an ExceptionThrower
/// method throws an exception then your test may fix the cause of the exception and then call this to make sure it is now fixed).
/// </remarks>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
protected void AssertDoesNotThrowException(ExceptionThrower exceptionThrowingFunc)
{
    try
    {
        exceptionThrowingFunc();
    }
    catch (NUnit.Framework.AssertionException)
    {
        // Ignore and rethrow any NUnit exception
        throw;
    }
    catch (Exception ex)
    {
        Assert.Fail("Call raised an unexpected exception: " + ex.Message);
    }
}

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

How can I use custom fonts on a website?

You have to import the font in your stylesheet like this:

@font-face{
    font-family: "Thonburi-Bold";
    src: url('Thonburi-Bold.ttf'),
    url('Thonburi-Bold.eot'); /* IE */
}

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Python error when trying to access list by index - "List indices must be integers, not str"

players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.

Jenkins not executing jobs (pending - waiting for next executor)

For me I have to restart the executors manually. Click on "Dead" under "Build Executor Status" and push the restart button.

Add Custom Headers using HttpWebRequest

You should do ex.StackTrace instead of ex.ToString()

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just use the interface provided by MySql's GUI Tool (SQLyog):

Click on User manager: enter image description here

Now, if you want to grant access FOR ANY OTHER REMOTE PC, just make sure that, just like in the underneath picture, the Host field value is % (which is the wildcard)

enter image description here

Bootstrap 3 select input form inline

Another different answer to an old question. However, I found a implementation made specifically for bootstrap which might prove useful here. Hope this helps anybody who is looking...

Bootstrap-select

How to append to New Line in Node.js

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

A keyboard shortcut to comment/uncomment the select text in Android Studio

I had the same problem, usually, you have found the shortcut but it doesn't work because you have not a NumPad. Actually, the only one issue I found is to set my own shortcut with the one I suppose should works.

First step, find the IDE shortcuts : cmd + shift + A enter shortcuts First step, find the IDE shortcuts : <code>cmd + shift + A</code> enter shortcuts

Second step : Find Comments Shortcut with the finder enter image description here

Third step : Set your custom shortcut (I suggest cmd + shift + / or cmd + : ) enter image description here

Now enjoy, it works on a macBook without NumPad

edit : cmd + shift + : has conflicts

Edit : this both works without conflicts enter image description hereIssue on MacBook

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

LINQ .Any VS .Exists - What's the difference?

The difference is that Any is an extension method for any IEnumerable<T> defined on System.Linq.Enumerable. It can be used on any IEnumerable<T> instance.

Exists does not appear to be an extension method. My guess is that coll is of type List<T>. If so Exists is an instance method which functions very similar to Any.

In short, the methods are essentially the same. One is more general than the other.

  • Any also has an overload which takes no parameters and simply looks for any item in the enumerable.
  • Exists has no such overload.

Selenium WebDriver findElement(By.xpath()) not working for me

Correct Xpath syntax is like:

//tagname[@value='name']

So you should write something like this:

findElement(By.xpath("//input[@test-id='test-username']"));

Can't update data-attribute value

Basically, there are two ways to set / update data attribute value, depends on your need. The difference is just, where the data saved,

If you use .data() it will be saved in local variable called data_user, and its not visible upon element inspection, If you use .attr() it will be publicly visible.

Much clearer explanation on this comment

ng if with angular for string contains

Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.

Controller:

angular.module("myApp")
.controller("myController",function(){
    var self = this;

    self.select = { /* ... */ };

    self.showFoo = function() {
        //Checks if self.select.name contains the character '?'
        return self.select.name.indexOf('?') != -1;
    }
});

Page example:

<div ng-app="myApp" ng-controller="myController as vm">
    <p ng-show="vm.showFoo()">Bar</p>
</div>

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

Dynamically Add Variable Name Value Pairs to JSON Object

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

How to delete rows in tables that contain foreign keys to other tables

You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.

ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE 

How to ignore the certificate check when ssl

Since there is only one global ServicePointManager, setting ServicePointManager.ServerCertificateValidationCallback will yield the result that all subsequent requests will inherit this policy. Since it is a global "setting" it would be prefered to set it in the Application_Start method in Global.asax.

Setting the callback overrides the default behaviour and you can yourself create a custom validation routine.

How to prevent colliders from passing through each other?

  • Edit ---> Project Settings ---> Time ... decrease "Fixed Timestep" value .. This will solve the problem but it can affect performance negatively.

  • Another solution is could be calculate the coordinates (for example, you have a ball and wall. Ball will hit to wall. So calculate coordinates of wall and set hitting process according these cordinates )

Is it a bad practice to use break in a for loop?

Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).

In those cases it will even make sense to set a flag and only check the flag value AFTER all the for loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.

If you do not care about the run time... use break; and continue; to make the code easier to read.

Rolling or sliding window iterator?

why not

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

It is documented in Python doc . You can easily extend it to wider window.

How to inject a Map using the @Value Spring Annotation?

You can inject .properties as a map in your class using @Resource annotation.

If you are working with XML based configuration, then add below bean in your spring configuration file:

 <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

Then you can pick them up in your application as a Map:

@Resource(name = "myProperties")
private Map<String, String> myProperties;

How to check if a textbox is empty using javascript

Using this JavaScript will help you a lot. Some explanations are given within the code.

<script type="text/javascript">
    <!-- 
        function Blank_TextField_Validator()
        {
        // Check whether the value of the element 
        // text_name from the form named text_form is null
        if (!text_form.text_name.value)
        {
          // If it is display and alert box
           alert("Please fill in the text field.");
          // Place the cursor on the field for revision
           text_form.text_name.focus();
          // return false to stop further processing
           return (false);
        }
        // If text_name is not null continue processing
        return (true);
        }
        -->
</script>
<form name="text_form" method="get" action="#" 
    onsubmit="return Blank_TextField_Validator()">
    <input type="text" name="text_name" >
    <input type="submit" value="Submit">
</form>

One line if in VB .NET

You can use the IIf function too:

CheckIt = IIf(TestMe > 1000, "Large", "Small")

how to check if string contains '+' character

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj

Visual Studio Code open tab in new window

On Windows and Linux, press Ctrl+K, then release the keys and press O (the letter O, not Zero).

On macOS, press command+K, then O (without holding command).

This will open the active file tab in a new window/instance.

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Postgresql - unable to drop database because of some auto connections to DB

Stop your running application.(in Eclipse) After you try again.

How do I address unchecked cast warnings?

You can create a utility class like the following, and use it to suppress the unchecked warning.

public class Objects {

    /**
     * Helps to avoid using {@code @SuppressWarnings({"unchecked"})} when casting to a generic type.
     */
    @SuppressWarnings({"unchecked"})
    public static <T> T uncheckedCast(Object obj) {
        return (T) obj;
    }
}

You can use it as follows:

import static Objects.uncheckedCast;
...

HashMap<String, String> getItems(javax.servlet.http.HttpSession session) {
      return uncheckedCast(session.getAttribute("attributeKey"));
}

Some more discussion about this is here: http://cleveralias.blogs.com/thought_spearmints/2006/01/suppresswarning.html

Adding background image to div using CSS

To use an image for body background in CSS

body {
  background-image: url("image.jpg");
}

find all unchecked checkbox in jquery

Also it can be achieved with pure js in such a way:

var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

Adding a Time to a DateTime in C#

   DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));

How to remove an element slowly with jQuery?

You mean like

$target.hide('slow')

?

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

ImportError: No module named requests

if you want request import on windows:

pip install request

then beautifulsoup4 for:

pip3 install beautifulsoup4

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.