Programs & Examples On #Dataview

A dataview is a .net class which represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data, but instead represents a connected view of its corresponding DataTable. Changes to the DataView’s data will affect the DataTable. Changes to the DataTable’s data will affect all DataViews associated with it.

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...
}

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

How to capture multiple repeated groups?

Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:

def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
  println "Match #$i: ${g[1]}"
}

Match #0: HELLO
Match #1: THERE
Match #2: WORLD

How to align an indented line in a span that wraps into multiple lines?

<!DOCTYPE html>
<html>
<body>

<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>

</body>
</html>

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

How to remove button shadow (android)

I use a custom style

<style name="MyButtonStyle" parent="@style/Widget.AppCompat.Button.Borderless"></style>

Don't forget to add

<item name="android:textAllCaps">false</item>

otherwise the button text will be in UpperCase.

Is #pragma once a safe include guard?

Today old-school include guards are as fast as a #pragma once. Even if the compiler doesn't treat them specially, it will still stop when it sees #ifndef WHATEVER and WHATEVER is defined. Opening a file is dirt cheap today. Even if there were to be an improvement, it would be in the order of miliseconds.

I simply just don't use #pragma once, as it has no benefit. To avoid clashing with other include guards I use something like: CI_APP_MODULE_FILE_H --> CI = Company Initials; APP = Application name; the rest is self-explanatory.

Remote debugging Tomcat with Eclipse

In catalina.bat file please modify the below.

  • Step 1: CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

  • Step 2: JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  • Step 3: Run Tomcat from command prompt like below: catalina.sh jpda start

  • Step 4: Then in the eclipse create a debug configuration

    1. Give any name for configuration.
    2. Give the project name.
    3. Give the connection type as Standard(Socket Attach)
    4. host as localhost
    5. port as 8000( or any port number , but that should be same in other places also).

Doctrine findBy 'does not equal'

Based on the answer from Luis, you can do something more like the default findBy method.

First, create a default repository class that is going to be used by all your entities.

/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );

Or you can edit this in config.yml

doctrine: orm: default_repository_class: MyCompany\Repository

Then:

<?php

namespace MyCompany;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $expr = $this->getEntityManager()->getExpressionBuilder();

        $qb->select( 'entity' )
            ->from( $this->getEntityName(), 'entity' );

        foreach ( $criteria as $field => $value ) {
            // IF INTEGER neq, IF NOT notLike
            if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
                $qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
            } else {
                $qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
            }
        }

        if ( $orderBy ) {

            foreach ( $orderBy as $field => $order ) {

                $qb->addOrderBy( 'entity.' . $field, $order );
            }
        }

        if ( $limit )
            $qb->setMaxResults( $limit );

        if ( $offset )
            $qb->setFirstResult( $offset );

        return $qb->getQuery()
            ->getResult();
    }

}

The usage is the same than the findBy method, example:

$entityManager->getRepository( 'MyRepo' )->findByNot(
    array( 'status' => Status::STATUS_DISABLED )
);

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

How to delete an element from a Slice in Golang

Remove one element from the Slice (this is called 're-slicing'):

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
    all = RemoveIndex(all, 5)
    fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}

Bootstrap css hides portion of container below navbar navbar-fixed-top

Just define an empty navbar prior to the fixed one, it will create the space needed.

<nav class="navbar navbar-default ">
</nav>
<nav class="navbar  navbar-default navbar-fixed-top ">
     <div class="container-fluid">
// Your menu code 
     </div>
</nav>

Querying data by joining two tables in two database on different servers

From a practical enterprise perspective, the best practice is to make a mirrored copy of the database table in your database, and then just have a task/proc update it with delta's every hour.

mat-form-field must contain a MatFormFieldControl

Unfortunately content projection into mat-form-field is not supported yet. Please track the following github issue to get the latest news about it.

By now the only solution for you is either place your content directly into mat-form-field component or implement a MatFormFieldControl class thus creating a custom form field component.

Understanding Python super() with __init__() methods

It's been noted that in Python 3.0+ you can use

super().__init__()

to make your call, which is concise and does not require you to reference the parent OR class names explicitly, which can be handy. I just want to add that for Python 2.7 or under, some people implement a name-insensitive behaviour by writing self.__class__ instead of the class name, i.e.

super(self.__class__, self).__init__()  # DON'T DO THIS!

HOWEVER, this breaks calls to super for any classes that inherit from your class, where self.__class__ could return a child class. For example:

class Polygon(object):
    def __init__(self, id):
        self.id = id

class Rectangle(Polygon):
    def __init__(self, id, width, height):
        super(self.__class__, self).__init__(id)
        self.shape = (width, height)

class Square(Rectangle):
    pass

Here I have a class Square, which is a sub-class of Rectangle. Say I don't want to write a separate constructor for Square because the constructor for Rectangle is good enough, but for whatever reason I want to implement a Square so I can reimplement some other method.

When I create a Square using mSquare = Square('a', 10,10), Python calls the constructor for Rectangle because I haven't given Square its own constructor. However, in the constructor for Rectangle, the call super(self.__class__,self) is going to return the superclass of mSquare, so it calls the constructor for Rectangle again. This is how the infinite loop happens, as was mentioned by @S_C. In this case, when I run super(...).__init__() I am calling the constructor for Rectangle but since I give it no arguments, I will get an error.

Gitignore not working

I used something to generate common .gitignore for me and I ran into this. After reading @Ozesh answer I opened in VS Code because it has a nice indicator at bottom right showing type of line endings. It was LF so I converted to CRLF as suggested but no dice.

Then I looked next to the line endings and noticed it was saved using UTF16. So I resaved using UTF8 encoding an voila, it worked. I didn't think the CRLF mattered so I changed it back to LF to be sure and it still worked.

Of course this wasn't OPs issue since he had already committed the files so they were already indexed, but thought I'd share in case someone else stumbles across this.

TLDR; If you haven't already committed the files and .gitignore still isn't being respected then check file encoding and, make sure its UTF8 and if that doesn't work then maybe try messing with line endings.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

Don't return Strings in your methods but Customer objects it self and let JAXB take care of the de/serialization.

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

Pass Additional ViewData to a Strongly-Typed Partial View

You can use the dynamic variable ViewBag

ViewBag.AnotherValue = valueToView;

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.

Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.

The advantages over other FTS (full text search) Engines are:

  • RESTful interface
  • Better scalability
  • Large community
  • Built by Lucene developers
  • Extensive documentation
  • There are many open source libraries available (including Django)

We are using this search engine at our project and very happy with it.

How do I convert between ISO-8859-1 and UTF-8 in Java?

Apache Commons IO Charsets class can come in handy:

String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())

How to enumerate an enum

There are two ways to iterate an Enum:

1. var values =  Enum.GetValues(typeof(myenum))
2. var values =  Enum.GetNames(typeof(myenum))

The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.

Use it in a foreach loop as below:

foreach(var value in values)
{
    // Do operations here
}

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

state machines tutorials

State machines are very simple in C if you use function pointers.

Basically you need 2 arrays - one for state function pointers and one for state transition rules. Every state function returns the code, you lookup state transition table by state and return code to find the next state and then just execute it.

int entry_state(void);
int foo_state(void);
int bar_state(void);
int exit_state(void);

/* array and enum below must be in sync! */
int (* state[])(void) = { entry_state, foo_state, bar_state, exit_state};
enum state_codes { entry, foo, bar, end};

enum ret_codes { ok, fail, repeat};
struct transition {
    enum state_codes src_state;
    enum ret_codes   ret_code;
    enum state_codes dst_state;
};
/* transitions from end state aren't needed */
struct transition state_transitions[] = {
    {entry, ok,     foo},
    {entry, fail,   end},
    {foo,   ok,     bar},
    {foo,   fail,   end},
    {foo,   repeat, foo},
    {bar,   ok,     end},
    {bar,   fail,   end},
    {bar,   repeat, foo}};

#define EXIT_STATE end
#define ENTRY_STATE entry

