Programs & Examples On #Conceptual

Conceptual questions involve programming problems which are not related to program code itself, but with algorithm logic and program architecture.

Post-increment and Pre-increment concept?

Post-increment:

int x, y, z;

x = 1;
y = x++; //this means: y is assigned the x value first, then increase the value of x by 1. Thus y is 1;
z = x; //the value of x in this line and the rest is 2 because it was increased by 1 in the above line. Thus z is 2.

Pre-increment:

int x, y, z;

x = 1;
y = ++x; //this means: increase the value of x by 1 first, then assign the value of x to y. The value of x in this line and the rest is 2. Thus y is 2.
z = x; //the value of x in this line is 2 as stated above. Thus z is 2.

Repeat command automatically in Linux

If you want to do something a specific number of times you can always do this:

repeat 300 do my first command here && sleep 1.5

rename the columns name after cbind the data

Try:

colnames(merger)[1] <- "Date"

Example

Here is a simple example:

a <- 1:10
b <- cbind(a, a, a)
colnames(b)

# change the first one
colnames(b)[1] <- "abc"

# change all colnames
colnames(b) <- c("aa", "bb", "cc")

What is the command to truncate a SQL Server log file?

For SQL 2008 you can backup log to nul device:

BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10

And then use DBCC SHRINKFILE to truncate the log file.

How to make an AlertDialog in Flutter?

showAlertDialog(BuildContext context, String message, String heading,
      String buttonAcceptTitle, String buttonCancelTitle) {
    // set up the buttons
    Widget cancelButton = FlatButton(
      child: Text(buttonCancelTitle),
      onPressed: () {},
    );
    Widget continueButton = FlatButton(
      child: Text(buttonAcceptTitle),
      onPressed: () {

      },
    );

    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      title: Text(heading),
      content: Text(message),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

called like:

showAlertDialog(context, 'Are you sure you want to delete?', "AppName" , "Ok", "Cancel");

Easy way to convert Iterable to Collection

With Guava you can use Lists.newArrayList(Iterable) or Sets.newHashSet(Iterable), among other similar methods. This will of course copy all the elements in to memory. If that isn't acceptable, I think your code that works with these ought to take Iterable rather than Collection. Guava also happens to provide convenient methods for doing things you can do on a Collection using an Iterable (such as Iterables.isEmpty(Iterable) or Iterables.contains(Iterable, Object)), but the performance implications are more obvious.

Set "Homepage" in Asp.Net MVC

Step 1: Click on Global.asax File in your Solution.

Step 2: Then Go to Definition of

RouteConfig.RegisterRoutes(RouteTable.Routes);

Step 3: Change Controller Name and View Name

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(name: "Default",
                        url: "{controller}/{action}/{id}",
                        defaults: new { controller = "Home", 
                                        action = "Index", 
                                        id = UrlParameter.Optional }
                        );
    }
}

TypeError: $.browser is undefined

I did solved using this jquery for Github

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Enabling error display in PHP via htaccess only

If you want to see only fatal runtime errors:

php_value display_errors on
php_value error_reporting 4

Facebook Graph API, how to get users email?

The email in the profile can be obtained using extended permission but I Guess it's not possible to get the email used to login fb. In my app i wanted to display mulitple fb accounts of a user in a list, i wanted to show the login emails of fb accounts as a unique identifier of the respective accounts but i couldn't get it off from fb, all i got was the primary email in the user profile but in my case my login email and my primary email are different.

Zabbix server is not running: the information displayed may not be current

As Zabbix Senior Instructor and Consultant Hernandes Martins says in his "Zabbix server is not running what to do?" blog post:

This is the first step that should be checked regardless of the situation, always view the logs, from the moment the error message appeared in the zabbix web interface always view the log.

By following his advice I could be able to identify the cause of the issue with my Zabbix server, and then apply the solution related to the specific problem.

In my case, as I've commented in the page:

The problem in my server was of "4. Resource Allocation Issues". Just like you wrote above, Zabbix was showing out of memory errors on the log when trying to start the server.

After increasing the value of parameter CacheSize I tried to restart the service, but it didn't respond. So, I ended up restarting the whole machine. Fortunately, in the end it resolved the problem for good.

So, take a look at the log with command tail -f /var/log/zabbix/zabbix_server.log on the terminal/prompt, watch for any errors, and tackle the problem according to what it makes sense for your particular case.

Codeigniter's `where` and `or_where`

You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.

$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->group_start() //this will start grouping
    ->where('library.available_until >=', date("Y-m-d H:i:s"))
    ->or_where('library.available_until =', "00-00-00 00:00:00")
    ->group_end() //this will end grouping
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id')

Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

Javascript, Change google map marker color

I have 4 ships to set on one single map, so I use the Google Developers example and then twisted it

https://developers.google.com/maps/documentation/javascript/examples/icon-complex

In the function bellow I set 3 more color options:

function setMarkers(map, locations) {
...
var image = {
    url: 'img/bullet_amarelo.png',
    // This marker is 20 pixels wide by 32 pixels tall.
    size: new google.maps.Size(40, 40),
    // The origin for this image is 0,0.
    origin: new google.maps.Point(0,0),
    // The anchor for this image is the base of the flagpole at 0,32.
    anchor: new google.maps.Point(0, 40)
  };
  var image1 = {
            url: 'img/bullet_azul.png',
            // This marker is 20 pixels wide by 32 pixels tall.
            size: new google.maps.Size(40, 40),
            // The origin for this image is 0,0.
            origin: new google.maps.Point(0,0),
            // The anchor for this image is the base of the flagpole at 0,32.
            anchor: new google.maps.Point(0, 40)
          };
  var image2 = {
          url: 'img/bullet_vermelho.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
  var image3 = {
          url: 'img/bullet_verde.png',
          // This marker is 20 pixels wide by 32 pixels tall.
          size: new google.maps.Size(40, 40),
          // The origin for this image is 0,0.
          origin: new google.maps.Point(0,0),
          // The anchor for this image is the base of the flagpole at 0,32.
          anchor: new google.maps.Point(0, 40)
        };
...
}

And in the FOR bellow I set one color for each ship:

for (var i = 0; i < locations.length; i++) {
...
    if (i==0) var imageV=image;
    if (i==1) var imageV=image1;
    if (i==2) var imageV=image2;
    if (i==3) var imageV=image3;
...
# remember to change icon: image to icon: imageV
}

The final result:

http://www.mercosul-line.com.br/site/teste.html

Sum a list of numbers in Python

Let us make it easy for Beginner:-

  1. The global keyword will allow the global variable message to be assigned within the main function without producing a new local variable
    message = "This is a global!"


def main():
    global message
    message = "This is a local"
    print(message)


main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope

This concept is called Shadowing

  1. Sum a list of numbers in Python
nums = [1, 2, 3, 4, 5]

var = 0


def sums():
    for num in nums:
        global var
        var = var + num
    print(var)


if __name__ == '__main__':
    sums()

Outputs = 15

td widths, not working?

This problem is quite easily solved using min-width and max-width within a css rule.

HTML

<table>
  <tr>
    <td class="name">Peter</td>
    <td class="hobby">Photography</td>
    <td class="comment">A long comment about something...</td>
  </td>
</table>

CSS

.name {
  max-width: 80px;
  min-width: 80px;
}

This will force the first column to be 80px wide. Usually I only use max-width without min-width to reign in text that is very occasionally too long from creating a table that has a super wide column that is mostly empty. The OP's question was about setting to a fixed width though, hence both rules together. On many browsers width:80px; in CSS is ignored for table columns. Setting the width within the HTML does work, but is not the way you should do things.

I would recommend using min and max width rules, and not set them the same but rather set a range. This way the table can do it's thing, but you can give it some hints on what to do with overly long content.

If I want to keep the text from wrapping and increasing the height of a row - but still make it possible for a user to see the full text, I use white-space: nowrap; on the main rule, then apply a hover rule that removes the width and nowrap rules so that the user can see the full content when they over their mouse over it. Something like this:

CSS

.name {
  max-width: 80px;
  white-space: nowrap;
  overflow: hidden;
}
.name:hover {
  max-width: none;
  white-space: normal;
  overflow:auto;
}

It just depends on exactly what you are trying to achieve. I hope this helps someone. PS As an aside, for iOS there is a fix for hover not working - see CSS Hover Not Working on iOS Safari and Chrome

Check if element is visible in DOM

The accepted answer did not worked for me.

Year 2020 breakdown.

  1. The (elem.offsetParent !== null) method works fine in Firefox but not in Chrome. In Chrome position: fixed will also make offsetParent return null even the element if visible in the page.

    User Phrogz conducted a large test (2,304 divs) on elements with varying properties to demonstrate the issue. https://stackoverflow.com/a/11639664/4481831 . Run it with multiple browsers to see the differences.

    Demo:

    _x000D_
    _x000D_
    //different results in Chrome and Firefox
    console.log(document.querySelector('#hidden1').offsetParent); //null Chrome & Firefox
    console.log(document.querySelector('#fixed1').offsetParent); //null in Chrome, not null in Firefox
    _x000D_
        <div id="hidden1" style="display:none;"></div>
        <div id="fixed1" style="position:fixed;"></div>
    _x000D_
    _x000D_
    _x000D_

  2. The (getComputedStyle(elem).display !== 'none') does not work because the element can be invisible because one of the parents display property is set to none, getComputedStyle will not catch that.

    Demo:

    _x000D_
    _x000D_
    var child1 = document.querySelector('#child1');
    console.log(getComputedStyle(child1).display);
    //child will show "block" instead of "none"
    _x000D_
    <div id="parent1" style="display:none;">
      <div id="child1" style="display:block"></div>
    </div>
    _x000D_
    _x000D_
    _x000D_

  3. The (elem.clientHeight !== 0). This method is not influenced by position: fixed and it also check if element parents are not-visible. But it has problems with simple elements that do not have a css layout, see more here

    Demo:

    _x000D_
    _x000D_
    console.log(document.querySelector('#div1').clientHeight); //not zero
    console.log(document.querySelector('#span1').clientHeight); //zero
    _x000D_
    <div id="div1">test1 div</div>
    <span id="span1">test2 span</span>
    _x000D_
    _x000D_
    _x000D_

  4. The (elem.getClientRects().length !== 0) may seem to solve the problems of the previous 3 methods. However it has problems with elements that use CSS tricks (other then display: none) to hide in the page.

    Demo

    _x000D_
    _x000D_
    console.log(document.querySelector('#notvisible1').getClientRects().length);
    console.log(document.querySelector('#notvisible1').clientHeight);
    console.log(document.querySelector('#notvisible2').getClientRects().length);
    console.log(document.querySelector('#notvisible2').clientHeight);
    console.log(document.querySelector('#notvisible3').getClientRects().length);
    console.log(document.querySelector('#notvisible3').clientHeight);
    _x000D_
    <div id="notvisible1" style="height:0; overflow:hidden; background-color:red;">not visible 1</div>
    
    <div id="notvisible2" style="visibility:hidden; background-color:yellow;">not visible 2</div>
    
    <div id="notvisible3" style="opacity:0; background-color:blue;">not visible 3</div>
    _x000D_
    _x000D_
    _x000D_

Conclusion.

So what I have showed you is that no method is perfect. To make a proper visibility check, you must use a combination of the last 3 methods.

Test if object implements interface

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

How to remove the bottom border of a box with CSS

You could just set the width to auto. Then the width of the div will equal 0 if it has no content.

width:auto;

How to cast int to enum in C++?

Test e = static_cast<Test>(1);

Hiding elements in responsive layout?

Bootstrap 4.x answer

hidden-* classes are removed from Bootstrap 4 beta onward.

If you want to show on medium and up use the d-* classes, e.g.:

<div class="d-none d-md-block">This will show in medium and up</div>

If you want to show only in small and below use this:

<div class="d-block d-md-none"> This will show only in below medium form factors</div>

Screen size and class chart

| Screen Size        | Class                          |
|--------------------|--------------------------------|
| Hidden on all      | .d-none                        |
| Hidden only on xs  | .d-none .d-sm-block            |
| Hidden only on sm  | .d-sm-none .d-md-block         |
| Hidden only on md  | .d-md-none .d-lg-block         |
| Hidden only on lg  | .d-lg-none .d-xl-block         |
| Hidden only on xl  | .d-xl-none                     |
| Visible on all     | .d-block                       |
| Visible only on xs | .d-block .d-sm-none            |
| Visible only on sm | .d-none .d-sm-block .d-md-none |
| Visible only on md | .d-none .d-md-block .d-lg-none |
| Visible only on lg | .d-none .d-lg-block .d-xl-none |
| Visible only on xl | .d-none .d-xl-block            |

Rather than using explicit .visible-* classes, you make an element visible by simply not hiding it at that screen size. You can combine one .d-*-none class with one .d-*-block class to show an element only on a given interval of screen sizes (e.g. .d-none.d-md-block.d-xl-none shows the element only on medium and large devices).

Documentation

__FILE__, __LINE__, and __FUNCTION__ usage in C++

__FUNCTION__ is non standard, __func__ exists in C99 / C++11. The others (__LINE__ and __FILE__) are just fine.

It will always report the right file and line (and function if you choose to use __FUNCTION__/__func__). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.

how to increase java heap memory permanently?

The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:

under Windows:

SET _JAVA_OPTIONS = -Xms512m -Xmx1024m

under Linux:

export _JAVA_OPTIONS="-Xms512m -Xmx1024m"

It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.

public class GetHeapSize {
    public static void main(String[]args){

        //Get the jvm heap size.
        long heapSize = Runtime.getRuntime().totalMemory();

        //Print the jvm heap size.
        System.out.println("Heap Size = " + heapSize);
    }
}

How to parse a JSON string into JsonNode in Jackson?

A third variant:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);

Importing images from a directory (Python) to list or dictionary

I'd start by using glob:

from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)

then do what you need to do with your list of images (image_list).

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

I tried out solution suggested by Russ Bateman Here in the post

http://localhost:8080/Myapp to http://localhost:8080/somepath/Myapp

But Didnt worked for me as I needed to have a *.war file that can hold the config and not the individual instance of server on my localmachine.

Reference

In order to do that I need jboss-web.xml placed in WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
 <!--
Copyright (c) 2008 Object Computing, Inc.
All rights reserved.
-->
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN"
"http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">

  <jboss-web>
  <context-root>somepath/Myapp</context-root>
  </jboss-web>

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

How to monitor the memory usage of Node.js?

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

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

How to know Hive and Hadoop versions from command prompt?

You can get Hive version

hive --version

if you want to know hive version and its related package versions.

rpm -qa|grep hive

Output will be like below.

libarchive2-2.5.5-5.19
hive-0.13.0.2.1.2.2-516
perl-Archive-Zip-1.24-2.7
hive-jdbc-0.13.0.2.1.2.2-516
webhcat-tar-hive-0.13.0.2.1.2.2_516-2
hive-webhcat-0.13.0.2.1.2.2-516
hive-hcatalog-0.13.0.2.1.2.2-516

Latter gives better understanding of hive and its dependents. Nevertheless rpm needs to be present.

Javascript Thousand Separator / string format

I use this:

function numberWithCommas(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

source: link

Get first key in a (possibly) associative array?

A one-liner:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'

Could not find or load main class

i had

':'

in my project name e.g 'HKUSTx:part-2' renaming it 'HKUSTx-part-2' worked for me

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

The first problem is that your query string is wrong:

I think this: "INSERT INTO employee(hans,germany) values(?,?)" should be like this: "INSERT INTO employee(name,country) values(?,?)"

The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.

You should add these to your code:

String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();

how to filter out a null value from spark dataframe

Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.

df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")

If you need to filter out rows that contain any null (OR connected) please use

df.na.drop()

Is it possible to change the speed of HTML's <marquee> tag?

On HTML5 the scrollamount and the scrolldelay attributes do not work. They are depricated attributes.

Looping from 1 to infinity in Python

def infinity():
    i=0
    while True:
        i+=1
        yield i


for i in infinity():
    if there_is_a_reason_to_break(i):
        break

Enable binary mode while restoring a Database from an SQL dump

I meet the same problem in windows restoring a dump file. My dump file was created with windows powershell and mysqldump like:

mysqldump db > dump.sql

The problem comes from the default encoding of powershell is UTF16. To look deeper into this, we can use "file" utility of GNU, and there exists a windows version here.
The output of my dump file is:

Little-endian UTF-16 Unicode text, with very long lines, with CRLF line terminators.

Then a conversion of coding system is needed, and there are various software can do this. For example in emacs,

M-x set-buffer-file-coding-system

then input required coding system such as utf-8.

And in the future, for a better mysqldump result, use:

mysqldump <dbname> -r <filename>

and then the output is handled by mysqldump itself but not redirection of powershell.

reference: https://dba.stackexchange.com/questions/44721/error-while-restoring-a-database-from-an-sql-dump

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

Issue:

.Net application code aborts before it starts its execution [Console application or Windows application]

Error received: Aborted with Error code "E0434352"

Exception: Unknown exception

Scenario 1:

When an application is already executed, which have used some of the dependent resources and those resources are still in use with the application executed, when another application or the same exe is triggered from some other source then one of the app throws the error

Scenario 2:

When an application is triggered by scheduler or automatic jobs, it may be in execution state at background, meanwhile when you try to trigger the same application again, the error may be triggered.

Solution:

Create an application, when & where the application release all its resources as soon as completed Kill all the background process once the application is closed Check and avoid executing the application from multiple sources like Batch Process, Task Scheduler and external tools at same time. Check for the Application and resource dependencies and clean up the code if needed.

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;
    }
}

// an intermediate class that just uses the trait
class IntClass {
    use A;
}

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

How to generate range of numbers from 0 to n in ES2015 only?

To support delta

const range = (start, end, delta) => {
  return Array.from(
    {length: (end - start) / delta}, (v, k) => (k * delta) + start
  )
};