int main(int argc, char *argv[]) {
    enum state_codes cur_state = ENTRY_STATE;
    enum ret_codes rc;
    int (* state_fun)(void);

    for (;;) {
        state_fun = state[cur_state];
        rc = state_fun();
        if (EXIT_STATE == cur_state)
            break;
        cur_state = lookup_transitions(cur_state, rc);
    }

    return EXIT_SUCCESS;
}

I don't put lookup_transitions() function as it is trivial.

That's the way I do state machines for years.

What's the difference between nohup and ampersand

There are many cases when small differences between environments can bite you. This is one into which I have ran recently. What is the difference between these two commands?

1 ~ $ nohup myprocess.out &
2 ~ $ myprocess.out &

The answer is the same as usual - it depends.

nohup catches the hangup signal while the ampersand does not.

What is the hangup signal?

SIGHUP - hangup detected on controlling terminal or death of controlling process (value: 1).

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (like kill -SIGHUP $PID). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

Fine, but like in this case there are always ‘buts’. There is no difference between these launching methods when the shell is configured in a way where it does not send SIGHUP at all.

In case you are using bash, you can use the command specified below to find out whether your shell sends SIGHUP to its child processes or not:

~ $ shopt | grep hupon

And moreover - there are cases where nohup does not work. For example, when the process you start reconnects the NOHUP signal (it is done inside, on the application code level).

In the described case, lack of differences bit me when inside a custom service launching script there was a call to a second script which sets up and launches the proper application without a nohup command.

On one Linux environment everything worked smoothly, on a second one the application quit as soon as the second script exited (detecting that case, of course took me much more time then you might think :stuck_out_tongue:).

After adding nohup as a launching method to second script, application keeps running even if the scripts will exit and this behavior became consistent on both environments.

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

Linear regression with matplotlib / numpy

from pylab import * 

import numpy as np
x1 = arange(data) #for example this is a list
y1 = arange(data) #for example this is a list 
x=np.array(x) #this will convert a list in to an array
y=np.array(y)
m,b = polyfit(x, y, 1) 

plot(x, y, 'yo', x, m*x+b, '--k') 
show()

Do something if screen width is less than 960 px

I recommend to not use jQuery for such thing and proceed with window.innerWidth:

if (window.innerWidth < 960) {
    doSomething();
}

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

The steps I needed to perform were:

  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.

I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

App_Start\WebApiConfig.cs:

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Global.asax.cs:

using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Update 10.16.2015:

Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

How to get the MD5 hash of a file in C++?

There is a pretty library at http://256stuff.com/sources/md5/, with example of use. This is the simplest library for MD5.

Edit a commit message in SourceTree Windows (already pushed to remote)

Here are the steps to edit the commit message of a previous commit (which is not the most recent commit) using SourceTree for Windows version 1.5.2.0:

Step 1

Select the commit immediately before the commit that you want to edit. For example, if I want to edit the commit with message "FOOBAR!" then I need to select the commit that comes right before it:

Selecting commit before the one that I want to edit.

Step 2

Right-click on the selected commit and click Rebase children...interactively:

Selecting "Rebase children interactively".

Step 3

Select the commit that you want to edit, then click Edit Message at the bottom. In this case, I'm selecting the commit with the message "FOOBAR!":

Select the commit that you want to edit.

Step 4

Edit the commit message, and then click OK. In my example, I've added "SHAZBOT! SKADOOSH!"

Edit the commit message

Step 5

When you return to interactive rebase window, click on OK to finish the rebase:

Click OK to finish.

Step 6

At this point, you'll need to force-push your new changes since you've rebased commits that you've already pushed. However, the current 1.5.2.0 version of SourceTree for Windows does not allow you to force-push through the GUI, so you'll need to use Git from the command line anyways in order to do that.

Click Terminal from the GUI to open up a terminal.

Click Terminal

Step 7

From the terminal force-push with the following command,

git push origin <branch> -f

where <branch> is the name of the branch that you want to push, and -f means to force the push. The force push will overwrite your commits on your remote repo, but that's OK in your case since you said that you're not sharing your repo with other people.

That's it! You're done!

Access-control-allow-origin with multiple domains

For IIS 7.5+ you can use IIS CORS Module: https://www.iis.net/downloads/microsoft/iis-cors-module

Your web.config should be something like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="http://localhost:1506">
                <allowMethods>                    
                    <add method="GET" />
                    <add method="HEAD" />
                    <add method="POST" />
                    <add method="PUT" /> 
                    <add method="DELETE" /> 
                </allowMethods>
            </add>
            <add origin="http://localhost:1502">
                <allowMethods>
                    <add method="GET" />
                    <add method="HEAD" />
                    <add method="POST" />
                    <add method="PUT" /> 
                    <add method="DELETE" /> 
                </allowMethods>
            </add>
        </cors>
    </system.webServer>
</configuration>

You can find the configuration reference in here: https://docs.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference

How can I get the error message for the mail() function?

There is no error message associated with the mail() function. There is only a true or false returned on whether the email was accepted for delivery. Not whether it ultimately gets delivered, but basically whether the domain exists and the address is a validly formatted email address.

Why split the <script> tag when writing it with document.write()?

I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...

var newScript = document.createElement("script");
...

Casting variables in Java

Suppose you wanted to cast a String to a File (yes it does not make any sense), you cannot cast it directly because the File class is not a child and not a parent of the String class (and the compiler complains).

But you could cast your String to Object, because a String is an Object (Object is parent). Then you could cast this object to a File, because a File is an Object.

So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !

File f = (File)(Object) "Stupid cast";

The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:

Exception in thread "main" java.lang.ClassCastException:
    java.lang.String cannot be cast to java.io.File

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

just set position: fixed to the footer element (instead of relative)

Jsbin example

Note that you may need to also set a margin-bottom to the main element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

Setting the classpath in java using Eclipse IDE

You can create new User library,

On

"Configure Build Paths" page -> Add Library -> User Library (on list) -> User Libraries Button (rigth side of page)

and create your library and (add Jars buttons) include your specific Jars.

I hope this can help you.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Similar to the selected answer, a table source can be used, in this case a derived query:

delete from dd
from (
    select top 1 *
    from my_table
) dd

Feel free to add orderbys and conditions.

For the next example, I'll assume that the restriction on 'where' is due to not wanting to select a row based on its values. So assuming that we want to delete a row based on position (in this case the first position):

delete from dd
from (
    select
        *,
        row = row_number() over (order by (select 1))
    from my_table
) dd
where row = 1

Note that the (select 1) makes it the sort order that the tables or indexes are in. You can replace that with a newid to get fairly random rows.

You can also add a partition by to delete the top row of each color, for example.

Programmatically read from STDIN or input file in Perl

if(my $file = shift) { # if file is specified, read from that
  open(my $fh, '<', $file) or die($!);
  while(my $line = <$fh>) {
    print $line;
  }
}
else { # otherwise, read from STDIN
  print while(<>);
}

How to change a TextView's style at runtime

try this line of code.

textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD);

here , it will get current Typeface from this textview and replace it using new Typeface. New typeface here is DEFAULT_BOLD but you can apply many more.

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

How to insert data to MySQL having auto incremented primary key?

In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows. The database will supply a value for you.

INSERT INTO test.authors (
   instance_id,host_object_id,check_type,is_raw_check,
   current_check_attempt,max_check_attempts,state,state_type,
   start_time,start_time_usec,end_time,end_time_usec,command_object_id,
   command_args,command_line,timeout,early_timeout,execution_time,
   latency,return_code,output,long_output,perfdata
) VALUES (
   '1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
   '2012-01-03 12:50:59','198963','21','',
   '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
   '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
   '','rta=2.860000m=0%;80;100;0'
);

How disable / remove android activity label and label bar?

This one.

android:theme="@style/android:Theme.NoTitleBar"

How do I refresh the page in ASP.NET? (Let it reload itself by code)

If you don't want to do a full page refresh, then how about wrapping what you want to refresh inside of a UpdatePanel and then do an asynchronous postback?

How to urlencode data for curl command?