Can't change z-index with JQuery

$(this).parent().css('z-index',3000);

How to "crop" a rectangular image into a square with CSS?

Assuming they do not have to be in IMG tags...

HTML:

<div class="thumb1">
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1:hover { YOUR HOVER STYLES HERE }

EDIT: If the div needs to link somewhere just adjust HTML and Styles like so:

HTML:

<div class="thumb1">
<a href="#">Link</a>
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1 a {
  display: block;
  width: 250px;
  height: 250px;
}

.thumb1 a:hover { YOUR HOVER STYLES HERE }

Note this could also be modified to be responsive, for example % widths and heights etc.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.

How can I capitalize the first letter of each word in a string using JavaScript?

Here's how you could do it with the map function basically, it does the same as the accepted answer but without the for-loop. Hence, saves you few lines of code.

_x000D_
_x000D_
function titleCase(text) {_x000D_
  if (!text) return text;_x000D_
  if (typeof text !== 'string') throw "invalid argument";_x000D_
_x000D_
  return text.toLowerCase().split(' ').map(value => {_x000D_
    return value.charAt(0).toUpperCase() + value.substring(1);_x000D_
  }).join(' ');_x000D_
}_x000D_
_x000D_
console.log(titleCase("I'm A little tea pot"));
_x000D_
_x000D_
_x000D_

PHP form - on submit stay on same page

You have to use code similar to this:

echo "<div id='divwithform'>";

if(isset($_POST['submit']))  // if form was submitted (if you came here with form data)
{
    echo "Success";
}
else                // if form was not submitted (if you came here without form data)
{
    echo "<form> ... </form>";
} 

echo "</div>";

Code with if like this is typical for many pages, however this is very simplified.

Normally, you have to validate some data in first "if" (check if form fields were not empty etc).

Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.

Solution to "subquery returns more than 1 row" error

Adding my answer, because it elaborates the idea that you can SELECT multiple columns from the table from which you subquery.

Here I needed the the most recently cast cote and it's associated information.

I first tried simply to SELECT the max(votedate) along with vote, itemid, userid etc., but while the query would return the max votedate, it would also return the a random row for the other information. Hard to see among a bunch of 1s and 0s.

This worked well:

$query = "  
    SELECT t1.itemid, t1.itemtext, t2.vote, t2.votedate, t2.userid 
    FROM
        (
        SELECT itemid, itemtext FROM oc_item ) t1
    LEFT JOIN 
        (
        SELECT vote, votedate, itemid,userid FROM oc_votes
        WHERE votedate IN 
        (select max(votedate) FROM oc_votes group by itemid)
        AND userid=:userid) t2
    ON (t1.itemid = t2.itemid)
    order by itemid ASC
";

The subquery in the WHERE clause WHERE votedate IN (select max(votedate) FROM oc_votes group by itemid) returns one record - the record with the max vote date.

Perl regular expression (using a variable as a search string with Perl operator characters included)

You can use quotemeta (\Q \E) if your Perl is version 5.16 or later, but if below you can simply avoid using a regular expression at all.

For example, by using the index command:

if (index($text_to_search, $search_string) > -1) {
    print "wee";
}

Delete element in a slice

In golang's wiki it show some tricks for slice, including delete an element from slice.

Link: enter link description here

For example a is the slice which you want to delete the number i element.

a = append(a[:i], a[i+1:]...)

OR

a = a[:i+copy(a[i:], a[i+1:])]

Add swipe to delete UITableViewCell

Swift 3:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // delete data and row
        dataList.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

Where does Hive store files in HDFS?

Another way to check where a specific table is stored would be execute this query on the hive interactive interface:

show create table table_name;

where table_name is the name of the subject table.

An example for the above query on 'customers' table would be something like this:

CREATE TABLE `customers`(
  `id` string, 
  `name` string)
COMMENT 'Imported by sqoop on 2016/03/01 13:01:49'
ROW FORMAT DELIMITED 
  FIELDS TERMINATED BY ',' 
  LINES TERMINATED BY '\n' 
STORED AS INPUTFORMAT 
  'org.apache.hadoop.mapred.TextInputFormat' 
OUTPUTFORMAT 
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'hdfs://quickstart.cloudera:8020/user/hive/warehouse/
   sqoop_workspace.db/customers'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='true', 
  'numFiles'='4', 
  'totalSize'='77', 
  'transient_lastDdlTime'='1456866115')

LOCATION in the example above is where you should focus on. That is your hdfs location for hive warehouse.

Don't forget to like if you like this solution. Cheers!

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

How to run a maven created jar file using just the command line

Just use the exec-maven-plugin.

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>com.example.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Then you run you program:

mvn exec:java

How do I create a slug in Django?

If you're using the admin interface to add new items of your model, you can set up a ModelAdmin in your admin.py and utilize prepopulated_fields to automate entering of a slug:

class ClientAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Client, ClientAdmin)

Here, when the user enters a value in the admin form for the name field, the slug will be automatically populated with the correct slugified name.

Is there a way to add a gif to a Markdown file?

in addition to all answers above:

if you want to use a gif for your github repository README.md and don't want to address it from your root directory, it's not enough if you just copy the url of your browser, for example your browser URL is sth like:

https://github.com/ashkan-nasirzadeh/simpleShell/blob/master/README%20assets/shell-gif.gif

but you should open your gif in your github account and right click on it and click copy image address or sth like that which is sth like this:

https://github.com/ashkan-nasirzadeh/simpleShell/blob/master/README%20assets/shell-gif.gif?raw=true

How to embed a Google Drive folder in a website

Google Drive folders can be embedded and displayed in list and grid views:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>


Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>



Q: What is a folder ID (FOLDER-ID) and how can I get it?

A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:

Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2

Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME in Chrome.

Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

As others said, it's a time change in 1927 in Shanghai.

It was 23:54:07 in Shanghai, in the local standard time, but then after 5 minutes and 52 seconds, it turned to the next day at 00:00:00, and then local standard time changed back to 23:54:08. So, that's why the difference between the two times is 343 seconds, not 1 second, as you would have expected.

The time can also mess up in other places like the US. The US has Daylight Saving Time. When the Daylight Saving Time starts the time goes forward 1 hour. But after a while, the Daylight Saving Time ends, and it goes backward 1 hour back to the standard time zone. So sometimes when comparing times in the US the difference is about 3600 seconds not 1 second.

But there is something different about these two-time changes. The latter changes continuously and the former was just a change. It didn't change back or change again by the same amount.

It's better to use UTC unless if needed to use non-UTC time like in display.

Why is "cursor:pointer" effect in CSS not working

Position the element as relative and then use z-index, it worked for me :)

How to semantically add heading to a list

Try defining a new class, ulheader, in css. p.ulheader ~ ul selects all that immediately follows My Header

p.ulheader ~ ul {
   margin-top:0;
{
p.ulheader {
   margin-bottom;0;
}

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

How to add jQuery to an HTML page?

Include javascript using script tags just before your ending body tag. Preferably you will want to put it in a separate file and link to it to keep things a little more organized and easier to read. Theres a simple article here that will show you how http://www.selftaughtweb.com/how-to-include-javascript/

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

Most popular C# Data Structures and Collections

  • Array
  • ArrayList
  • List
  • LinkedList
  • Dictionary
  • HashSet
  • Stack
  • Queue
  • SortedList

C#.NET has a lot of different data structures, for example, one of the most common ones is an Array. However C# comes with many more basic data structures. Choosing the correct data structure to use is part of writing a well structured and efficient program.

In this article I will go over the built-in C# data structures, including the new ones introduces in C#.NET 3.5. Note that many of these data structures apply for other programming languages.

Array

The perhaps simplest and most common data structure is the array. A C# array is basically a list of objects. Its defining traits are that all the objects are the same type (in most cases) and there is a specific number of them. The nature of an array allows for very fast access to elements based on their position within the list (otherwise known as the index). A C# array is defined like this:

[object type][] myArray = new [object type][number of elements]

Some examples:

 int[] myIntArray = new int[5];
 int[] myIntArray2 = { 0, 1, 2, 3, 4 };

As you can see from the example above, an array can be intialized with no elements or from a set of existing values. Inserting values into an array is simple as long as they fit. The operation becomes costly when there are more elements than the size of the array, at which point the array needs to be expanded. This takes longer because all the existing elements must be copied over to the new, bigger array.

ArrayList

The C# data structure, ArrayList, is a dynamic array. What that means is an ArrayList can have any amount of objects and of any type. This data structure was designed to simplify the processes of adding new elements into an array. Under the hood, an ArrayList is an array whose size is doubled every time it runs out of space. Doubling the size of the internal array is a very effective strategy that reduces the amount of element-copying in the long run. We won't get into the proof of that here. The data structure is very simple to use:

    ArrayList myArrayList = new ArrayList();
    myArrayList.Add(56);
    myArrayList.Add("String");
    myArrayList.Add(new Form());

The downside to the ArrayList data structure is one must cast the retrived values back into their original type:

int arrayListValue = (int)myArrayList[0]

Sources and more info you can find here :

Remove all whitespace in a string

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

How can the Euclidean distance be calculated with NumPy?

Here's some concise code for Euclidean distance in Python given two points represented as lists in Python.

def distance(v1,v2): 
    return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

ULIMIT configuration:

  1. Login by root
  2. vi security/limits.conf
  3. Make Below entry

    Ulimit configuration start for website user

    website   soft   nofile    8192
    website   hard   nofile    8192
    website   soft   nproc    4096
    website   hard   nproc    8192
    website   soft   core    unlimited
    website   hard   core    unlimited
    
  4. Make Below entry for ALL USER

    Ulimit configuration for every user

    *   soft   nofile    8192
    *   hard   nofile    8192
    *   soft   nproc    4096
    *   hard   nproc    8192
    *   soft   core    unlimited
    *   hard   core    unlimited
    
  5. After modifying the file, user need to logoff and login again to see the new values.

Preventing twitter bootstrap carousel from auto sliding on page load

The problem with carousel automatically sliding after prev/next button press is solved.

$('.carousel').carousel({
    pause: true,
    interval: false
});

GitHub commit 78b927b

How to Retrieve value from JTextField in Java Swing?

What I found helpful is this condition that is below.

String tempEmail = "";
JTextField tf1 = new JTextField();

tf1.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent evt){
         tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
    }
});

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