Here is my version for busybox ash shell for an embedded system, I originally adopted Orwellophile's variant:

urlencode()
{
    local S="${1}"
    local encoded=""
    local ch
    local o
    for i in $(seq 0 $((${#S} - 1)) )
    do
        ch=${S:$i:1}
        case "${ch}" in
            [-_.~a-zA-Z0-9]) 
                o="${ch}"
                ;;
            *) 
                o=$(printf '%%%02x' "'$ch")                
                ;;
        esac
        encoded="${encoded}${o}"
    done
    echo ${encoded}
}

urldecode() 
{
    # urldecode <string>
    local url_encoded="${1//+/ }"
    printf '%b' "${url_encoded//%/\\x}"
}

What is the purpose of the return statement?

Here is my understanding. (hope it will help someone and it's correct).

def count_number_of(x):
    count = 0
    for item in x:
        if item == "what_you_look_for":
        count = count + 1
    return count

So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0. If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change. I hope I got it right. Oh, and return is always inside a function.

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')

Chris

How to sort pandas data frame using values from several columns?

Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:

 import pandas as pd
 df = pd.read_csv('data.csv')
 df.sort_values(ascending=False,inplace=True)

Refer to the official website here.

Regex to extract substring, returning 2 results for some reason

I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

Get properties of a class

Other answers mainly get all name of object, to get value of property, you can use yourObj[name], for example:

var propNames = Object.getOwnPropertyNames(yourObj);
propNames.forEach(
    function(propName) {
        console.log(
           'name: ' + propName 
        + ' value: ' + yourObj[propName]);
    }
);

Large WCF web service request failing with (400) HTTP Bad Request

You can also turn on WCF logging for more information about the original error. This helped me solve this problem.

Add the following to your web.config, it saves the log to C:\log\Traces.svclog

<system.diagnostics>
    <sources>
        <source name="System.ServiceModel"
                  switchValue="Information, ActivityTracing"
                  propagateActivity="true">
            <listeners>
                <add name="traceListener"
                     type="System.Diagnostics.XmlWriterTraceListener"
                     initializeData= "c:\log\Traces.svclog" />
            </listeners>
        </source>
    </sources>
</system.diagnostics>

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

tar -cvzf filename.tar.gz directory_to_compress/

Most tar commands have a z option to create a gziped version.

Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,

tar -cvzf filename.bla directory_to_compress/

and then send the filename.bla - contents will would be a zipped tar, so at the other end it could be retrieved as usual.

Load external css file like scripts in jquery which is compatible in ie also

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

SQL Error: ORA-12899: value too large for column

As mentioned, the error message shows you the exact problem: you are passing 25 characters into a field set up to hold 20. You might also want to consider defining the columns a little more precisely. You can define whether the VARCHAR2 column will store a certain number of bytes or characters. You may encounter a problem in the future where you try to insert a multi byte character into the field, for example this is 5 characters in length but it won't fit into 5 bytes: 'ÀÈÌÕÛ'

Here is an example:

CREATE TABLE Customers(CustomerID  VARCHAR2(9 BYTE), ...

or

CREATE TABLE Customers(CustomerID  VARCHAR2(9 CHAR), ...

Where can I get a list of Countries, States and Cities?

The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html

How to block users from closing a window in Javascript?

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

"The public type <<classname>> must be defined in its own file" error in Eclipse

I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.

Adding delay between execution of two following lines

This line calls the selector secondMethod after 3 seconds:

[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];

Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:. It wont block the UI like sleep

Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay
{
    block = [block copy];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}

@end

Or perhaps even cleaner:

void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
      dispatch_get_current_queue(), block);
}

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

How should I remove all the leading spaces from a string? - swift

If you are wanting to remove spaces from the front (and back) but not the middle, you should use stringByTrimmingCharactersInSet

    let dirtyString   = " First Word "
    let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

If you want to remove spaces from anywhere in the string, then you might want to look at stringByReplacing...

How do I check if a variable is of a certain type (compare two types) in C?

This is crazily stupid, but if you use the code:

fprintf("%x", variable)

and you use the -Wall flag while compiling, then gcc will kick out a warning of that it expects an argument of 'unsigned int' while the argument is of type '____'. (If this warning doesn't appear, then your variable is of type 'unsigned int'.)

Best of luck!

Edit: As was brought up below, this only applies to compile time. Very helpful when trying to figure out why your pointers aren't behaving, but not very useful if needed during run time.

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

What is the difference between min SDK version/target SDK version vs. compile SDK version?

compileSdkVersion : The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device.

minSdkVersion : The min sdk version is the minimum version of the Android operating system required to run your application.

targetSdkVersion : The target sdk version is the version your app is targeted to run on.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

Have you tried using:

(status,output) = commands.getstatusoutput("ps aux")

I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..

After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2

My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.

I found that python was leaking file descriptors by just keeping an eye on it:

watch "ls /proc/$PYTHONPID/fd | wc -l"

Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...

Passing data through intent using Serializable

I extended ??s???? K's answer to make the code full and workable. So, when you finish filling your 'all_thumbs' list, you should put its content one by one into the bundle and then into the intent:

Bundle bundle = new Bundle();

for (int i = 0; i<all_thumbs.size(); i++)
bundle.putSerializable("extras"+i, all_thumbs.get(i));

intent.putExtras(bundle);

In order to get the extras from the intent, you need:

Bundle bundle = new Bundle();
List<Thumbnail> thumbnailObjects = new ArrayList<Thumbnail>();

// collect your Thumbnail objects
for (String key : bundle.keySet()) {
thumbnailObjects.add((Thumbnail) bundle.getSerializable(key));
}

// for example, in order to get a value of the 3-rd object you need to:
String label = thumbnailObjects.get(2).get_label();

Advantage of Serializable is its simplicity. However, I would recommend you to consider using Parcelable method when you need transfer many data, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

  1. an online tool - parcelabler
  2. a plugin for Android Studion - Android Parcelable code generator

MongoDB: Combine data from multiple collections into one..how?

Mongorestore has this feature of appending on top of whatever is already in the database, so this behavior could be used for combining two collections:

  1. mongodump collection1
  2. collection2.rename(collection1)
  3. mongorestore

Didn't try it yet, but it might perform faster than the map/reduce approach.

How would I extract a single file (or changes to a file) from a git stash?

If the stashed files need to merge with the current version so use the previous ways using diff. Otherwise you might use git pop for unstashing them, git add fileWantToKeep for staging your file, and do a git stash save --keep-index, for stashing everything except what is on stage. Remember that the difference of this way with the previous ones is that it "pops" the file from stash. The previous answers keep it git checkout stash@{0} -- <filename> so it goes according to your needs.

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

Command not found after npm install in zsh

If you have added using nvm please add the following to your .zshrc file and restart the terminal since the binaries of the file are not being detected by zsh shell we specify the path

export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I spent many hours spent tearing out my hair over this. The build output wasn't consistent; different projects would be "not up to date" for different reasons from one build to the next consecutive build. I eventually found that the culprit was DropBox (3.0.4). I junction my source folder from ...\DropBox into my projects folder (not sure if this is the reason), but DropBox somehow "touches" files during a build. Paused syncing and everything is consistently up-to-date.

Facebook Javascript SDK Problem: "FB is not defined"

There is solution for you :)

You must run your script after window loaded

if you use jQuery, you can use simple way:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            status     : true,
            version    : 'v2.5'
        });
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

<script>
$(window).load(function() {
    var comment_callback = function(response) {
        console.log("comment_callback");
        console.log(response);
    }
    FB.Event.subscribe('comment.create', comment_callback);
    FB.Event.subscribe('comment.remove', comment_callback);
});
</script>

Redirect to Action in another controller

You can supply the area in the routeValues parameter. Try this:

return RedirectToAction("LogIn", "Account", new { area = "Admin" });

Or

return RedirectToAction("LogIn", "Account", new { area = "" });

depending on which area you're aiming for.

Class has no initializers Swift

You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.

@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!

Read this doc, they explain it all nicely.

Pass a String from one Activity to another Activity in Android

You need to pass it as an extra:

String easyPuzzle  = "630208010200050089109060030"+
                     "008006050000187000060500900"+
                     "09007010681002000502003097";

Intent i = new Intent(this, ToClass.class);
i.putExtra("epuzzle", easyPuzzle);
startActivity(i); 

Then extract it from your new activity like this:

Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("epuzzle");

Convert character to ASCII numeric value in java

For this we could straight away use String classe's

    input.codePointAt(index);

I would like to give one more suggestion as to get whole of string converted to corresponding ascii codes, using java 8 for example, "abcde" to "979899100101".

    String input = "abcde";
    System.out.println(
            input.codePoints()
                    .mapToObj((t) -> "" + t)
                    .collect(joining()));

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

How to tell if browser/tab is active

In addition to Richard Simões answer you can also use the Page Visibility API.

if (!document.hidden) {
    // do what you need
}

This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.

Learn more (2019 update)

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Java swing application, close one window and open another when button is clicked

You can call dispose() on the current window and setVisible(true) on the one you want to display.

error C2065: 'cout' : undeclared identifier

If you started a project requiring the #include "stdafx.h" line, put it first.

How to get a value inside an ArrayList java

You should name your list cars instead of car, so that its name matches its content.

Then you can simply say cars.get(0).getPrice(). And if your Car class doesn't have this method yet, you need to create it.

Node.js: Gzip compression?

Use gzip compression

Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the compression middleware for gzip compression in your Express app. For example:

var compression = require('compression');
var express = require('express')
var app = express()
app.use(compression())

How to find children of nodes using BeautifulSoup

Yet another method - create a filter function that returns True for all desired tags:

def my_filter(tag):
    return (tag.name == 'a' and
        tag.parent.name == 'li' and
        'test' in tag.parent['class'])

Then just call find_all with the argument:

for a in soup(my_filter): # or soup.find_all(my_filter)
    print a

Can anonymous class implement interface?

Using Roslyn, you can dynamically create a class which inherits from an interface (or abstract class).

I use the following to create concrete classes from abstract classes.

In this example, AAnimal is an abstract class.

var personClass = typeof(AAnimal).CreateSubclass("Person");

Then you can instantiate some objects:

var person1 = Activator.CreateInstance(personClass);
var person2 = Activator.CreateInstance(personClass);

Without a doubt this won't work for every case, but it should be enough to get you started:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Publisher
{
    public static class Extensions
    {
        public static Type CreateSubclass(this Type baseType, string newClassName, string newNamespace = "Magic")
        {
            //todo: handle ref, out etc.
            var concreteMethods = baseType
                                    .GetMethods()
                                    .Where(method => method.IsAbstract)
                                    .Select(method =>
                                    {
                                        var parameters = method
                                                            .GetParameters()
                                                            .Select(param => $"{param.ParameterType.FullName} {param.Name}")
                                                            .ToString(", ");

                                        var returnTypeStr = method.ReturnParameter.ParameterType.Name;
                                        if (returnTypeStr.Equals("Void")) returnTypeStr = "void";

                                        var methodString = @$"
                                        public override {returnTypeStr} {method.Name}({parameters})
                                        {{
                                            Console.WriteLine(""{newNamespace}.{newClassName}.{method.Name}() was called"");
                                        }}";

                                        return methodString.Trim();
                                    })
                                    .ToList();

            var concreteMethodsString = concreteMethods
                                        .ToString(Environment.NewLine + Environment.NewLine);

            var classCode = @$"
            using System;

            namespace {newNamespace}
            {{
                public class {newClassName}: {baseType.FullName}
                {{
                    public {newClassName}()
                    {{
                    }}

                    {concreteMethodsString}
                }}
            }}
            ".Trim();

            classCode = FormatUsingRoslyn(classCode);


            /*
            var assemblies = new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(baseType.Assembly.Location),
            };
            */

            var assemblies = AppDomain
                        .CurrentDomain
                        .GetAssemblies()
                        .Where(a => !string.IsNullOrEmpty(a.Location))
                        .Select(a => MetadataReference.CreateFromFile(a.Location))
                        .ToArray();

            var syntaxTree = CSharpSyntaxTree.ParseText(classCode);

            var compilation = CSharpCompilation
                                .Create(newNamespace)
                                .AddSyntaxTrees(syntaxTree)
                                .AddReferences(assemblies)
                                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                //compilation.Emit($"C:\\Temp\\{newNamespace}.dll");

                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    var newTypeFullName = $"{newNamespace}.{newClassName}";

                    var type = assembly.GetType(newTypeFullName);
                    return type;
                }
                else
                {
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                        diagnostic.IsWarningAsError ||
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }

                    return null;
                }
            }
        }

        public static string ToString(this IEnumerable<string> list, string separator)
        {
            string result = string.Join(separator, list);
            return result;
        }

        public static string FormatUsingRoslyn(string csCode)
        {
            var tree = CSharpSyntaxTree.ParseText(csCode);
            var root = tree.GetRoot().NormalizeWhitespace();
            var result = root.ToFullString();
            return result;
        }
    }
}

How to access array elements in a Django template?

Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:

foo[bar]       # dictionary lookup
foo.bar        # attribute lookup
foo.bar()      # method call
foo[bar]       # list-index lookup

It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.

Bootstrap carousel multiple frames at once

Updated 2019...

Bootstrap 4

The carousel has changed in 4.x, and the multi-slide animation transitions can be overridden like this...

.carousel-inner .carousel-item-right.active,
.carousel-inner .carousel-item-next {
  transform: translateX(33.33%);
}

.carousel-inner .carousel-item-left.active, 
.carousel-inner .carousel-item-prev {
  transform: translateX(-33.33%)
}

.carousel-inner .carousel-item-right,
.carousel-inner .carousel-item-left{ 
  transform: translateX(0);
}

Bootstrap 4 Alpha.6 Demo
Bootstrap 4.0.0 (show 4, advance 1 at a time)
Bootstrap 4.1.0 (show 3, advance 1 at a time)
Bootstrap 4.1.0 (advance all 4 at once)
Bootstrap 4.3.1 responsive (show multiple, advance 1)new
Bootstrap 4.3.1 carousel with cardsnew


Another option is a responsive carousel that only shows and advances 1 slide on smaller screens, but shows multiple slides are larger screens. Instead of cloning the slides like the previous example, this one adjusts the CSS and use jQuery only to move the extra slides to allow for continuous cycling (wrap around):

Please don't just copy-and-paste this code. First, understand how it works.

Bootstrap 4 Responsive (show 3, 1 slide on mobile)

@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -33.3333%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

<div class="container-fluid">
    <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
        <div class="carousel-inner row w-100 mx-auto" role="listbox">
            <div class="carousel-item col-md-4 active">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7">
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
            <i class="fa fa-chevron-left fa-lg text-muted"></i>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
            <i class="fa fa-chevron-right fa-lg text-muted"></i>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>

Example - Bootstrap 4 Responsive (show 4, 1 slide on mobile)
Example - Bootstrap 4 Responsive (show 5, 1 slide on mobile)


Bootstrap 3

Here is a 3.x example on Bootply: http://bootply.com/89193

You need to put an entire row of images in the item active. Here is another version that doesn't stack the images at smaller screen widths: http://bootply.com/92514

EDIT Alternative approach to advance one slide at a time:

Use jQuery to clone the next items..

$('.carousel .item').each(function(){
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  if (next.next().length>0) {
    next.next().children(':first-child').clone().appendTo($(this));
  }
  else {
    $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
  }
});

And then CSS to position accordingly...

Before 3.3.1

.carousel-inner .active.left { left: -33%; }
.carousel-inner .next        { left:  33%; }

After 3.3.1

.carousel-inner .item.left.active {
  transform: translateX(-33%);
}
.carousel-inner .item.right.active {
  transform: translateX(33%);
}

.carousel-inner .item.next {
  transform: translateX(33%)
}
.carousel-inner .item.prev {
  transform: translateX(-33%)
}