i think that special characters are # and @ only... query will list both.

DECLARE  @str VARCHAR(50) 
SET @str = '[azAB09ram#reddy@wer45' + CHAR(5) + 'a~b$' 
SELECT DISTINCT poschar 
FROM   MASTER..spt_values S 
       CROSS APPLY (SELECT SUBSTRING(@str,NUMBER,1) AS poschar) t 
WHERE  NUMBER > 0 
       AND NUMBER <= LEN(@str) 
       AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90 
                 OR ASCII(t.poschar) BETWEEN 97 AND 122 
                 OR ASCII(t.poschar) BETWEEN 48 AND 57) 

Change remote repository credentials (authentication) on Intellij IDEA 14

The easiest of all the above ways is to:

  1. Go to Settings>>Appearance & Behavior>>System Settings>>Passwords
  2. Change the setting to not store passwords at all
  3. Invalidate and restart IntelliJ
  4. Go to Settings>>Version Control>>Git>>SSH executable: Build-in
  5. Do a fetch/pull operation
  6. Enter the password when prompted
  7. Again go to Settings>>Appearance & Behavior>>System Settings>>Passwords
  8. This time select store passwords on disk(protected with master password)

Voila!

Note that this will not work if your password is in your URL itself. If that is the case then you need to follow the steps given by @moleksyuk here

You also choose to use the credentials helper option in IntelliJ to achieve similar functionality as suggested by Ramesh here

Keyword not supported: "data source" initializing Entity Framework Context

Make sure you have Data Source and not DataSource in your connection string. The space is important. Trust me. I'm an idiot.

Using a custom typeface in Android

Hey i also need 2 different fonts in my app for different widgeds! I use this way:

In my Application class i create an static method:

public static Typeface getTypeface(Context context, String typeface) {
    if (mFont == null) {
        mFont = Typeface.createFromAsset(context.getAssets(), typeface);
    }
    return mFont;
}

The String typeface represents the xyz.ttf in the asset folder. (i created an Constants Class) Now you can use this everywhere in your app:

mTextView = (TextView) findViewById(R.id.text_view);
mTextView.setTypeface(MyApplication.getTypeface(this, Constants.TYPEFACE_XY));

The only problem is, you need this for every widget where you want to use the Font! But i think this is the best way.

Check string for palindrome

/**
 * Check whether a word is a palindrome
 *
 * @param word the word
 * @param low  low index
 * @param high high index
 * @return {@code true} if the word is a palindrome;
 * {@code false} otherwise
 */
private static boolean isPalindrome(char[] word, int low, int high) {
    if (low >= high) {
        return true;
    } else if (word[low] != word[high]) {
        return false;
    } else {
        return isPalindrome(word, low + 1, high - 1);
    }
}

/**
 * Check whether a word is a palindrome
 *
 * @param the word
 * @return {@code true} if the word is a palindrome;
 * @code false} otherwise
 */
private static boolean isPalindrome(char[] word) {
    int length = word.length;
    for (int i = 0; i <= length / 2; i++) {
        if (word[i] != word[length - 1 - i]) {
            return false;
        }
    }
    return true;
}

public static void main(String[] args) {
    char[] word = {'a', 'b', 'c', 'b', 'a' };
    System.out.println(isPalindrome(word, 0, word.length - 1));
    System.out.println(isPalindrome(word));
}

Call a Vue.js component method from outside the component

Using Vue 3:

const app = createApp({})

// register an options object
app.component('my-component', {
  /* ... */
})

....

// retrieve a registered component
const MyComponent = app.component('my-component')

MyComponent.methods.greet();

https://v3.vuejs.org/api/application-api.html#component

Resolving require paths with webpack

I have resolve it with Webpack 2 like this:

module.exports = {
  resolve: {
    modules: ["mydir", "node_modules"]    
  }
}

You can add more directories to array...

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

DateTime.ToString() format that can be used in a filename or extension?

You can try with

var result = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss");

Concat all strings inside a List<string> using LINQ

This is for a string array:

string.Join(delimiter, array);

This is for a List<string>:

string.Join(delimiter, list.ToArray());

And this is for a list of custom objects:

string.Join(delimiter, list.Select(i => i.Boo).ToArray());

Angular pass callback function to child component as @Input similar to AngularJS way

An alternative to the answer Max Fahl gave.

You can define callback function as an arrow function in the parent component so that you won't need to bind that.

_x000D_
_x000D_
@Component({_x000D_
  ..._x000D_
  // unlike this, template: '<child [myCallback]="theCallback.bind(this)"></child>',_x000D_
  template: '<child [myCallback]="theCallback"></child>',_x000D_
  directives: [ChildComponent]_x000D_
})_x000D_
export class ParentComponent {_x000D_
_x000D_
   // unlike this, public theCallback(){_x000D_
   public theCallback = () => {_x000D_
    ..._x000D_
  }_x000D_
}_x000D_
_x000D_
@Component({...})_x000D_
export class ChildComponent{_x000D_
  //This will be bound to the ParentComponent.theCallback_x000D_
  @Input()_x000D_
  public myCallback: Function; _x000D_
  ..._x000D_
}
_x000D_
_x000D_
_x000D_

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

ViewerJS is helpful to view/embed openoffice format like odt,odp,ods and also pdf.

For embed openoffice/pdf document

<iframe src = "/ViewerJS/#../demo/ohm2013.odp" width='700' height='550' allowfullscreen webkitallowfullscreen></iframe>

/ViewerJS/ is the path of ViewerJS

#../demo/ohm2013 is the path of your file want to embed

allowing only alphabets in text box using java script

just use onkeypress event like below:

<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">

PHP - iterate on string characters

Step 1: convert the string to an array using the str_split function

$array = str_split($your_string);

Step 2: loop through the newly created array

foreach ($array as $char) {
 echo $char;
}

You can check the PHP docs for more information: str_split

How do I find the length of an array?

Is there a way to find how many values an array has?

Yes!

Try sizeof(array)/sizeof(array[0])

Detecting whether or not I've reached the end of an array would also work.

I dont see any way for this unless your array is an array of characters (i.e string).

P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.

CodeIgniter - accessing $config variable in view

You can do something like that:

$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');

How can I find a specific file from a Linux terminal?

Try this (via a shell):

update db
locate index.html

Or:

find /var -iname "index.html"

Replace /var with your best guess as to the directory it is in but avoid starting from /

The representation of if-elseif-else in EL using JSF

You can use EL if you want to work as IF:

<h:outputLabel value="#{row==10? '10' : '15'}"/>

Changing styles or classes:

style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"

class="#{test eq testMB.test? 'divRred' : 'divGreen'}"

error: command 'gcc' failed with exit status 1 while installing eventlet

For CentOS 7.2:

LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: CentOS
Description:    CentOS Linux release 7.2.1511 (Core) 
Release:    7.2.1511
Codename:   Core

Install eventlet:

sudo yum install python-devel
sudo easy_install -ZU eventlet

Terminal info:

[root@localhost ~]# easy_install -ZU eventlet
Searching for eventlet
Reading http://pypi.python.org/simple/eventlet/
Best match: eventlet 0.19.0
Downloading https://pypi.python.org/packages/5a/e8/ac80f330a80c18113df0f4f872fb741974ad2179f8c2a5e3e45f40214cef/eventlet-0.19.0.tar.gz#md5=fde857181347d5b7b921541367a99204
Processing eventlet-0.19.0.tar.gz
Running eventlet-0.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-Hh9GQY/eventlet-0.19.0/egg-dist-tmp-rBFoAx
Adding eventlet 0.19.0 to easy-install.pth file

Installed /usr/lib/python2.6/site-packages/eventlet-0.19.0-py2.6.egg
Processing dependencies for eventlet
Finished processing dependencies for eventlet

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

Python Brute Force algorithm

If you really want a bruteforce algorithm, don't save any big list in the memory of your computer, unless you want a slow algorithm that crashes with a MemoryError.

You could try to use itertools.product like this :

from string import ascii_lowercase
from itertools import product

charset = ascii_lowercase  # abcdefghijklmnopqrstuvwxyz
maxrange = 10


def solve_password(password, maxrange):
    for i in range(maxrange+1):
        for attempt in product(charset, repeat=i):
            if ''.join(attempt) == password:
                return ''.join(attempt)


solved = solve_password('solve', maxrange)  # This worked for me in 2.51 sec

itertools.product(*iterables) returns the cartesian products of the iterables you entered.

[i for i in product('bar', (42,))] returns e.g. [('b', 42), ('a', 42), ('r', 42)]

The repeat parameter allows you to make exactly what you asked :

[i for i in product('abc', repeat=2)]

Returns

[('a', 'a'),
 ('a', 'b'),
 ('a', 'c'),
 ('b', 'a'),
 ('b', 'b'),
 ('b', 'c'),
 ('c', 'a'),
 ('c', 'b'),
 ('c', 'c')]

Note:

You wanted a brute-force algorithm so I gave it to you. Now, it is a very long method when the password starts to get bigger because it grows exponentially (it took 62 sec to find the word 'solved').

What is difference between mutable and immutable String in java

In Java, all strings are immutable(Can't change). When you are trying to modify a String, what you are really doing is creating a new one.

Following ways we can create the string object

  1. Using String literal

    String str="java";
    
  2. Using new keyword

    String str = new String("java");
    
  3. Using character array

    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
    
    String helloString = new String(helloArray);   
    

coming to String immutability, simply means unmodifiable or unchangeable

Let's take one example

I'm initializing the value to the String literal s

String s="kumar";

Below I'm going to display the decimal representation of the location address using hashcode()

System.out.println(s.hashCode());

Simply printing the value of a String s

System.out.println("value "+s);

Okay, this time I'm inittializing value "kumar" to s1

String s1="kumar";   // what you think is this line, takes new location in the memory ??? 

Okay let's check by displaying hashcode of the s1 object which we created

System.out.println(s1.hashCode());

okay, let's check below code

String s2=new String("Kumar");
    System.out.println(s2.hashCode());  // why this gives the different address ??

Okay, check this below code at last

String s3=new String("KUMAR");
    System.out.println(s3.hashCode());  // again different address ???

YES, if you see Strings 's' and 's1' having the same hashcode because the value hold by 's' & 's1' are same that is 'kumar'

Let's consider String 's2' and 's3' these two Strings hashcode appears to be different in the sense, they both stored in a different location because you see their values are different.

since s and s1 hashcode is same because those values are same and storing in the same location.

Example 1: Try below code and analyze line by line

public class StringImmutable {
public static void main(String[] args) {

    String s="java";
    System.out.println(s.hashCode());
    String s1="javA";
    System.out.println(s1.hashCode());
    String s2=new String("Java");
    System.out.println(s2.hashCode());
    String s3=new String("JAVA");
    System.out.println(s3.hashCode());
}
}

Example 2: Try below code and analyze line by line

public class StringImmutable {
    public static void main(String[] args) {

        String s="java";
        s.concat(" programming");  // s can not be changed "immutablity"
        System.out.println("value of s "+s);
        System.out.println(" hashcode of s "+s.hashCode());

        String s1="java";
        String s2=s.concat(" programming");   // s1 can not be changed "immutablity" rather creates object s2
        System.out.println("value of s1 "+s1);
        System.out.println(" hashcode of s1 "+s1.hashCode());  

        System.out.println("value of s2 "+s2);
        System.out.println(" hashcode of s2 "+s2.hashCode());

    }
}

Okay, Let's look what is the difference between mutable and immutable.

mutable(it change) vs. immutable (it can't change)

public class StringMutableANDimmutable {
    public static void main(String[] args) {


        // it demonstrates immutable concept
        String s="java";
        s.concat(" programming");  // s can not be changed (immutablity)
        System.out.println("value of s ==  "+s); 
        System.out.println(" hashcode of s == "+s.hashCode()+"\n\n");


        // it demonstrates mutable concept
        StringBuffer s1= new StringBuffer("java");
        s1.append(" programming");  // s can be changed (mutablity)
        System.out.println("value of s1 ==  "+s1); 
        System.out.println(" hashcode of s1 == "+s1.hashCode());


    }
}

Any further questions?? please write on...

C pass int array pointer as parameter into a function

Maybe you were trying to do this?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Bootstrap modal: is not a function

I meet this error when integrate modal bootstrap in angular.

This is my solution to solve this issue.

I share for whom concern.

First step you need install jquery and bootstrap by npm command.

Second you need add declare var $ : any; in component

And use can use $('#myModal').modal('hide'); on onSave() method

Demo https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts

How to fix corrupted git repository?

I was facing the same issue, so I replaced the ".git" folder with a backed up version and it still wasn't working because .gitconfig file was corrupted. The BSOD on my laptop corrupted it. I replaced it with the following code and sourcetree restored all my repositories.

[user]
name = *your username*
email = *your email address*
[core]
autocrlf = true
excludesfile = C:\\Users\\*user name*\\Documents\\gitignore_global.txt

I don't know if this will help anybody, but this is just another solution that worked for me.

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

How to check currently internet connection is available or not in android

  public  boolean isInternetConnection()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            //we are connected to a network
            return  true;
        }
        else {
            return false;
        }
    }

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Golang append an item to a slice

In your example the slice argument of the Test function receives a copy of the variable a in the caller's scope.

Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test function you modify the slice descriptor held in the slice variable several times in a row, but this does not affect the caller and its a variable.