.carousel-inner .item.right,
.carousel-inner .item.left { 
  transform: translateX(0);
}

This will show 3 at time, but only slide one at a time:

Bootstrap 3.x Demo


Please don't copy-and-paste this code. First, understand how it works. This answer is here to help you learn.

Doubling up this modified bootstrap 4 carousel only functions half correctly (scroll loop stops working)
how to make 2 bootstrap sliders in single page without mixing their css and jquery?
Bootstrap 4 Multi Carousel show 4 images instead of 3

CSS/HTML: What is the correct way to make text italic?

I'm no expert but I'd say that if you really want to be semantic, you should use vocabularies (RDFa).

This should result in something like that:

<em property="italic" href="http://url/to/a/definition_of_italic"> Your text </em>

em is used for the presentation (humans will see it in italic) and the property and href attributes are linking to a definition of what italic is (for machines).

You should check if there's a vocabulary for that kind of thing, maybe properties already exist.

More info about RDFa here: http://www.alistapart.com/articles/introduction-to-rdfa/

How can I format a list to print each element on a separate line in python?

Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:

from __future__ import print_function  # Py 2.6+; In Py 3k not needed

mylist = ['10', 12, '14']    # Note that 12 is an int

print(*mylist,sep='\n')

Prints:

10
12
14

Eventually, print as Python statement will go away... Might as well start to get used to it.

ORA-01036: illegal variable name/number when running query through C#

This error happens when you are also missing cmd.CommandType = System.Data.CommandType.StoredProcedure;

How to get the android Path string to a file on Assets folder?

You can use this method.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

In Kotlin (;D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }

Sum one number to every element in a list (or array) in Python

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

angularjs - ng-repeat: access key and value from JSON array object

Solution I have json object which has data

[{"name":"Ata","email":"[email protected]"}]

You can use following approach to iterate through ng-repeat and use table format instead of list.

<div class="container" ng-controller="fetchdataCtrl">    
  <ul ng-repeat="item in numbers">
    <li>            
      {{item.name}}: {{item.email}}
    </li>
  </ul>     
</div>

Serialize object to query string in JavaScript/jQuery

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);

Tensorflow image reading & display

(Can't comment, not enough reputation, but here is a modified version that worked for me)

To @HamedMP error about the No default session is registered you can use InteractiveSession to get rid of this error: https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession

And to @NumesSanguis issue with Image.show, you can use the regular PIL .show() method because fromarray returns an image object.

I do both below (note I'm using JPEG instead of PNG):

import tensorflow as tf
import numpy as np
from PIL import Image

filename_queue = tf.train.string_input_producer(['my_img.jpg']) #  list of files to read

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.

init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
    sess.run(init_op)

# Start populating the filename queue.

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

for i in range(1): #length of your filename list
  image = my_img.eval() #here is your image Tensor :) 

Image.fromarray(np.asarray(image)).show()

coord.request_stop()
coord.join(threads)

How to prevent downloading images and video files from my website?

Don't post them to your site.

Otherwise it is not possible.

How many socket connections possible?

depends on the application. if there is only a few packages from each client, 100K is very easy for linux. A engineer of my team had done a test years ago, the result shows : when there is no package from client after connection established, linux epoll can watch 400k fd for readablity at cpu usage level under 50%.

Get difference between two lists

The existing solutions all offer either one or the other of:

  • Faster than O(n*m) performance.
  • Preserve order of input list.

But so far no solution has both. If you want both, try this:

s = set(temp2)
temp3 = [x for x in temp1 if x not in s]

Performance test

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)

Results:

4.34620224079 # ars' answer
4.2770634955  # This answer
30.7715615392 # matt b's answer

The method I presented as well as preserving order is also (slightly) faster than the set subtraction because it doesn't require construction of an unnecessary set. The performance difference would be more noticable if the first list is considerably longer than the second and if hashing is expensive. Here's a second test demonstrating this:

init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''

Results:

11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer

Running a script inside a docker container using shell script

If you want to run the same command on multiple instances you can do this :

for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done

How to create an integer-for-loop in Ruby?

You can perform a simple each loop on the range from 1 to `x´:

(1..x).each do |i|
  #...
end

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

What's the difference between an id and a class?

Perhaps an analogy will help understanding the difference:

<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It's okay to put multiple students under one Class title, such as Biology. But it's never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

"Tomorrow, all students are to wear a red shirt to Biology class."

.Biology {
  color: red;
}

Or you can give rules to a Specific Student, by calling his unique ID:

"Jonathan Sampson is to wear a green shirt tomorrow."

#JonathanSampson {
  color: green;
}

In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.

The more specific selectors win.

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

How to merge rows in a column into one cell in excel?

In simple cases you can use next method which doesn`t require you to create a function or to copy code to several cells:

  1. In any cell write next code

    =Transpose(A1:A9) 
    

Where A1:A9 are cells you would like to merge.

  1. Without leaving the cell press F9

After that, the cell will contain the string:

={A1,A2,A3,A4,A5,A6,A7,A8,A9}

Source: http://www.get-digital-help.com/2011/02/09/concatenate-a-cell-range-without-vba-in-excel/

Update: One part can be ambiguous. Without leaving the cell means having your cell in editor mode. Alternatevly you can press F9 while are in cell editor panel (normaly it can be found above the spreadsheet)

Run a task every x-minutes with Windows Task Scheduler

After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

Should methods in a Java interface be declared with or without a public access modifier?

I would avoid to put modifiers that are applied by default. As pointed out, it can lead to inconsistency and confusion.

The worst I saw is an interface with methods declared abstract...

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

How to disable horizontal scrolling of UIScrollView?

Disable horizontal scrolling by overriding contentOffset property in subclass.

override var contentOffset: CGPoint {
  get {
    return super.contentOffset
  }
  set {
    super.contentOffset = CGPoint(x: 0, y: newValue.y)
  }
}

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

Reading an integer from user input

You could just go ahead and try :

    Console.WriteLine("1. Add account.");
    Console.WriteLine("Enter choice: ");
    int choice=int.Parse(Console.ReadLine());

That should work for the case statement.

It works with the switch statement and doesn't throw an exception.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

Metadata file '.dll' could not be found

Wow, it seems like this error can come from everywhere.

Anyway, I added a new WebAPI controller to my MVC application and it automagically got all the references from NuGet. Little bit later I removed the references from the NuGet UI, but I forgot to delete the files using them (i.e. System.Http).

For some reason, the error I was receiving was this, along with a simple warning about a variable not being used.

I commented out the variable to get rid at least of the warning and rebuilding pointed me out of all the files that were using the non-existing reference. After deleting those files, everything went OK.

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
    json:true
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

and the same for post

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Get controller and action name from within controller?

This seems to work nicely for me (so far), also works if you are using attribute routing.

public class BaseController : Controller
{
    protected string CurrentAction { get; private set; }
    protected string CurrentController { get; private set; }

    protected override void Initialize(RequestContext requestContext)
    {
        this.PopulateControllerActionInfo(requestContext);
    }

    private void PopulateControllerActionInfo(RequestContext requestContext)
    {
        RouteData routedata = requestContext.RouteData;

        object routes;

        if (routedata.Values.TryGetValue("MS_DirectRouteMatches", out routes))
        {
            routedata = (routes as List<RouteData>)?.FirstOrDefault();
        }

        if (routedata == null)
            return;

        Func<string, string> getValue = (s) =>
        {
            object o;
            return routedata.Values.TryGetValue(s, out o) ? o.ToString() : String.Empty;
        };

        this.CurrentAction = getValue("action");
        this.CurrentController = getValue("controller");
    }
}

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The only solution that worked for me and $.each was definitely causing the error. so i used for loop and it's not throwing error anymore.

Example code

     $.ajax({
            type: 'GET',
            url: 'https://example.com/api',
            data: { get_param: 'value' },
            success: function (data) {
                for (var i = 0; i < data.length; ++i) {
                    console.log(data[i].NameGerman);
                }
            }
        });

How to change the integrated terminal in visual studio code or VSCode

Probably it is too late but the below thing worked for me:

  1. Open Settings --> this will open settings.json
  2. type terminal.integrated.windows.shell
  3. Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
  4. Set the value as terminal.integrated.windows.shell: C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
  5. Click Ctrl + S

Try to open new terminal. It should open in bash editor in integrated mode.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

How do I remove leading whitespace in Python?

To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Try adding below code in build.gradle, it worked for me -

compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    multiDexEnabled true
}

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

You cannot concatenate raw strings like this. operator+ only works with two std::string objects or with one std::string and one raw string (on either side of the operation).

std::string s("...");
s + s; // OK
s + "x"; // OK
"x" + s; // OK
"x" + "x" // error

The easiest solution is to turn your raw string into a std::string first:

"Do you feel " + std::string(AGE) + " years old?";

Of course, you should not use a macro in the first place. C++ is not C. Use const or, in C++11 with proper compiler support, constexpr.

Assert equals between 2 Lists in Junit

Don't reinvent the wheel!

There's a Google Code library that does this for you: Hamcrest

[Hamcrest] Provides a library of matcher objects (also known as constraints or predicates) allowing 'match' rules to be defined declaratively, to be used in other frameworks. Typical scenarios include testing frameworks, mocking libraries and UI validation rules.

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

Gerrit error when Change-Id in commit messages are missing

Try this:

git commit --amend

Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a at the end of the file.

Save it and push it again!

How do I import material design library to Android Studio?

First, add the Material Design dependency.

implementation 'com.google.android.material:material:<version>'

To get the latest material design library version. check the official website github repository.

Current version is 1.2.0.

So, you have to add,

implementation 'com.google.android.material:material:1.2.0'

Then, you need to change the app theme to material theme by adding,

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.

Is there a way to SELECT and UPDATE rows at the same time?

in SQL 2008 a new TSQL statement "MERGE" is introduced which performs insert, update, or delete operations on a target table based on the results of a join with a source table. You can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.

http://blogs.msdn.com/ajaiman/archive/2008/06/25/tsql-merge-statement-sql-2008.aspx http://msdn.microsoft.com/en-us/library/bb510625.aspx

Ruby function to remove all white spaces?

I'm a bit late to the game, but I remove trailing and leading whitespaces by using strip!. If you have an array, such as I did, I needed to iterate through the array and save it after the instance ended. The ! took care of this. This removed all whitespaces at the end or the beginning, not just the first leading or the last trailing.

For example:

array = ["hello ","   Melanie", "is", " new ", "to  ", " programming"]
array.each do |i|
  i.strip!
end

This would output to: ["hello","Melanie", "is", "new ", "to", "programming"]. I further explored/shared this in a video I made to highlight this code for similar question I had.

I'm newer to programming and using strip did not work as it didn't save it to the array after the loop ended.

Replace part of a string in Python?

Use the replace() method on string:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'

How to get current foreground activity context in android?

For backwards compatibility:

ComponentName cn;
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
    cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
} else {
    //noinspection deprecation
    cn = am.getRunningTasks(1).get(0).topActivity;
}

How to Increase Import Size Limit in phpMyAdmin

this is due to file size import limit in phpmyadmin, default is very low, so you should increase upload_max_filesize you can change this in your php.ini, replaced with this

upload_max_filesize = 100M

What is pluginManagement in Maven's pom.xml?

You use pluginManagement in a parent pom to configure it in case any child pom wants to use it, but not every child plugin wants to use it. An example can be that your super pom defines some options for the maven Javadoc plugin.

Not each child pom might want to use Javadoc, so you define those defaults in a pluginManagement section. The child pom that wants to use the Javadoc plugin, just defines a plugin section and will inherit the configuration from the pluginManagement definition in the parent pom.

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

Use sudo with password as parameter

One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.

How to convert C++ Code to C

http://llvm.org/docs/FAQ.html#translatecxx

It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.

Usage sytax from the command line is as follows for version 9.0.1:

clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c  CPPtoC.bc -o CPPtoC.c

For older versions (unsure of transition version), use the following syntax:

llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c  CPPtoC.bc -o CPPtoC.c

Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.

Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.

EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.

The import android.support cannot be resolved

Please follow these Steps:

For Eclipse:

  • Go to your Project's Properties
  • Navigate to the Java Build Path
  • Then go to the Libraries tab. There click the Add External JARs Button on the Right pane.
  • Select the android-support-v4.jar file, usually the path for the Jar file is :
    YOUR_DRIVE\android-sdks\extras\android\support\v4\android-support-v4.jar
  • After adding android-support-v4.jar Library, navigate to the Order and Export tab and put check mark on the android-support-v4 Library file.
  • After doing the above, Clean the Project and Build it.
  • Problem Solved.

For Android Studio:

Short Version:

  • Add the following line to your build.gradle file:
    implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'

Long Version:

  • Go to File -> Project Structure

  • Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"

  • Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"

  • Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.

  • Rebuild your project and now everything should work.

Further reading regarding this Question:

  1. Support Library - Android Dev
  2. Recent Support Library Revisions
  3. Support Library Packages
  4. What is an Android Support Library?
  5. How Android Support Library work?

I hope this helps.

jQuery checkbox change and click event

Try this:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

Should I add the Visual Studio .suo and .user files to source control?

These files are user-specific options, which should be independent of the solution itself. Visual Studio will create new ones as necessary, so they do not need to be checked in to source control. Indeed, it would probably be better not to as this allows individual developers to customize their environment as they see fit.

How to make a dropdown readonly using jquery?

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

How to create a multiline UITextfield?

Use textView instead then conform with its delegate, call the textViewDidChange method inside of that method call tableView.beginUpdates() and tableView.endUpdates() and don't forget to set rowHeight and estimatedRowHeight to UITableView.automaticDimension.

Location of WSDL.exe

If you have Windows 10 and VS2019, and the .NET Framework 4.8, below you can see the Location of WSDL.exe

Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools

How to run a class from Jar which is not the Main-Class in its Manifest file

Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

MyJar1.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar

MyJar2.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar

etc. Then just run it with java -jar MyJar2.jar

Get first date of current month in java

import java.util.Date;
import java.text.SimpleDateFormat;

...
Date currentMonth = new Date();
String yyyyMM = new SimpleDateFormat("yyyyMM").format(currentMonth);
Date firstDateOfMonth = new SimpleDateFormat("yyyyMM").parse(yyyyMM);
...

my stupid solution. but it's work for me :D

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Python Selenium accessing HTML source

You can simply use the WebDriver object, and access to the page source code via its @property field page_source...

Try this code snippet :-)

from selenium import webdriver
driver = webdriver.Firefox('path/to/executable')
driver.get('https://some-domain.com')
source = driver.page_source
if 'stuff' in source:
    print('found...')
else:
    print('not in source...')

How to select/get drop down option in Selenium 2

in ruby for constantly using, add follow:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value
            option.click
              return
           end
       end
    end
  end
end

and you will be able to select value:

browser.find_element(:xpath, ".//xpath").select("Value")

How to declare string constants in JavaScript?

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
    Object.defineProperty(Constants , prop, {
      value: value,
      writable: false
   });
};

How to calculate the difference between two dates using PHP?

This will try to detect whether a timestamp was given or not, and will also return future dates/times as negative values:

<?php