Inside the Test function, the first append reallocates the backing array under the slice variable, copies its original contents over, appends 100 to it, and that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references. (Jeff Lee is correct about that it's not what really happens, so the updated version follows; as he correctly states, this answer is correct, if maybe a bit too terse.)

Outside the Test function, a slice of length 7 and capacity 8 is allocated, and its 7 elements filled.
Inside the Test function, the first append sees the that the slice's capacity is still one element larger than its length — in other words, there is room for one more element to add without reallocation. So it "eats up" that remaining element and places 100 to it, after which it adjusts the length in the copy of the slice descriptor to become equal to the slice's capaticy. This does not affect the slice descriptor's in the caller's scope.

And that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references.

If you want to make Test behave like append, you have to return the new slice from it — just like append does — and require the callers of Test to use it in the same way they would use append:

func Test(slice []int) []int {
    slice = append(slice, 100)

    fmt.Println(slice)

    return slice
}

a = Test(a)

Please read this article thoroughly as it basically shows you how to implement append by hand, after explaining how slices are working internally. Then read this.

How to parse dates in multiple formats using SimpleDateFormat

Matt's approach above is fine, but please be aware that you will run into problems if you use it to differentiate between dates of the format y/M/d and d/M/y. For instance, a formatter initialised with y/M/d will accept a date like 01/01/2009 and give you back a date which is clearly not what you wanted. I fixed the issue as follows, but I have limited time and I'm not happy with the solution for 2 main reasons:

  1. It violates one of Josh Bloch's quidelines, specifically 'don't use exceptions to handle program flow'.
  2. I can see the getDateFormat() method becoming a bit of a nightmare if you needed it to handle lots of other date formats.

If I had to make something that could handle lots and lots of different date formats and needed to be highly performant, then I think I would use the approach of creating an enum which linked each different date regex to its format. Then use MyEnum.values() to loop through the enum and test with if(myEnum.getPattern().matches(date)) rather than catching a dateformatexception.

Anway, that being said, the following can handle dates of the formats 'y/M/d' 'y-M-d' 'y M d' 'd/M/y' 'd-M-y' 'd M y' and all other variations of those which include time formats as well:

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

public class DateUtil {
    private static final String[] timeFormats = {"HH:mm:ss","HH:mm"};
    private static final String[] dateSeparators = {"/","-"," "};

    private static final String DMY_FORMAT = "dd{sep}MM{sep}yyyy";
    private static final String YMD_FORMAT = "yyyy{sep}MM{sep}dd";

    private static final String ymd_template = "\\d{4}{sep}\\d{2}{sep}\\d{2}.*";
    private static final String dmy_template = "\\d{2}{sep}\\d{2}{sep}\\d{4}.*";

    public static Date stringToDate(String input){
    Date date = null;
    String dateFormat = getDateFormat(input);
    if(dateFormat == null){
        throw new IllegalArgumentException("Date is not in an accepted format " + input);
    }

    for(String sep : dateSeparators){
        String actualDateFormat = patternForSeparator(dateFormat, sep);
        //try first with the time
        for(String time : timeFormats){
        date = tryParse(input,actualDateFormat + " " + time);
        if(date != null){
            return date;
        }
        }
        //didn't work, try without the time formats
        date = tryParse(input,actualDateFormat);
        if(date != null){
        return date;
        }
    }

    return date;
    }

    private static String getDateFormat(String date){
    for(String sep : dateSeparators){
        String ymdPattern = patternForSeparator(ymd_template, sep);
        String dmyPattern = patternForSeparator(dmy_template, sep);
        if(date.matches(ymdPattern)){
        return YMD_FORMAT;
        }
        if(date.matches(dmyPattern)){
        return DMY_FORMAT;
        }
    }
    return null;
    }

    private static String patternForSeparator(String template, String sep){
    return template.replace("{sep}", sep);
    }

    private static Date tryParse(String input, String pattern){
    try{
        return new SimpleDateFormat(pattern).parse(input);
    }
    catch (ParseException e) {}
    return null;
    }


}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I've read in JQuery docs that data can be an array (key value pairs). I get the error if I put:

This is object not an array:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

You probably want:

var data = [{
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
}];

How to count the frequency of the elements in an unordered list?

#!usr/bin/python
def frq(words):
    freq = {}
    for w in words:
            if w in freq:
                    freq[w] = freq.get(w)+1
            else:
                    freq[w] =1
    return freq

fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()

Android - get children inside a View?

If you not only want to get all direct children but all children's children and so on, you have to do it recursively:

private ArrayList<View> getAllChildren(View v) {

    if (!(v instanceof ViewGroup)) {
        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        return viewArrayList;
    }

    ArrayList<View> result = new ArrayList<View>();

    ViewGroup vg = (ViewGroup) v;
    for (int i = 0; i < vg.getChildCount(); i++) {

        View child = vg.getChildAt(i);

        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        viewArrayList.addAll(getAllChildren(child));

        result.addAll(viewArrayList);
    }
    return result;
}

To use the result you could do something like this:

    // check if a child is set to a specific String
    View myTopView;
    String toSearchFor = "Search me";
    boolean found = false;
    ArrayList<View> allViewsWithinMyTopView = getAllChildren(myTopView);
    for (View child : allViewsWithinMyTopView) {
        if (child instanceof TextView) {
            TextView childTextView = (TextView) child;
            if (TextUtils.equals(childTextView.getText().toString(), toSearchFor)) {
                found = true;
            }
        }
    }
    if (!found) {
        fail("Text '" + toSearchFor + "' not found within TopView");
    }

Fastest method to replace all instances of a character in a string

I tried a number of these suggestions after realizing that an implementation I had written of this probably close to 10 years ago actually didn't work completely (nasty production bug in an long-forgotten system, isn't that always the way?!)... what I noticed is that the ones I tried (I didn't try them all) had the same problem as mine, that is, they wouldn't replace EVERY occurrence, only the first, at least for my test case of getting "test....txt" down to "test.txt" by replacing ".." with "."... maybe I missed so regex situation? But I digress...

So, I rewrote my implementation as follows. It's pretty darned simple, although I suspect not the fastest but I also don't think the difference will matter with modern JS engines, unless you're doing this inside a tight loop of course, but that's always the case for anything...

function replaceSubstring(inSource, inToReplace, inReplaceWith) {

  var outString = inSource;
  while (true) {
    var idx = outString.indexOf(inToReplace);
    if (idx == -1) {
      break;
    }
    outString = outString.substring(0, idx) + inReplaceWith +
      outString.substring(idx + inToReplace.length);
  }
  return outString;

}

Hope that helps someone!

Page Redirect after X seconds wait using JavaScript

Use JavaScript setInterval() method to redirect page after some specified time. The following script will redirect page after 5 seconds.

var count = 5;
setInterval(function(){
    count--;
    document.getElementById('countDown').innerHTML = count;
    if (count == 0) {
        window.location = 'https://www.google.com'; 
    }
},1000);

Example script and live demo can be found from here - Redirect page after delay using JavaScript

Right pad a string with variable number of spaces

Whammo blammo (for leading spaces):

SELECT 
    RIGHT(space(60) + cust_name, 60),
    RIGHT(space(60) + cust_address, 60)

OR (for trailing spaces)

SELECT
    LEFT(cust_name + space(60), 60),
    LEFT(cust_address + space(60), 60),

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

C++ error: "Array must be initialized with a brace enclosed initializer"

The syntax to statically initialize an array uses curly braces, like this:

int array[10] = { 0 };

This will zero-initialize the array.

For multi-dimensional arrays, you need nested curly braces, like this:

int cipher[Array_size][Array_size]= { { 0 } };

Note that Array_size must be a compile-time constant for this to work. If Array_size is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector).

check if "it's a number" function in Oracle

You can use the regular expression function 'regexp_like' in ORACLE (10g)as below:

select case
       when regexp_like(myTable.id, '[[:digit:]]') then
        case
       when myTable.id > 0 then
        'Is a number greater than 0'
       else
        'Is a number less than or equal to 0'
     end else 'it is not a number' end as valuetype
from table myTable

Static constant string (class member)

Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.

I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like

const std::string foo = "hello";

at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write

// class definition with incomplete static member could be in a header file
class A {
    static const char RECTANGLE[];
};

// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";

There! No heap allocation, no copying, no dynamic initialization.

Cheers, s.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

jQuery: value.attr is not a function

You are dealing with the raw DOM element .. need to wrap it in a jquery object

console.info("cat_id: ",$(value).attr('cat_id'));

force Maven to copy dependencies into target/lib

If you make your project a war or ear type maven will copy the dependencies.

Is the 'as' keyword required in Oracle to define an alias?

Both are correct. Oracle allows the use of both.

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

To see all tables:

.tables

To see a particular table:

.schema [tablename]

Kill all processes for a given user

Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

pkill -9 -u `id -u username`

Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

openCV video saving in python

Try this. It's working for me (Windows 10).

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

Can I give a default value to parameters or optional parameters in C# functions?

Yes. See Named and Optional Arguments. Note that the default value needs to be a constant, so this is OK:

public string Foo(string myParam = "default value") // constant, OK
{
}

but this is not:

public void Bar(string myParam = Foo()) // not a constant, not OK
{
}

jquery find element by specific class when element has multiple classes

you are looking for http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture

How remove border around image in css?

img need src to use border is remover, i no know a why css is crazy

data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7

So try example with SRC:

_x000D_
_x000D_
img.logo {_x000D_
 width: 200px;_x000D_
    height: 50px;_x000D_
 background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;_x000D_
}
_x000D_
<img class="logo" src="data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7">
_x000D_
_x000D_
_x000D_

So try example without SRC:

_x000D_
_x000D_
img.logo {_x000D_
 width: 200px;_x000D_
    height: 50px;_x000D_
 background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;_x000D_
}
_x000D_
<img class="logo">
_x000D_
_x000D_
_x000D_

lol... css crazy! good fun

What's the safest way to iterate through the keys of a Perl hash?

One thing you should be aware of when using each is that it has the side effect of adding "state" to your hash (the hash has to remember what the "next" key is). When using code like the snippets posted above, which iterate over the whole hash in one go, this is usually not a problem. However, you will run into hard to track down problems (I speak from experience ;), when using each together with statements like last or return to exit from the while ... each loop before you have processed all keys.

In this case, the hash will remember which keys it has already returned, and when you use each on it the next time (maybe in a totaly unrelated piece of code), it will continue at this position.

Example:

my %hash = ( foo => 1, bar => 2, baz => 3, quux => 4 );

# find key 'baz'
while ( my ($k, $v) = each %hash ) {
    print "found key $k\n";
    last if $k eq 'baz'; # found it!
}

# later ...

print "the hash contains:\n";

# iterate over all keys:
while ( my ($k, $v) = each %hash ) {
    print "$k => $v\n";
}

This prints:

found key bar
found key baz
the hash contains:
quux => 4
foo => 1

What happened to keys "bar" and baz"? They're still there, but the second each starts where the first one left off, and stops when it reaches the end of the hash, so we never see them in the second loop.

Differences between Ant and Maven

Ant is mainly a build tool.

Maven is a project and dependencies management tool (which of course builds your project as well).

Ant+Ivy is a pretty good combination if you want to avoid Maven.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Access a URL and read Data with R

Beside of read.csv(url("...")) you also can use read.table("http://...").

Example:

> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
                V1   V2   V3   V4 V5
1        Rochester 19.0 20.6 15.0  E
2         Syracuse 17.0 15.6 20.2  E
...
43         Atlanta  4.2 70.6 32.6  S
> 

Trim characters in Java

My solution:

private static String trim(String string, String charSequence) {
        var str = string;
        str = str.replace(" ", "$SAVE_SPACE$").
                  replace(charSequence, " ").
                  trim().
                  replace(" ", charSequence).
                  replace("$SAVE_SPACE$", " ");
        return str;
    }

Which one is the best PDF-API for PHP?

http://sourceforge.net/projects/html2ps/, is the best if you need the css and 3c compatibily.

if you can install software on your server, i suggest you to use http://wkhtmltopdf.org/.

There is also a drupal module using wkhtmltopdf :)

PHP take many resources to convert html in pdf, imho, php is not the right language to do that (if you expect a large numbers of coversion or large files to convert)

Iterating through array - java

You should definitely encapsulate this logic into a method.

There is no benefit to repeating identical code multiple times.

Also, if you place the logic in a method and it changes, you only need to modify your code in one place.

Whether or not you want to use a 3rd party library is an entirely different decision.

Load Image from javascript

Try this.You have some symbols in $imageUrl

<img id="id1" src="$imageUrl" onload="javascript:showImage();">

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

Add a linebreak in an HTML text area

If it's not vb you can use &#013;&#010; (ascii codes for cr,lf)

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

ImportError: No module named tensorflow

In my case, I install 32 Bit Python so I cannot install Tensorflow, After uninstall 32 Bit Python and install 64 Bit Python, I can install tensorflow successfully.

After reinstall Python 64 bit, you need to check your python install folder path is properly set in Windows Environment Path.

You can check Python version by typing python in cmd.

Password encryption/decryption code in .NET

EDIT: this is a very old answer. SHA1 was deprecated in 2011 and has now been broken in practice. https://shattered.io/ Use a newer standard instead (e.g. SHA256, SHA512, etc).

If your answer to the question in my comment is "No", here's what I use:

    public static byte[] HashPassword(string password)
    {
        var provider = new SHA1CryptoServiceProvider();
        var encoding = new UnicodeEncoding();
        return provider.ComputeHash(encoding.GetBytes(password));
    }

How to remove a package from Laravel using composer?

In case the given answers still don't help you remove that, try this:

  • Manually delete the line in require from composer.json

  • Run composer update

Return list using select new in LINQ

public List<Object> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
     {
         var query = from pro in db.Projects
                     select new {pro.ProjectName,pro.ProjectId};

         return query.ToList<Object>();
    }
}

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

Can I force a UITableView to hide the separator between empty cells?

Using the link from Daniel, I made an extension to make it more usable:

//UITableViewController+Ext.m
- (void)hideEmptySeparators
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    v.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:v];
    [v release];
}

After some testings, I found out that the size can be 0 and it works as well. So it doesn't add some kind of margin at the end of the table. So thanks wkw for this hack. I decided to post that here since I don't like redirect.

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

Zooming MKMapView to fit annotation pins?

Based on answers above you can use universal method to zoom map to fit all annotations and overlays at the same time.

-(MKMapRect)getZoomingRectOnMap:(MKMapView*)map toFitAllOverlays:(BOOL)overlays andAnnotations:(BOOL)annotations includeUserLocation:(BOOL)userLocation {
    if (!map) {
        return MKMapRectNull;
    }

    NSMutableArray* overlaysAndAnnotationsCoordinateArray = [[NSMutableArray alloc]init];        
    if (overlays) {
        for (id <MKOverlay> overlay in map.overlays) {
            MKMapPoint overlayPoint = MKMapPointForCoordinate(overlay.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:overlayPoint.x], [NSNumber numberWithDouble:overlayPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    if (annotations) {
        for (id <MKAnnotation> annotation in map.annotations) {
            MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:annotationPoint.x], [NSNumber numberWithDouble:annotationPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    MKMapRect zoomRect = MKMapRectNull;
    if (userLocation) {
        MKMapPoint annotationPoint = MKMapPointForCoordinate(map.userLocation.coordinate);
        zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
    }

    for (NSArray* coordinate in overlaysAndAnnotationsCoordinateArray) {
        MKMapRect pointRect = MKMapRectMake([coordinate[0] doubleValue], [coordinate[1] doubleValue], 0.1, 0.1);
        zoomRect = MKMapRectUnion(zoomRect, pointRect);
    }

    return zoomRect;
}

And then:

MKMapRect mapRect = [self getZoomingRectOnMap:mapView toFitAllOverlays:YES andAnnotations:YES includeUserLocation:NO];
[mapView setVisibleMapRect:mapRect edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:YES];

Difference between TCP and UDP?

Short and simple differences between Tcp and Udp protocol:

1) Tcp - Transmission control protocol and Udp - User datagram protocol.

2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.

3) Tcp is a stream oriented, where as Udp is a message oriented protocol.

4) Tcp is a slower than Udp.

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

Switching to landscape mode in Android Emulator

Just a little bug (Bug for me) I found on mac emulator.

On changing the orientation to landscape (CtrlCmdF11) it changes to landscape but content shows in portrait format.for that:

Go to emulator: Settings-> Display->When device is rotated->Rotate the contents of the screen

Work with a time span in Javascript

/**
 * ??????????????,???????? 
 * English: Calculating the difference between the given time and the current time and then showing the results.
 */
function date2Text(date) {
    var milliseconds = new Date() - date;
    var timespan = new TimeSpan(milliseconds);
    if (milliseconds < 0) {
        return timespan.toString() + "??";
    }else{
        return timespan.toString() + "?";
    }
}

/**
 * ???????????
 * English: Using a function to calculate the time interval
 * @param milliseconds ???
 */
var TimeSpan = function (milliseconds) {
    milliseconds = Math.abs(milliseconds);
    var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
    milliseconds -= days * (1000 * 60 * 60 * 24);

    var hours = Math.floor(milliseconds / (1000 * 60 * 60));
    milliseconds -= hours * (1000 * 60 * 60);

    var mins = Math.floor(milliseconds / (1000 * 60));
    milliseconds -= mins * (1000 * 60);

    var seconds = Math.floor(milliseconds / (1000));
    milliseconds -= seconds * (1000);
    return {
        getDays: function () {
            return days;
        },
        getHours: function () {
            return hours;
        },
        getMinuts: function () {
            return mins;
        },
        getSeconds: function () {
            return seconds;
        },
        toString: function () {
            var str = "";
            if (days > 0 || str.length > 0) {
                str += days + "?";
            }
            if (hours > 0 || str.length > 0) {
                str += hours + "??";
            }
            if (mins > 0 || str.length > 0) {
                str += mins + "??";
            }
            if (days == 0 && (seconds > 0 || str.length > 0)) {
                str += seconds + "?";
            }
            return str;
        }
    }
}

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

My own solution on Linux (under ~/.config/smartgit/19.1) is to comment or remove line listx from preferences.yml file and reopen program.

Deleting the all folders will make you reconfigure everything (useless).

Javascript parse float is ignoring the decimals after my comma

Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language:

Globalize.parseFloat('0,04'); // 0.04

Some links on stackoverflow to look into:

How to get all elements inside "div" that starts with a known text

Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:

function fillArray(vector1,vector2){
    for (var i = 0; i < vector1.length; i++){
        if (vector1[i].id.indexOf('q17_') == 0)
            vector2.push(vector1[i]);
        if(vector1[i].tagName == 'DIV')
            fillArray (document.getElementById(vector1[i].id).children,vector2);
    }
}

function selectAllElementsInsideDiv(divId){ 
    var matches = new Array();
    var searchEles = document.getElementById(divId).children;
    fillArray(searchEles,matches);
    return matches;
}

Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:

var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv =  selectAllElementsInsideDiv('myDiv')

I have tested it and it worked for me. I hope it helps you.

Using the slash character in Git branch name

Are you sure branch labs does not already exist (as in this thread)?

You can't have both a file, and a directory with the same name.

You're trying to get git to do basically this:

% cd .git/refs/heads
% ls -l
total 0
-rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 labs
-rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 master
% mkdir labs
mkdir: cannot create directory 'labs': File exists

You're getting the equivalent of the "cannot create directory" error.
When you have a branch with slashes in it, it gets stored as a directory hierarchy under .git/refs/heads.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

This is kind of stupid, but I got this error message by accidentally using [formControl] instead of [formGroup]. See here:

WRONG

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formControl]="formGroup"> <!-- '[formControl]' IS THE WRONG ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

RIGHT

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formGroup]="formGroup"> <!-- '[formGroup]' IS THE RIGHT ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

How to find the size of an int[]?

You have to use sizeof() function.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);

      int arr[] ={5, 3, 6, 7};

      int size = sizeof(arr) / sizeof(arr[0]);
      cout<<size<<endl;

      return 0;
}

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Parse an URL in JavaScript

got it from google, try to use this method

function getQuerystring2(key, default_) 
{ 
    if (default_==null) 
    { 
        default_=""; 
    } 
    var search = unescape(location.search); 
    if (search == "") 
    { 
        return default_; 
    } 
    search = search.substr(1); 
    var params = search.split("&"); 
    for (var i = 0; i < params.length; i++) 
    { 
        var pairs = params[i].split("="); 
        if(pairs[0] == key) 
        { 
            return pairs[1]; 
        } 
    } 


return default_; 
}

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Is it possible to style html5 audio tag?

Yes! The HTML5 audio tag with the "controls" attribute uses the browser's default player. You can customize it to your liking by not using the browser controls, but rolling your own controls and talking to the audio API via javascript.

Luckily, other people have already done this. My favorite player right now is jPlayer, it is very stylable and works great. Check it out.

sh: react-scripts: command not found after running npm start

Tried all of the above and nothing worked so I used npm i react-scripts and it worked