function time_diff($start, $end = NULL, $convert_to_timestamp = FALSE) {
  // If $convert_to_timestamp is not explicitly set to TRUE,
  // check to see if it was accidental:
  if ($convert_to_timestamp || !is_numeric($start)) {
    // If $convert_to_timestamp is TRUE, convert to timestamp:
    $timestamp_start = strtotime($start);
  }
  else {
    // Otherwise, leave it as a timestamp:
    $timestamp_start = $start;
  }
  // Same as above, but make sure $end has actually been overridden with a non-null,
  // non-empty, non-numeric value:
  if (!is_null($end) && (!empty($end) && !is_numeric($end))) {
    $timestamp_end = strtotime($end);
  }
  else {
    // If $end is NULL or empty and non-numeric value, assume the end time desired
    // is the current time (useful for age, etc):
    $timestamp_end = time();
  }
  // Regardless, set the start and end times to an integer:
  $start_time = (int) $timestamp_start;
  $end_time = (int) $timestamp_end;

  // Assign these values as the params for $then and $now:
  $start_time_var = 'start_time';
  $end_time_var = 'end_time';
  // Use this to determine if the output is positive (time passed) or negative (future):
  $pos_neg = 1;

  // If the end time is at a later time than the start time, do the opposite:
  if ($end_time <= $start_time) {
    $start_time_var = 'end_time';
    $end_time_var = 'start_time';
    $pos_neg = -1;
  }

  // Convert everything to the proper format, and do some math:
  $then = new DateTime(date('Y-m-d H:i:s', $$start_time_var));
  $now = new DateTime(date('Y-m-d H:i:s', $$end_time_var));

  $years_then = $then->format('Y');
  $years_now = $now->format('Y');
  $years = $years_now - $years_then;

  $months_then = $then->format('m');
  $months_now = $now->format('m');
  $months = $months_now - $months_then;

  $days_then = $then->format('d');
  $days_now = $now->format('d');
  $days = $days_now - $days_then;

  $hours_then = $then->format('H');
  $hours_now = $now->format('H');
  $hours = $hours_now - $hours_then;

  $minutes_then = $then->format('i');
  $minutes_now = $now->format('i');
  $minutes = $minutes_now - $minutes_then;

  $seconds_then = $then->format('s');
  $seconds_now = $now->format('s');
  $seconds = $seconds_now - $seconds_then;

  if ($seconds < 0) {
    $minutes -= 1;
    $seconds += 60;
  }
  if ($minutes < 0) {
    $hours -= 1;
    $minutes += 60;
  }
  if ($hours < 0) {
    $days -= 1;
    $hours += 24;
  }
  $months_last = $months_now - 1;
  if ($months_now == 1) {
    $years_now -= 1;
    $months_last = 12;
  }

  // "Thirty days hath September, April, June, and November" ;)
  if ($months_last == 9 || $months_last == 4 || $months_last == 6 || $months_last == 11) {
    $days_last_month = 30;
  }
  else if ($months_last == 2) {
    // Factor in leap years:
    if (($years_now % 4) == 0) {
      $days_last_month = 29;
    }
    else {
      $days_last_month = 28;
    }
  }
  else {
    $days_last_month = 31;
  }
  if ($days < 0) {
    $months -= 1;
    $days += $days_last_month;
  }
  if ($months < 0) {
    $years -= 1;
    $months += 12;
  }

  // Finally, multiply each value by either 1 (in which case it will stay the same),
  // or by -1 (in which case it will become negative, for future dates).
  // Note: 0 * 1 == 0 * -1 == 0
  $out = new stdClass;
  $out->years = (int) $years * $pos_neg;
  $out->months = (int) $months * $pos_neg;
  $out->days = (int) $days * $pos_neg;
  $out->hours = (int) $hours * $pos_neg;
  $out->minutes = (int) $minutes * $pos_neg;
  $out->seconds = (int) $seconds * $pos_neg;
  return $out;
}

Example usage:

<?php
  $birthday = 'June 2, 1971';
  $check_age_for_this_date = 'June 3, 1999 8:53pm';
  $age = time_diff($birthday, $check_age_for_this_date)->years;
  print $age;// 28

Or:

<?php
  $christmas_2020 = 'December 25, 2020';
  $countdown = time_diff($christmas_2020);
  print_r($countdown);

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

Round to 5 (or other number) in Python

Here is my C code. If I understand it correctly, it should supposed to be something like this;

#include <stdio.h>

int main(){
int number;

printf("Enter number: \n");
scanf("%d" , &number);

if(number%5 == 0)
    printf("It is multiple of 5\n");
else{
    while(number%5 != 0)
        number++;
  printf("%d\n",number);
  }
}

and this also rounds to nearest multiple of 5 instead of just rounding up;

#include <stdio.h>

int main(){
int number;

printf("Enter number: \n");
scanf("%d" , &number);

if(number%5 == 0)
    printf("It is multiple of 5\n");
else{
    while(number%5 != 0)
        if (number%5 < 3)
            number--;
        else
        number++;
  printf("nearest multiple of 5 is: %d\n",number);
  }
}

Android - save/restore fragment state

Try this :

@Override
protected void onPause() {
    super.onPause();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}

@Override
protected void onResume() {
    super.onResume();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}

Hope this will help.

Also you can write this to activity tag in menifest file :

  android:configChanges="orientation|screenSize"

Good luck !!!

Convert Enum to String

Works for our project...

public static String convertToString(this Enum eff)
{
    return Enum.GetName(eff.GetType(), eff);
}

public static EnumType converToEnum<EnumType>(this String enumValue)  
{
    return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}

Binding multiple events to a listener (without JQuery)?

In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:

/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
  var events = eventNames.split(' ');
  for (var i=0, iLen=events.length; i<iLen; i++) {
    element.addEventListener(events[i], listener, false);
  }
}

addListenerMulti(window, 'mousemove touchmove', function(){…});

Hopefully it shows the concept.

Edit 2016-02-25

Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:

function addListenerMulti(el, s, fn) {
  s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}

A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.

map function for objects (instead of arrays)

const mapObject = (targetObject, callbackFn) => {
    if (!targetObject) return targetObject;
    if (Array.isArray(targetObject)){
        return targetObject.map((v)=>mapObject(v, callbackFn))
    }
    return Object.entries(targetObject).reduce((acc,[key, value]) => {
        const res = callbackFn(key, value);
        if (!Array.isArray(res) && typeof res ==='object'){
            return {...acc, [key]: mapObject(res, callbackFn)}
        }
        if (Array.isArray(res)){
            return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
        }
        return {...acc, [key]: res};
    },{})
};
const mapped = mapObject(a,(key,value)=> {
    if (!Array.isArray(value) && key === 'a') return ;
    if (!Array.isArray(value) && key === 'e') return [];
    if (!Array.isArray(value) && key === 'g') return value * value;
    return value;
});
console.log(JSON.stringify(mapped)); 
// {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}

This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined

jquery - How to determine if a div changes its height or any css attribute?

First, There is no such css-changes event out of the box, but you can create one by your own, as onchange is for :input elements only. not for css changes.

There are two ways to track css changes.

  1. Examine the DOM element for css changes every x time(500 milliseconds in the example).
  2. Trigger an event when you change the element css.
  3. Use the DOMAttrModified mutation event. But it's deprecated, so I'll skip on it.

First way:

var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
    if ($element.css('height') != lastHeight)
    {
        alert('xxx');
        lastHeight = $element.css('height'); 
    }

    setTimeout(checkForChanges, 500);
}

Second way:

$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


$("#btnSample1").click(function() {
    $("#mainContent").css('height', '400px');
    $("#mainContent").trigger('heightChange'); //<====
    ...
});    

If you control the css changes, the second option is a lot more elegant and efficient way of doing it.

Documentations:

  • bind: Description: Attach a handler to an event for the elements.
  • trigger: Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

I'm running MacOS Mojave 10.14.6, Xcode 11.3.1 and Transporter 1.1.1, and always got stuck at the Authentication with App Store stage, no matter how long I wait, I tried uploading using Xcode, using xcrun altool, Transporter, nada.

Finally I got it working by exporting the ipa file to a new Macbook (10.15.3, Xcode 11.3.1, Transporter 1.1.1), and used the Transporter app to upload it there.

The key difference is the Transporter tool on my new Macbook asked for a 6-digit code as authentication while the old Macbook did not, I suspect the authentication token on my old device expired but the system didn't ask for a new one when trying to upload the app. I had 2-FA enabled.

So I think forcing a manual re-authentication when you upload the app is the answer, the only other difference is the MacOS version, but I didn't test if it'll make a difference.

determine DB2 text string length

From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:

select * from table where length(RTRIM(fieldName))=10

UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:

select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890  ' as varchar(30)) )) 
as tab(fieldName)