MAC addresses in JavaScript

I concur with all the previous answers that it would be a privacy/security vulnerability if you would be able to do this directly from Javascript. There are two things I can think of:

  • Using Java (with a signed applet)
  • Using signed Javascript, which in FF (and Mozilla in general) gets higher privileges than normal JS (but it is fairly complicated to set up)

How to get the last character of a string in a shell?

For anyone interested in a pure POSIX method:

https://github.com/spiralofhope/shell-random/blob/master/live/sh/scripts/string-fetch-last-character.sh

#!/usr/bin/env  sh

string_fetch_last_character() {
  length_of_string=${#string}
  last_character="$string"
  i=1
  until [ $i -eq "$length_of_string" ]; do
    last_character="${last_character#?}"
    i=$(( i + 1 ))
  done

  printf  '%s'  "$last_character"
}


string_fetch_last_character  "$string"

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Is there a way to crack the password on an Excel VBA Project?

ElcomSoft makes Advanced Office Password Breaker and Advanced Office Password Recovery products which may apply to this case, as long as the document was created in Office 2007 or prior.

How to update two tables in one statement in SQL Server 2005?

It is as simple as this query shown below.

UPDATE 
  Table1 T1 join Table2 T2 on T1.id = T2.id
SET 
  T1.LastName='DR. XXXXXX', 
  T2.WAprrs='start,stop'
WHERE 
  T1.id = '010008'

How do I clear all options in a dropdown box?

The simplest solutions are the best, so You just need:

_x000D_
_x000D_
var list = document.getElementById('list');_x000D_
while (list.firstChild) {_x000D_
    list.removeChild(list.firstChild);_x000D_
}
_x000D_
<select id="list">_x000D_
  <option value="0">0</option>_x000D_
  <option value="1">1</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

JUnit tests pass in Eclipse but fail in Maven Surefire

I suddenly experienced this error, and the solution for me was to disable to run tests in parallel.

Your milage may vary, since I could lower number of failing tests by configuring surefire to run parallel tests by ´classes´.:

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <parallel>classes</parallel>
                    <threadCount>10</threadCount>
                </configuration>
            </plugin>

As I wrote first, this was not enough for my test suite, so I completely disabled parallel by removing the <configuration> section.

Resizing an iframe based on content

We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.

There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.

There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:

 www.foo.com/home.html, which iframes
 |-> www.bar.net/framed.html, which iframes
     |-> www.foo.com/helper.html

then home.html can communicate with framed.html (iframed) and helper.html (same domain).

 Communication options for each page:
 +-------------------------+-----------+-------------+-------------+
 |                         | home.html | framed.html | helper.html |
 +-------------------------+-----------+-------------+-------------+
 | www.foo.com/home.html   |    N/A    |     YES     |     YES     |
 | www.bar.net/framed.html |    NO     |     N/A     |     YES     |
 | www.foo.com/helper.html |    YES    |     YES     |     N/A     |
 +-------------------------+-----------+-------------+-------------+

framed.html can send messages to helper.html (iframed) but not home.html (child can't communicate cross-domain with parent).

The key here is that helper.html can receive messages from framed.html, and can also communicate with home.html.

So essentially, when framed.html loads, it works out its own height, tells helper.html, which passes the message on to home.html, which can then resize the iframe in which framed.html sits.

The simplest way we found to pass messages from framed.html to helper.html was through a URL argument. To do this, framed.html has an iframe with src='' specified. When its onload fires, it evaluates its own height, and sets the src of the iframe at this point to helper.html?height=N

There's an explanation here of how facebook handle it, which may be slightly clearer than mine above!


Code

In www.foo.com/home.html, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):

<script>
  // Resize iframe to full height
  function resizeIframe(height)
  {
    // "+60" is a general rule of thumb to allow for differences in
    // IE & and FF height reporting, can be adjusted as required..
    document.getElementById('frame_name_here').height = parseInt(height)+60;
  }
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>

In www.bar.net/framed.html:

<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>

<script type="text/javascript">
  function iframeResizePipe()
  {
     // What's the page height?
     var height = document.body.scrollHeight;

     // Going to 'pipe' the data to the parent through the helpframe..
     var pipe = document.getElementById('helpframe');

     // Cachebuster a precaution here to stop browser caching interfering
     pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();

  }
</script>

Contents of www.foo.com/helper.html:

<html> 
<!-- 
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content 
--> 
  <body onload="parentIframeResize()"> 
    <script> 
      // Tell the parent iframe what height the iframe needs to be
      function parentIframeResize()
      {
         var height = getParam('height');
         // This works as our parent's parent is on our domain..
         parent.parent.resizeIframe(height);
      }

      // Helper function, parse param from request string
      function getParam( name )
      {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
      }
    </script> 
  </body> 
</html>

Run batch file as a Windows service

While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.

I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.

There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).

SQL update from one Table to another based on a ID match

I believe an UPDATE FROM with a JOIN will help:

MS SQL

UPDATE
    Sales_Import
SET
    Sales_Import.AccountNumber = RAN.AccountNumber
FROM
    Sales_Import SI
INNER JOIN
    RetrieveAccountNumber RAN
ON 
    SI.LeadID = RAN.LeadID;

MySQL and MariaDB

UPDATE
    Sales_Import SI,
    RetrieveAccountNumber RAN
SET
    SI.AccountNumber = RAN.AccountNumber
WHERE
    SI.LeadID = RAN.LeadID;

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

You need to put package-info.java in your generated jaxb package. Its content should be something like that

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/StudentOperations/")
package generated.marsh;

using batch echo with special characters

The way to output > character is to prepend it with ^ escape character:

echo ^>

will print simply

>

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

How to check if a string "StartsWith" another string?

data.substring(0, input.length) === input

PHP and MySQL Select a Single Value

try this

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
      $_SESSION['myid'] = $row['id'];
}

How to create a .NET DateTime from ISO 8601 format

This works fine in LINQPad4:

Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00Z"));
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00"));
Console.WriteLine(DateTime.Parse("2010-08-20 15:00:00"));

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.

Create a view model class like this:

public class EmployeeAddViewModel
{
    public Employee employee { get; set; }
    public Dictionary<int, string> staffTypes { get; set; }
    // really? a 1-to-many for genders
    public Dictionary<int, string> genderTypes { get; set; }

    public EmployeeAddViewModel() { }
    public EmployeeAddViewModel(int id)
    {
        employee = someEntityContext.Employees
            .Where(e => e.ID == id).SingleOrDefault();

        // instantiate your dictionaries

        foreach(var staffType in someEntityContext.StaffTypes)
        {
            staffTypes.Add(staffType.ID, staffType.Type);
        }

        // repeat similar loop for gender types
    }
}

Controller:

[HttpGet]
public ActionResult Add()
{
    return View(new EmployeeAddViewModel());
}

[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
    if(ModelState.IsValid)
    {
        Employee.Add(vm.Employee);
        return View("Index"); // or wherever you go after successful add
    }

    return View(vm);
}

Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:

@Html.DropDownListFor(model => model.employee.staffTypeID,
    new SelectList(model.staffTypes, "ID", "Type"))

and similarly for the gender dropdown

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(model.genderTypes, "ID", "Gender"))

Update per comments

For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList... below, you would use your IEnumerable.

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(new SelectList()
    {
        new { ID = 1, Gender = "Male" },
        new { ID = 2, Gender = "Female" }
    }, "ID", "Gender"))

Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:

ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1  | Gender     | 1         | Male        | male gender       | 1
2  | State      | 50        | Hawaii      | 50th state        | 1
3  | Gender     | 2         | Female      | female gender     | 1
4  | State      | 49        | Alaska      | 49th state        | 1
5  | OrderType  | 1         | Web         | online order      | 1

I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.

Hope this helps!

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Can't import all at once but can use following combination:

ALT + Enter --> Show intention actions and quick-fixes.

F2 --> Next highlighted error.

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

How to get jSON response into variable from a jquery script

You should use data.response in your JS instead of json.response.

SDK Location not found Android Studio + Gradle

If none of the answers work for you which happened to me on macbook pro in one of the projects you can always try to run Android Studio with an alias command passing sdk.dir with each run:

alias studio='launchctl setenv ANDROID_HOME '\''/Users/username/Library/Android/sdk'\'' && open -a '\''Android Studio'\'''

How to create Android Facebook Key Hash?

Please try this:

public static void printHashKey(Context pContext) {
        try {
            PackageInfo info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String hashKey = new String(Base64.encode(md.digest(), 0));
                Log.i(TAG, "printHashKey() Hash Key: " + hashKey);
            }
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "printHashKey()", e);
        } catch (Exception e) {
            Log.e(TAG, "printHashKey()", e);
        }
    }

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

Converting integer to digit list

num = list(str(100))
index = len(num)
while index > 0:
    index -= 1
    num[index] = int(num[index])
print(num)

It prints [1, 0, 0] object.

How to dismiss ViewController in Swift?

@IBAction func back(_ sender: Any) {
        self.dismiss(animated: false, completion: nil)
    }