FIELDNAME                      LEN_ONLY    LEN_RTRIM
------------------------------ ----------- -----------
1234567890                              12          10

One can test this by using this term:

where length(fieldName)!=length(rtrim(fieldName))

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

    JavascriptExecutor js = (JavascriptExecutor) driver;        
    js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");

I could add an attribute using the above code in java

How to get the date and time values in a C program?

To expand on the answer by Ori Osherov

You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:

You can get both the time and date by using the SYSTEMTIME struct. You also need to call one of two functions (either GetLocalTime() or GetSystemTime()) to fill out the struct.

GetLocalTime() will give you the time and date specific to your time zone.

GetSystemTime() will give you the time and date in UTC.

The SYSTEMTIME struct has the following members:

wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond and wMilliseconds

You then need to just access the struct in the regular way


Actual example code:

#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)

int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)

    SYSTEMTIME t; // Declare SYSTEMTIME struct

    GetLocalTime(&t); // Fill out the struct so that it can be used

    // Use GetSystemTime(&t) to get UTC time 

    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order

    return 0;
}

(Coded for simplicity and clarity, see the original answer for a better formatted method)

The output will be something like this:

Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572

Useful References:

All the WinAPI documentation (most already listed above):

An extremely good beginners tutorial on this subject by Zetcode:

Simple operations with datetime on Codeproject:


1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

You may have come to this question with MySQL version 8 installed (like me) and not found a satisfactory answer. You can no longer create users like this in version 8:

GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]' WITH GRANT OPTION;

The rather confusing error message that you get back is: ERROR 1410 (42000): You are not allowed to create a user with GRANT

In order to create users in version 8 you have to do it in two steps:

CREATE USER 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]';
GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' WITH GRANT OPTION;

Of course, if you prefer, you can also supply a limited number of privileges (instead of GRANT ALL PRIVILEGES), e.g. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

Wait until ActiveWorkbook.RefreshAll finishes - VBA

I have had a similar requirement. After a lot of testing I found a simple but not very elegant solution (not sure if it will work for you?)...

After my macro refresh's the data that Excel is getting, I added into my macro the line "Calculate" (normally used to recalculate the workbook if you have set calculation to manual).

While I don't need to do do this, it appears by adding this in, Excel waits while the data is refreshed before continuing with the rest of my macro.

How to change the icon of .bat file programmatically?

I'll assume you are talking about Windows, right? I don't believe you can change the icon of a batch file directly. Icons are embedded in .EXE and .DLL files, or pointed to by .LNK files.

You could try to change the file association, but that approach may vary based on the version of Windows you are using. This is down with the registry in XP, but I'm not sure about Vista.

OS X Bash, 'watch' command

Or, in your ~/.bashrc file:

function watch {
    while :; do clear; date; echo; $@; sleep 2; done
}

SELECT * FROM in MySQLi

This was already a month ago, but oh well.

I could be wrong, but for your question I get the feeling that bind_param isn't really the problem here. You always need to define some conditions, be it directly in the query string itself, of using bind_param to set the ? placeholders. That's not really an issue.

The problem I had using MySQLi SELECT * queries is the bind_result part. That's where it gets interesting. I came across this post from Jeffrey Way: http://jeff-way.com/2009/05/27/tricky-prepared-statements/(This link is no longer active). The script basically loops through the results and returns them as an array — no need to know how many columns there are, and you can still use prepared statements.

In this case it would look something like this:

$stmt = $mysqli->prepare(
  'SELECT * FROM tablename WHERE field1 = ? AND field2 = ?');
$stmt->bind_param('ss', $value, $value2);
$stmt->execute();

Then use the snippet from the site:

$meta = $stmt->result_metadata();

while ($field = $meta->fetch_field()) {
  $parameters[] = &$row[$field->name];
}

call_user_func_array(array($stmt, 'bind_result'), $parameters);

while ($stmt->fetch()) {
  foreach($row as $key => $val) {
    $x[$key] = $val;
  }
  $results[] = $x;
}

And $results now contains all the info from SELECT *. So far I found this to be an ideal solution.

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

Uninstall Eclipse under OSX?

Here is my list of things to delete for OSX Mountain Lion

~/.eclipse (folder);

~/Library/Saved Application/org.eclipse.eclipse.savedState;

~/Library/Preferences/org.eclipse.eclipse.plist;

~/Library/Caches/org.eclipse.eclipse;

... and of course the eclipse install folder

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

LaTeX Optional Arguments

Example from the guide:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

Programmatic equivalent of default(Type)

 /// <summary>
    /// returns the default value of a specified type
    /// </summary>
    /// <param name="type"></param>
    public static object GetDefault(this Type type)
    {
        return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null;
    }

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]
tac 
 22 

Or for a list:

> foo[["tac"]]
[1] 22

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Commands out of sync; you can't run this command now

Create two connections, use both separately

$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");

$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS"); 

When should I use the Visitor Design Pattern?

One way to look at it is that the visitor pattern is a way of letting your clients add additional methods to all of your classes in a particular class hierarchy.

It is useful when you have a fairly stable class hierarchy, but you have changing requirements of what needs to be done with that hierarchy.

The classic example is for compilers and the like. An Abstract Syntax Tree (AST) can accurately define the structure of the programming language, but the operations you might want to do on the AST will change as your project advances: code-generators, pretty-printers, debuggers, complexity metrics analysis.

Without the Visitor Pattern, every time a developer wanted to add a new feature, they would need to add that method to every feature in the base class. This is particularly hard when the base classes appear in a separate library, or are produced by a separate team.

(I have heard it argued that the Visitor pattern is in conflict with good OO practices, because it moves the operations of the data away from the data. The Visitor pattern is useful in precisely the situation that the normal OO practices fail.)

ShowAllData method of Worksheet class failed

The error ShowAllData method of Worksheet class failed usually occurs when you try to remove an applied filter when there is not one applied.

I am not certain if you are trying to remove the whole AutoFilter, or just remove any applied filter, but there are different approaches for each.

To remove an applied filter but leave AutoFilter on:

If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
End If

The rationale behind the above code is to test that there is an AutoFilter or whether a filter has been applied (this will also remove advanced filters).

To completely remove the AutoFilter:

ActiveSheet.AutoFilterMode = False

In the above case, you are simply disabling the AutoFilter completely.

How to vertically align an image inside a div

You could try setting the CSS of PI to display: table-cell; vertical-align: middle;

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

binary tree :

No need to consider values, we need to look at the structrue.

Given by (2 power n) - n

Eg: for three nodes it is (2 power 3) -3 = 8-3 = 5 different structrues

binary search tree:

We need to consider even the node values. We call it as Catalan Number

Given by 2n C n / n+1

HTML Tags in Javascript Alert() method

alert() is a method of the window object that cannot interpret HTML tags

how to convert object into string in php

Use the casting operator (string)$yourObject;

What's the difference between emulation and simulation?

Please forgive me if I'm wrong. And I have to admit upfront that I haven't done any research on these 2 terms. Anyway...

Emulation is to mimic something with detailed known results, whatever the internal behaviors actually are. We only try to get things done and don't care much about what goes on inside.

Simulation, on the other hand, is to mimic something with some known behaviors to study something not being known yet.

my 2cents

How to only get file name with Linux 'find'?

If you are using GNU find

find . -type f -printf "%f\n"

Or you can use a programming language such as Ruby(1.9+)

$ ruby -e 'Dir["**/*"].each{|x| puts File.basename(x)}'

If you fancy a bash (at least 4) solution

shopt -s globstar
for file in **; do echo ${file##*/}; done

How to put space character into a string name in XML?

This should work as well. Use quotes to maintain space

<string name="spelatonertext3">"-4,  5, -5,   6,  -6,"</string>

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

iOS start Background Thread

If you use performSelectorInBackground:withObject: to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.

You'd probably be better off using Grand Central Dispatch, though:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self getResultSetFromDB:docids];
});

GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.


Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.

VBA Public Array : how to?

Try this:

Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Unfortunately the code found online was VB.NET not VBA.

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.