Programs & Examples On #Home directory

What is the alternative for ~ (user's home directory) on Windows command prompt?

Use %systemdrive%%homepath%. %systemdrive% gives drive character ( Mostly C: ) and %homepath% gives user home directory ( \Users\<USERNAME> ).

Node.js - Find home directory in platform agnostic way

os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());

Meaning of tilde in Linux bash (not home directory)

Are they the home directories of users in /etc/passwd? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

How to get the home directory in Python?

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How do you express binary literals in Python?

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)
4161

If you don't start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)
10101

MongoDB/Mongoose querying at a specific date?

We had an issue relating to duplicated data in our database, with a date field having multiple values where we were meant to have 1. I thought I'd add the way we resolved the issue for reference.

We have a collection called "data" with a numeric "value" field and a date "date" field. We had a process which we thought was idempotent, but ended up adding 2 x values per day on second run:

{ "_id" : "1", "type":"x", "value":1.23, date : ISODate("2013-05-21T08:00:00Z")}
{ "_id" : "2", "type":"x", "value":1.23, date : ISODate("2013-05-21T17:00:00Z")}

We only need 1 of the 2 records, so had to resort the javascript to clean up the db. Our initial approach was going to be to iterate through the results and remove any field with a time of between 6am and 11am (all duplicates were in the morning), but during implementation, made a change. Here's the script used to fix it:

var data = db.data.find({"type" : "x"})
var found = [];
while (data.hasNext()){
    var datum = data.next();
    var rdate = datum.date;
    // instead of the next set of conditions, we could have just used rdate.getHour() and checked if it was in the morning, but this approach was slightly better...
    if (typeof found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] !== "undefined") {
       if (datum.value != found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()]) {
           print("DISCREPENCY!!!: " + datum._id + " for date " + datum.date);
       }
       else {
           print("Removing " + datum._id);
           db.data.remove({ "_id": datum._id});
       }
    }
    else {
       found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] = datum.value;
    }
}

and then ran it with mongo thedatabase fixer_script.js

Hashset vs Treeset

A lot of answers have been given, based on technical considerations, especially around performance. According to me, choice between TreeSet and HashSet matters.

But I would rather say the choice should be driven by conceptual considerations first.

If, for the objects your need to manipulate, a natural ordering does not make sense, then do not use TreeSet.
It is a sorted set, since it implements SortedSet. So it means you need to override function compareTo, which should be consistent with what returns function equals. For example if you have a set of objects of a class called Student, then I do not think a TreeSet would make sense, since there is no natural ordering between students. You can order them by their average grade, okay, but this is not a "natural ordering". Function compareTo would return 0 not only when two objects represent the same student, but also when two different students have the same grade. For the second case, equals would return false (unless you decide to make the latter return true when two different students have the same grade, which would make equals function have a misleading meaning, not to say a wrong meaning.)
Please note this consistency between equals and compareTo is optional, but strongly recommended. Otherwise the contract of interface Set is broken, making your code misleading to other people, thus also possibly leading to unexpected behavior.

This link might be a good source of information regarding this question.

how to add value to combobox item

Although this question is 5 years old I have come across a nice solution.

Use the 'DictionaryEntry' object to pair keys and values.

Set the 'DisplayMember' and 'ValueMember' properties to:

   Me.myComboBox.DisplayMember = "Key"
   Me.myComboBox.ValueMember = "Value"

To add items to the ComboBox:

   Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))

To retreive items like this:

MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

How to dump a dict to a json file?

with pretty-print format:

import json

with open(path_to_file, 'w') as file:
    json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
    file.write(json_string)

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

How to hide code from cells in ipython notebook visualized with nbviewer?

jupyter nbconvert yourNotebook.ipynb --no-input --no-prompt

jupyter nbconvert yourNotebook.ipynb This part of the code will take the latex file format of the jupyter notebook and converts it to a html

--no-input This is like a parameter we are saying during conversion that dont add any inputs : here the input to a cell is the code.. so we hide it

--no-prompt Here also we are saying, During conversion dont show any prompts form the code like errors or warnings in the final HTML file ) so that that html will have only the Text and the code output in the form of a report !!..

Hope it helps :)

What is the difference between public, private, and protected?

PHP manual has a good read on the question here.

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Get RETURN value from stored procedure in SQL

Assign after the EXEC token:

DECLARE @returnValue INT

EXEC @returnValue = SP_One

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Mockito - difference between doReturn() and when()

The latter alternative is used for methods on mocks that return void.

Please have a look, for example, here: How to make mock to void methods with mockito

How to step through Python code to help debug issues?

ipdb (IPython debugger)

ipdb adds IPython functionality to pdb, offering the following HUGE improvements:

  • tab completion
  • show more context lines
  • syntax highlight

Much like pdg, ipdb is still far from perfect and completely rudimentary if compared to GDB, but it is already a huge improvement over pdb.

Usage is analogous to pdb, just install it with:

python3 -m pip install --user ipdb

and then add to the line you want to step debug from:

__import__('ipdb').set_trace(context=21)

You likely want to add a shortcut for that from your editor, e.g. for Vim snipmate I have:

snippet ipd
    __import__('ipdb').set_trace(context=21)

so I can type just ipd<tab> and it expands to the breakpoint. Then removing it is easy with dd since everything is contained in a single line.

context=21 increases the number of context lines as explained at: How can I make ipdb show more lines of context while debugging?

Alternatively, you can also debug programs from the start with:

ipdb3 main.py

but you generally don't want to do that because:

  • you would have to go through all function and class definitions as Python reads those lines
  • I don't know how to set the context size there without hacking ipdb. Patch to allow it: https://github.com/gotcha/ipdb/pull/155

Or alternatively, as in raw pdb 3.2+ you can set some breakpoints from the command line:

ipdb3 -c 'b 12' -c 'b myfunc' ~/test/a.py

although -c c is broken for some reason: https://github.com/gotcha/ipdb/issues/156

python -m module debugging has been asked at: How to debug a Python module run with python -m from the command line? and since Python 3.7 can be done with:

python -m pdb -m my_module

Serious missing features of both pdb and ipdb compared to GDB:

ipdb specific annoyances:

Tested in Ubuntu 16.04, ipdb==0.11, Python 3.5.2.

JavaScript DOM: Find Element Index In Container

An example of making an array from HTMLCollection

<ul id="myList">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

<script>
var tagList = [];

var ulList = document.getElementById("myList");

var tags   = ulList.getElementsByTagName("li");

//Dump elements into Array
while( tagList.length != tags.length){
    tagList.push(tags[tagList.length])
};

tagList.forEach(function(item){
        item.addEventListener("click", function (event){ 
            console.log(tagList.indexOf( event.target || event.srcElement));
        });
}); 
</script>

what is the difference between ajax and jquery and which one is better?

Ajax is a way of using Javascript for communicating with serverside without loading the page over again. jQuery uses ajax for many of its functions, but it nothing else than a library that provides easier functionality.

With jQuery you dont have to think about creating xml objects ect ect, everything is done for you, but with straight up javascript ajax you need to program every single step of the ajax call.

changing textbox border colour using javascript

Use CSS styles with CSS Classes instead

CSS

.error {
  border:2px solid red;
}

Now in Javascript

document.getElementById("fName").className = document.getElementById("fName").className + " error";  // this adds the error class

document.getElementById("fName").className = document.getElementById("fName").className.replace(" error", ""); // this removes the error class

The main reason I mention this is suppose you want to change the color of the errored element's border. If you choose your way you will may need to modify many places in code. If you choose my way you can simply edit the style sheet.

How to have a drop down <select> field in a rails form?

Or for custom options

<%= f.select :desired_attribute, ['option1', 'option2']%>

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview

How can I count the number of elements of a given value in a matrix?

Here's a list of all the ways I could think of to counting unique elements:

M = randi([1 7], [1500 1]);

Option 1: tabulate

t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);

Option 2: hist/histc

counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );

Option 3: accumarray

counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);

Option 4: sort/diff

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);

Option 5: arrayfun

counts5 = arrayfun( @(x)sum(M==x), unique(M) );

Option 6: bsxfun

counts6 = sum( bsxfun(@eq, M, unique(M)') )';

Option 7: sparse

counts7 = full(sparse(M,1,1));

If else embedding inside html

<?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>

how to destroy an object in java?

In java there is no explicit way doing garbage collection. The JVM itself runs some threads in the background checking for the objects that are not having any references which means all the ways through which we access the object are lost. On the other hand an object is also eligible for garbage collection if it runs out of scope that is the program in which we created the object is terminated or ended. Coming to your question the method finalize is same as the destructor in C++. The finalize method is actually called just before the moment of clearing the object memory by the JVM. It is up to you to define the finalize method or not in your program. However if the garbage collection of the object is done after the program is terminated then the JVM will not invoke the finalize method which you defined in your program. You might ask what is the use of finalize method? For instance let us consider that you created an object which requires some stream to external file and you explicitly defined a finalize method to this object which checks wether the stream opened to the file or not and if not it closes the stream. Suppose, after writing several lines of code you lost the reference to the object. Then it is eligible for garbage collection. When the JVM is about to free the space of your object the JVM just checks have you defined the finalize method or not and invokes the method so there is no risk of the opened stream. finalize method make the program risk free and more robust.

Adding three months to a date in PHP

Add nth Days, months and years

$n = 2;
for ($i = 0; $i <= $n; $i++){
    $d = strtotime("$i days");
    $x = strtotime("$i month");
    $y = strtotime("$i year");
    echo "Dates : ".$dates = date('d M Y', "+$d days");
    echo "<br>";
    echo "Months : ".$months = date('M Y', "+$x months");
    echo '<br>';
    echo "Years : ".$years = date('Y', "+$y years");
    echo '<br>';
}

How to 'foreach' a column in a DataTable using C#?

In LINQ you could do something like:

foreach (var data in from DataRow row in dataTable.Rows
                     from DataColumn col in dataTable.Columns
                          where
                              row[col] != null
                          select row[col])
{
    // do something with data
}

how to display variable value in alert box?

spans not have the value in html

one is the id for span tag

in javascript use

document.getElementById('one').innerText;

in jQuery use

$('#one').text()

function check() {
    var content = document.getElementById("one").innerText;
    alert(content);
}

or

function check() {
        var content = $('#one').text();
        alert(content);
    }

C# loop - break vs. continue

break will exit the loop completely, continue will just skip the current iteration.

For example:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.

Disable elastic scrolling in Safari

If you use the overflow:hidden hack on the <body> element, to get back normal scrolling behavior, you can position a <div> absolutely inside of the element to get scrolling back with overflow:auto. I think this is the best option, and it's quite easy to implement using only css!

Or, you can try with jQuery:

$(document).bind(
'touchmove',
function(e) {
e.preventDefault();
}
);

Same in javasrcipt:

document.addEventListener(
'touchmove',
function(e) {
e.preventDefault();
},
false
);

Last option, check ipad safari: disable scrolling, and bounce effect?

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

Confused about Service vs Factory

Adding to the first answer, I think .service() is for people who have written their code in more object oriented style(C#/Java) (using this keyword and instantiating object via prototype/Constructor function).

Factory is for developers who write code which is more natural to javascript/functional style of coding.

Take a look at the source code of .service and .factory method inside angular.js - internally they all call provider method:

  function provider(name, provider_) {
    if (isFunction(provider_)) {
      provider_ = providerInjector.instantiate(provider_);
    }
    if (!provider_.$get) {
      throw Error('Provider ' + name + ' must define $get factory method.');
    }
    return providerCache[name + providerSuffix] = provider_;
  }

  function factory(name, factoryFn) { \
    return provider(name, { $get: factoryFn }); 
  }

  function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
  }

How to get mouse position in jQuery without mouse-events?

I used this method:

$(document).mousemove(function(e) {
    window.x = e.pageX;
    window.y = e.pageY;
});

function show_popup(str) {
    $("#popup_content").html(str);
    $("#popup").fadeIn("fast");
    $("#popup").css("top", y);
    $("#popup").css("left", x);
}

In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.

DateTime vs DateTimeOffset

DateTimeOffset is a representation of instantaneous time (also known as absolute time). By that, I mean a moment in time that is universal for everyone (not accounting for leap seconds, or the relativistic effects of time dilation). Another way to represent instantaneous time is with a DateTime where .Kind is DateTimeKind.Utc.

This is distinct from calendar time (also known as civil time), which is a position on someone's calendar, and there are many different calendars all over the globe. We call these calendars time zones. Calendar time is represented by a DateTime where .Kind is DateTimeKind.Unspecified, or DateTimeKind.Local. And .Local is only meaningful in scenarios where you have an implied understanding of where the computer that is using the result is positioned. (For example, a user's workstation)

So then, why DateTimeOffset instead of a UTC DateTime? It's all about perspective. Let's use an analogy - we'll pretend to be photographers.

Imagine you are standing on a calendar timeline, pointing a camera at a person on the instantaneous timeline laid out in front of you. You line up your camera according to the rules of your timezone - which change periodically due to daylight saving time, or due to other changes to the legal definition of your time zone. (You don't have a steady hand, so your camera is shaky.)

The person standing in the photo would see the angle at which your camera came from. If others were taking pictures, they could be from different angles. This is what the Offset part of the DateTimeOffset represents.

So if you label your camera "Eastern Time", sometimes you are pointing from -5, and sometimes you are pointing from -4. There are cameras all over the world, all labeled different things, and all pointing at the same instantaneous timeline from different angles. Some of them are right next to (or on top of) each other, so just knowing the offset isn't enough to determine which timezone the time is related to.

And what about UTC? Well, it's the one camera out there that is guaranteed to have a steady hand. It's on a tripod, firmly anchored into the ground. It's not going anywhere. We call its angle of perspective the zero offset.

Instantaneous Time vs Calendar Time Visualization

So - what does this analogy tell us? It provides some intuitive guidelines-

  • If you are representing time relative to some place in particular, represent it in calendar time with a DateTime. Just be sure you don't ever confuse one calendar with another. Unspecified should be your assumption. Local is only useful coming from DateTime.Now. For example, I might get DateTime.Now and save it in a database - but when I retrieve it, I have to assume that it is Unspecified. I can't rely that my local calendar is the same calendar that it was originally taken from.

  • If you must always be certain of the moment, make sure you are representing instantaneous time. Use DateTimeOffset to enforce it, or use UTC DateTime by convention.

  • If you need to track a moment of instantaneous time, but you want to also know "What time did the user think it was on their local calendar?" - then you must use a DateTimeOffset. This is very important for timekeeping systems, for example - both for technical and legal concerns.

  • If you ever need to modify a previously recorded DateTimeOffset - you don't have enough information in the offset alone to ensure that the new offset is still relevant for the user. You must also store a timezone identifier (think - I need the name of that camera so I can take a new picture even if the position has changed).

    It should also be pointed out that Noda Time has a representation called ZonedDateTime for this, while the .Net base class library does not have anything similar. You would need to store both a DateTimeOffset and a TimeZoneInfo.Id value.

  • Occasionally, you will want to represent a calendar time that is local to "whomever is looking at it". For example, when defining what today means. Today is always midnight to midnight, but these represent a near-infinite number of overlapping ranges on the instantaneous timeline. (In practice we have a finite number of timezones, but you can express offsets down to the tick) So in these situations, make sure you understand how to either limit the "who's asking?" question down to a single time zone, or deal with translating them back to instantaneous time as appropriate.

Here are a few other little bits about DateTimeOffset that back up this analogy, and some tips for keeping it straight:

  • If you compare two DateTimeOffset values, they are first normalized to zero offset before comparing. In other words, 2012-01-01T00:00:00+00:00 and 2012-01-01T02:00:00+02:00 refer to the same instantaneous moment, and are therefore equivalent.

  • If you are doing any unit testing and need to be certain of the offset, test both the DateTimeOffset value, and the .Offset property separately.

  • There is a one-way implicit conversion built in to the .Net framework that lets you pass a DateTime into any DateTimeOffset parameter or variable. When doing so, the .Kind matters. If you pass a UTC kind, it will carry in with a zero offset, but if you pass either .Local or .Unspecified, it will assume to be local. The framework is basically saying, "Well, you asked me to convert calendar time to instantaneous time, but I have no idea where this came from, so I'm just going to use the local calendar." This is a huge gotcha if you load up an unspecified DateTime on a computer with a different timezone. (IMHO - that should throw an exception - but it doesn't.)

Shameless Plug:

Many people have shared with me that they find this analogy extremely valuable, so I included it in my Pluralsight course, Date and Time Fundamentals. You'll find a step-by-step walkthrough of the camera analogy in the second module, "Context Matters", in the clip titled "Calendar Time vs. Instantaneous Time".

mysqld: Can't change dir to data. Server doesn't start

Check your real my.ini file location and set --defaults-file="location" with this command

mysql --defaults-file="C:\MYSQL\my.ini" -u root -p

This solution is permanently for your cmd Screen.

How do I execute a PowerShell script automatically using Windows task scheduler?

In my case, my script has parameters, so I set:

Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"

Remove all special characters from a string

Here, check out this function:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I was facing the same issue. I realised that I was using the Wrong provider class in persistence.xml

For Hibernate it should be

<provider>org.hibernate.ejb.HibernatePersistence</provider>

And for EclipseLink it should be

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

Which version of CodeIgniter am I currently using?

Try this code working fine check codeigniter version

Just go to 'system' > 'core' > 'CodeIgniter.php' and look for the lines,

/**
 * CodeIgniter Version
 *
 * @var    string
 *
 */
    define('CI_VERSION', '3.0.0');

Alternate method to check codeigniter version, you can echo the constant value 'CI_VERSION' somewhere in codeigniter controller/view file.

<?php
    echo CI_VERSION;
?>

More Information with demo: how to check codeigniter version

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

Laravel: PDOException: could not find driver

In CentOS7,I try this: yum install php-mysql, then edit php.ini

How to open Atom editor from command line in OS X?

For Windows 7 x64 with default Atom installation add this to your PATH

%USERPROFILE%\AppData\Local\atom\app-1.4.0\resources\cli

and restart any running consoles

(if you don't find Atom there - right-click Atom icon and navigate to Target)

enter image description here

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

how to remove "," from a string in javascript

<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>

It's more common answer. And can be use with s= document.location.href;

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("new").show();

$("new").hide();

w3cSchool link to JQuery show and hide

Apply function to all elements of collection through LINQ

haha, man, I just asked this question a few hours ago (kind of)...try this:

example:

someIntList.ForEach(i=>i+5);

ForEach() is one of the built in .NET methods

This will modify the list, as opposed to returning a new one.

What is the easiest way to encrypt a password when I save it to the registry?

This is what you would like to do:

OurKey.SetValue("Password", StringEncryptor.EncryptString(textBoxPassword.Text));
OurKey.GetValue("Password", StringEncryptor.DecryptString(textBoxPassword.Text));

You can do that with this the following classes. This class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using Ninject.

public class StringEncryptor
{
    private static IKernel _kernel;

    static StringEncryptor()
    {
        _kernel = new StandardKernel(new EncryptionModule());
    }

    public static string EncryptString(string plainText)
    {
        return _kernel.Get<IStringEncryptor>().EncryptString(plainText);
    }

    public static string DecryptString(string encryptedText)
    {
        return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);
    }
}

This next class is the ninject class that allows you to inject the various algorithms:

public class EncryptionModule : StandardModule
{
    public override void Load()
    {
        Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();
    }
}

This is the interface that any algorithm needs to implement to encrypt/decrypt strings:

public interface IStringEncryptor
{
    string EncryptString(string plainText);
    string DecryptString(string encryptedText);
}

This is a implementation using the TripleDES algorithm:

public class TripleDESStringEncryptor : IStringEncryptor
{
    private byte[] _key;
    private byte[] _iv;
    private TripleDESCryptoServiceProvider _provider;

    public TripleDESStringEncryptor()
    {
        _key = System.Text.ASCIIEncoding.ASCII.GetBytes("GSYAHAGCBDUUADIADKOPAAAW");
        _iv = System.Text.ASCIIEncoding.ASCII.GetBytes("USAZBGAW");
        _provider = new TripleDESCryptoServiceProvider();
    }

    #region IStringEncryptor Members

    public string EncryptString(string plainText)
    {
        return Transform(plainText, _provider.CreateEncryptor(_key, _iv));
    }

    public string DecryptString(string encryptedText)
    {
        return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));
    }

    #endregion

    private string Transform(string text, ICryptoTransform transform)
    {
        if (text == null)
        {
            return null;
        }
        using (MemoryStream stream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
            {
                byte[] input = Encoding.Default.GetBytes(text);
                cryptoStream.Write(input, 0, input.Length);
                cryptoStream.FlushFinalBlock();

                return Encoding.Default.GetString(stream.ToArray());
            }
        }
    }
}

You can watch my video and download the code for this at : http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html

How to insert a value that contains an apostrophe (single quote)?

The apostrophe character can be inserted by calling the CHAR function with the apostrophe's ASCII table lookup value, 39. The string values can then be concatenated together with a concatenate operator.

Insert into Person
  (First, Last)
Values
  'Joe',
  concat('O',char(39),'Brien')

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Inspired by TheIT, I just got this to work by manipulating the manifest file but in a slightly different fashion. Set the icon in the application setting so that the majority of the activities get the icon. On the activity where you want to show the logo, add the android:logo attribute to the activity declaration. In the following example, only LogoActivity should have the logo, while the others will default to icon.

<application
    android:name="com.your.app"
    android:icon="@drawable/your_icon"
    android:label="@string/app_name">

    <activity
        android:name="com.your.app.LogoActivity"
        android:logo="@drawable/your_logo"
        android:label="Logo Activity" >

    <activity
        android:name="com.your.app.IconActivity1"
        android:label="Icon Activity 1" >

    <activity
        android:name="com.your.app.IconActivity2"
        android:label="Icon Activity 2" >

</application>

Hope this helps someone else out!

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange

Is there such a thing as min-font-size and max-font-size?

This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

EC2 Instance Cloning

You can do it very easily with a Cloud Management software -like enStratus, RightScale or Scalr (disclaimer: I work there). With the cloned farm you can:

  1. Create a snapshot or a pre-made image to launch another day
  2. Duplicate your configuration to test it before production

Output in a table format in Java's System.out

Because most of solutions is bit outdated I could also suggest asciitable which already available in maven (de.vandermeer:asciitable:0.3.2) and may produce very complicated configurations.

Features (by offsite):

  • Text table with some flexibility for rules and content, alignment, format, padding, margins, and frames:
  • add text, as often as required in many different formats (string, text provider, render provider, ST, clusters),
  • removes all excessive white spaces (tabulators, extra blanks, combinations of carriage return and line feed),
  • 6 different text alignments: left, right, centered, justified, justified last line left, justified last line right,
  • flexible width, set for text and calculated in many different ways for rendering
  • padding characters for left and right padding (configurable separately)
  • padding characters for top and bottom padding (configurable separately)
  • several options for drawing grids
  • rules with different styles (as supported by the used grid theme: normal, light, strong, heavy)
  • top/bottom/left/right margins outside a frame
  • character conversion to generated text suitable for further process, e.g. for LaTeX and HTML

And usage still looks easy:

AsciiTable at = new AsciiTable();

at.addRule();
at.addRow("row 1 col 1", "row 1 col 2");
at.addRule();
at.addRow("row 2 col 1", "row 2 col 2");
at.addRule();

System.out.println(at.render()); // Finally, print the table to standard out.

How do I send a file as an email attachment using Linux command line?

From looking at man mailx, the mailx program does not have an option for attaching a file. You could use another program such as mutt.

echo "This is the message body" | mutt -a file.to.attach -s "subject of message" [email protected]

Command line options for mutt can be shown with mutt -h.

Intellij IDEA Java classes not auto compiling on save

The only thing that worked for me in my maven project that was affected by this is to add a "test-compile" goal to the run configuration of my unit tests. Incredibly clumsy solution, but it works.

enter image description here

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

How do I schedule jobs in Jenkins?

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values. It will calculate the parameter based on the hash code of you project name.

This is so that if you are building several projects on your build machine at the same time, let’s say midnight each day, they do not all start their build execution at the same time. Each project starts its execution at a different minute depending on its hash code.

You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30.

Examples:

  1. Start build daily at 08:30 in the morning, Monday - Friday: 30 08 * * 1-5

  2. Weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday: 00 0,12 * * 0-4

  3. Start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash: H 16 * * 1-5

  4. Start build at midnight: @midnight or start build at midnight, every Saturday: 59 23 * * 6

  5. Every first of every month between 2:00 a.m. - 02:30 a.m.: H(0,30) 02 01 * *

Create array of regex matches

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

How does a Breadth-First Search work when looking for Shortest Path?

From tutorial here

"It has the extremely useful property that if all of the edges in a graph are unweighted (or the same weight) then the first time a node is visited is the shortest path to that node from the source node"

PHP, Get tomorrows date from date

Use DateTime

$datetime = new DateTime('tomorrow');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

Or:

$datetime = new DateTime('2013-01-22');
$datetime->add(new DateInterval("P1D"));
echo $datetime->format('Y-m-d H:i:s');

Or in PHP 5.4+:

echo (new DateTime('2013-01-22'))->add(new DateInterval("P1D"))
                                 ->format('Y-m-d H:i:s');

best practice font size for mobile

The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.

Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.

Set div height to fit to the browser using CSS

You could also use viewport percentages if you don't care about old school IE.

height: 100vh;

How to host google web fonts on my own server?

If you are using Nuxt, you can use their dedicated module for this purpose: https://github.com/nuxt-community/google-fonts-module For me it works much better than the webfonts helper, which often had problems downloading the fonts during build and generated CSS files without Unicode ranges.

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII: http://en.wikipedia.org/wiki/RAII

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 
{ 
  G[i]->Run(); 
} 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 
{ 
   G[i]->Run(); 
} 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

QString to char* conversion

EDITED

this way also works

QString str ("Something");

char* ch = str.toStdString().C_str();

Using Pip to install packages to Anaconda Environment

If you didn't add pip when creating conda environment

conda create -n env_name pip

and also didn't install pip inside the environment

source activate env_name
conda install pip

then the only pip you got is the system pip, which will install packages globally.

Bus as you can see in this issue, even if you did either of the procedure mentioned above, the behavior of pip inside conda environment is still kind of undefined.

To ensure using the pip installed inside conda environment without having to type the lengthy /home/username/anaconda/envs/env_name/bin/pip, I wrote a shell function:

# Using pip to install packages inside conda environments.
cpip() {
    ERROR_MSG="Not in a conda environment."
    ERROR_MSG="$ERROR_MSG\nUse \`source activate ENV\`"
    ERROR_MSG="$ERROR_MSG to enter a conda environment."

    [ -z "$CONDA_DEFAULT_ENV" ] && echo "$ERROR_MSG" && return 1

    ERROR_MSG='Pip not installed in current conda environment.'
    ERROR_MSG="$ERROR_MSG\nUse \`conda install pip\`"
    ERROR_MSG="$ERROR_MSG to install pip in current conda environment."

    [ -e "$CONDA_PREFIX/bin/pip" ] || (echo "$ERROR_MSG" && return 2)

    PIP="$CONDA_PREFIX/bin/pip"
    "$PIP" "$@"
}

Hope this is helpful to you.

Why should C++ programmers minimize use of 'new'?

I think the poster meant to say You do not have to allocate everything on theheap rather than the the stack.

Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.

Calculate row means on subset of columns

You can create a new row with $ in your data frame corresponding to the Means

DF$Mean <- rowMeans(DF[,2:4])

Jquery how to find an Object by attribute in an Array

Best, Fastest way is

function arrayLookup(array, prop, val) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].hasOwnProperty(prop) && array[i][prop] === val) {
            return array[i];
        }
    }
    return null;
}

Importing CSV data using PHP/MySQL

Database Connection:

 try {
        $conn = mysqli_connect($servername, $username, $password, $db);
        //echo "Connected successfully"; 
    } catch (exception $e) {
        echo "Connection failed: " . $e->getMessage();
    }

Code to read CSV file and upload to table in database.

   $file = fopen($filename, "r");
            while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
                $sql = "INSERT into db_table 
                   values ('','" . $getData[1] . "','" . $getData[2] . "','" . $getData[3] . "','" . $getData[4] . "','" . $getData[5] . "','" . $getData[6] . "')";
                $result = mysqli_query($conn, $sql);
                if (!isset($result)) {
                    echo "<script type=\"text/javascript\">
                            alert(\"Invalid File:Please Upload CSV File. 
                            window.location = \"home.do\"
                          </script>";
                } else {
                    echo "<script type=\"text/javascript\">
                        alert(\"CSV File has been successfully Imported.\");
                        window.location = \"home.do\"
                    </script>";
                }
            }
            fclose($file);

Exclude property from type

I do like that:

interface XYZ {
  x: number;
  y: number;
  z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);

Combine two integer arrays

NOTE: didn't test it

int[] concatArray(int[] a, int[] b) {
  int[] c = new int[a.length + b.length];
  int i = 0;
  for (int x : a) { c[i] = x; i ++; }
  for (int x : b) { c[i] = x; i ++; }
  return c;
}

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4, you can use the ParameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}

and in app/config/services.yaml:

parameters:
    locale: 'en'
    dir: '%kernel.project_dir%'

It works for me in both controller and form classes. More details can be found in the Symfony blog.

How to list running screen sessions?

ps x | grep SCREEN

to see what is that screen running in case you used the command

screen -A -m -d php make_something.php

Why can't decimal numbers be represented exactly in binary?

The high scoring answer above nailed it.

First you were mixing base 2 and base 10 in your question, then when you put a number on the right side that is not divisible into the base you get problems. Like 1/3 in decimal because 3 doesnt go into a power of 10 or 1/5 in binary which doesnt go into a power of 2.

Another comment though NEVER use equal with floating point numbers, period. Even if it is an exact representation there are some numbers in some floating point systems that can be accurately represented in more than one way (IEEE is bad about this, it is a horrible floating point spec to start with, so expect headaches). No different here 1/3 is not EQUAL to the number on your calculator 0.3333333, no matter how many 3's there are to the right of the decimal point. It is or can be close enough but is not equal. so you would expect something like 2*1/3 to not equal 2/3 depending on the rounding. Never use equal with floating point.

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

How to get source code of a Windows executable?

You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

How to use a RELATIVE path with AuthUserFile in htaccess?

or if you develop on localhost (only for apache 2.4+):

<If "%{REMOTE_ADDR} != '127.0.0.1'">
</If>

Read HttpContent in WebApi controller

Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.

If you still want to have the model as a parameter in the method, you can create a DelegatingHandler to buffer the content.

internal sealed class BufferizingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        await request.Content.LoadIntoBufferAsync();
        var result = await base.SendAsync(request, cancellationToken);
        return result;
    }
}

And add it to the global message handlers:

configuration.MessageHandlers.Add(new BufferizingHandler());

This solution is based on the answer by Darrel Miller.

This way all the requests will be buffered.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How to call a function in shell Scripting?

Summary:

  • Define functions before using them.
  • Once defined, treat them as commands.

Consider this script, called funcdemo:

#!/bin/bash

[ $# = 0 ] && exhort "write nastygram"

exhort(){
    echo "Please, please do not forget to $*"
}

[ $# != 0 ] && exhort "write begging letter"

In use:

$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$

Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.

How to get current route

This applies if you are using it with an authguard

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );

Pass Parameter to Gulp Task

I know I am late to answer this question but I would like to add something to answer of @Ethan, the highest voted and accepted answer.

We can use yargs to get the command line parameter and with that we can also add our own alias for some parameters like follow.

var args = require('yargs')
    .alias('r', 'release')
    .alias('d', 'develop')
    .default('release', false)
    .argv;

Kindly refer this link for more details. https://github.com/yargs/yargs/blob/HEAD/docs/api.md

Following is use of alias as per given in documentation of yargs. We can also find more yargs function there and can make the command line passing experience even better.

.alias(key, alias)

Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.

Optionally .alias() can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

The difference is not just for Chrome but for most of the web browsers.

enter image description here

F5 refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.

Shift + F5 forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.

Shift + F5 guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5.

You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Java: how to add image to Jlabel?

To get an image from a URL we can use the following code:

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

It totally works for me. The PicUrl is a string variable which strores the url of the picture.

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

How to run Java program in command prompt

javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command

java -cp classpath-entries mainjava arg1 arg2 should run your code with 2 arguments

Temporary table in SQL server causing ' There is already an object named' error

You must modify the query like this

CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME  FROM TBL_PEOPLE

-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.

DROP TABLE #TMPGUARDIAN

Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.

Use Table Variable http://odetocode.com/articles/365.aspx

declare @userData TABLE(
 LAST_NAME NVARCHAR(30),
    FRST_NAME NVARCHAR(30)
)

Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.

How to make HTML table cell editable?

You can use the contenteditable attribute on the cells, rows, or table in question.

Updated for IE8 compatibility

<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>

Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.

You'd also need to check whether your target audience's browsers supported this attribute.

As far as listening for the changes (so you can send to the server), see contenteditable change events

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You need Linq - System.Xml.Linq to be precise.

You can create XML using XElement from scratch - that should pretty much sort you out.

convert string to date in sql server

I had a similar situation. Here's what I was able to do to get a date range in a "where" clause (a modification of marc_s's answer):

where cast(replace(foo.TestDate, '-', '') as datetime) 
      between cast('20110901' as datetime) and
              cast('20510531' as datetime)

Hope that helps...

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

Tricks to manage the available memory in an R session

I use the data.table package. With its := operator you can :

  • Add columns by reference
  • Modify subsets of existing columns by reference, and by group by reference
  • Delete columns by reference

None of these operations copy the (potentially large) data.table at all, not even once.

  • Aggregation is also particularly fast because data.table uses much less working memory.

Related links :

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

jQuery get an element by its data-id

$('[data-item-id="stand-out"]')

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

It also doesn't hurt to watermark your images with Photoshop or even in Lightroom 3 now. Make sure the watermark is clear and in a conspicuous place on your image. That way if it's downloaded, at least you get the advertising!

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.

If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.

How to delete the last row of data of a pandas dataframe

DF[:-n]

where n is the last number of rows to drop.

To drop the last row :

DF = DF[:-1]

Import JSON file in React

This worked well in React 16.11.0

// in customData.js
export const customData = {
  //json data here
  name: 'John Smith',
  imgURL: 'http://lorempixel.com/100/100/',
  hobbyList: ['coding', 'writing', 'skiing']
}

// in index.js
import { customData } from './customData';

// example usage later in index.js
<p>{customData.name}</p>

resize2fs: Bad magic number in super-block while trying to open

After reading about LVM and being familiar with PV -> VG -> LV, this works for me :

0) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  824K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root   15G  2.1G   13G  14% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

1) # vgs

  VG     #PV #LV #SN Attr   VSize   VFree   
  fedora   1   2   0 wz--n- 231.88g 212.96g

2) # vgdisplay

  --- Volume group ---
  VG Name               fedora
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               231.88 GiB
  PE Size               4.00 MiB
  Total PE              59361
  Alloc PE / Size       4844 / 18.92 GiB
  Free  PE / Size       54517 / 212.96 GiB
  VG UUID               9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv

3) # lvextend -l +100%FREE /dev/mapper/fedora-root

  Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
  Logical volume fedora/root successfully resized.

4) #lvdisplay

5) #fd -h

6) # xfs_growfs /dev/mapper/fedora-root

meta-data=/dev/mapper/fedora-root isize=512    agcount=4, agsize=983040 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1 spinodes=0 rmapbt=0
         =                       reflink=0
data     =                       bsize=4096   blocks=3932160, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568

7) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  828K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root  228G  2.3G  226G   2% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

Best Regards,

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

Works for Safari, Firefox, and IE7 (haven't tried IE8). Simple test:

<button onclick='$("body,html").scrollTop(0);'>  Top </button>

<button onclick='$("body,html").scrollTop(100);'> Middle </button>

<button onclick='$("body,html").scrollTop(250);'> Bottom </button>

Most examples use either one or both, but in reverse order (i.e., "html,body").

Cheers.

(And semantic purists out there, don't bust my chops -- I've been looking for this for weeks, this is a simple example, that validates XHTML strict. Feel free to create 27 layers of abstraction and event binding bloat for your OCD peace of mind. Just please give due credit, since the folks in the jQuery forums, SO, and the G couldn't cough up the goods. Peace out.)

Any way to replace characters on Swift String?

Xcode 11 • Swift 5.1

The mutating method of StringProtocol replacingOccurrences can be implemented as follow:

extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
        self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
    }
}

var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"

Capitalize the first letter of string in AngularJs

if (value){
  value = (value.length > 1) ? value[0].toUpperCase() + value.substr(1).toLowerCase() : value.toUpperCase();
}

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

How can I format a number into a string with leading zeros?

Rather simple:

Key = i.ToString("D2");

D stands for "decimal number", 2 for the number of digits to print.

Oracle: is there a tool to trace queries, like Profiler for sql server?

I found an easy solution

Step1. connect to DB with an admin user using PLSQL or sqldeveloper or any other query interface

Step2. run the script bellow; in the S.SQL_TEXT column, you will see the executed queries

SELECT            
 S.LAST_ACTIVE_TIME,     
 S.MODULE,
 S.SQL_FULLTEXT, 
 S.SQL_PROFILE,
 S.EXECUTIONS,
 S.LAST_LOAD_TIME,
 S.PARSING_USER_ID,
 S.SERVICE                                                                       
FROM
 SYS.V_$SQL S, 
 SYS.ALL_USERS U
WHERE
 S.PARSING_USER_ID=U.USER_ID 
 AND UPPER(U.USERNAME) IN ('oracle user name here')   
ORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc;

The only issue with this is that I can't find a way to show the input parameters values(for function calls), but at least we can see what is ran in Oracle and the order of it without using a specific tool.

What should be the values of GOPATH and GOROOT?

in osx, i installed with brew, here is the setting that works for me

GOPATH="$HOME/my_go_work_space" //make sure you have this folder created

GOROOT="/usr/local/Cellar/go/1.10/libexec"

Download file from an ASP.NET Web API method using AngularJS

I have gone through array of solutions and this is what I found to have worked great for me.

In my case I needed to send a post request with some credentials. Small overhead was to add jquery inside the script. But was worth it.

var printPDF = function () {
        //prevent double sending
        var sendz = {};
        sendz.action = "Print";
        sendz.url = "api/Print";
        jQuery('<form action="' + sendz.url + '" method="POST">' +
            '<input type="hidden" name="action" value="Print" />'+
            '<input type="hidden" name="userID" value="'+$scope.user.userID+'" />'+
            '<input type="hidden" name="ApiKey" value="' + $scope.user.ApiKey+'" />'+
            '</form>').appendTo('body').submit().remove();

    }

How can I render inline JavaScript with Jade / Pug?

For multi-line content jade normally uses a "|", however:

Tags that accept only text such as script, style, and textarea do not need the leading | character

This said, i cannot reproduce the problem you are having. When i paste that code in a jade template, it produces the right output and prompts me with an alert on page-load.

How can I convert an Integer to localized month name in Java?

There is an issue when you use DateFormatSymbols class for its getMonthName method to get Month by Name it show Month by Number in some Android devices. I have resolved this issue by doing this way:

In String_array.xml

<string-array name="year_month_name">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
    <item>September</item>
    <item>October</item>
    <item>November</item>
    <item>December</item>
    </string-array>

In Java class just call this array like this way:

public String[] getYearMonthName() {
        return getResources().getStringArray(R.array.year_month_names);
        //or like 
       //return cntx.getResources().getStringArray(R.array.month_names);
    } 

      String[] months = getYearMonthName(); 
           if (i < months.length) {
            monthShow.setMonthName(months[i] + " " + year);

            }

Happy Coding :)

get dictionary key by value

Below Code only works if It contain Unique Value Data

public string getKey(string Value)
{
    if (dictionary.ContainsValue(Value))
    {
        var ListValueData=new List<string>();
        var ListKeyData = new List<string>();

        var Values = dictionary.Values;
        var Keys = dictionary.Keys;

        foreach (var item in Values)
        {
            ListValueData.Add(item);
        }

        var ValueIndex = ListValueData.IndexOf(Value);
        foreach (var item in Keys)
        {
            ListKeyData.Add(item);
        }

        return  ListKeyData[ValueIndex];

    }
    return string.Empty;
}

How can I tell when a MySQL table was last updated?

Although there is an accepted answer I don't feel that it is the right one. It is the simplest way to achieve what is needed, but even if already enabled in InnoDB (actually docs tell you that you still should get NULL ...), if you read MySQL docs, even in current version (8.0) using UPDATE_TIME is not the right option, because:

Timestamps are not persisted when the server is restarted or when the table is evicted from the InnoDB data dictionary cache.

If I understand correctly (can't verify it on a server right now), timestamp gets reset after server restart.

As for real (and, well, costly) solutions, you have Bill Karwin's solution with CURRENT_TIMESTAMP and I'd like to propose a different one, that is based on triggers (I'm using that one).

You start by creating a separate table (or maybe you have some other table that can be used for this purpose) which will work like a storage for global variables (here timestamps). You need to store two fields - table name (or whatever value you'd like to keep here as table id) and timestamp. After you have it, you should initialize it with this table id + starting date (NOW() is a good choice :) ).

Now, you move to tables you want to observe and add triggers AFTER INSERT/UPDATE/DELETE with this or similar procedure:

CREATE PROCEDURE `timestamp_update` ()
BEGIN
    UPDATE `SCHEMA_NAME`.`TIMESTAMPS_TABLE_NAME`
    SET `timestamp_column`=DATE_FORMAT(NOW(), '%Y-%m-%d %T')
    WHERE `table_name_column`='TABLE_NAME';
END

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

how to get the value of a textarea in jquery?

all Values is always taken with .val().

see the code bellow:

var message = $('#message').val();

How to pass table value parameters to stored procedure from .net code

The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

Create this extension method...

public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
   if(paramCollection != null)
   {
       var p = paramCollection.Add(parameterName, SqlDbType.Structured);
       p.TypeName = "dbo.tvp_Int";
       DataTable _dt = new DataTable() {Columns = {"Value"}};
       data.ForEach(value => _dt.Rows.Add(value));
       p.Value = _dt;
   }
}

Now you can add a table valued parameter in one line anywhere simply by doing this:

cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);

Error type 3 Error: Activity class {} does not exist

I faced this problem lately, and tried all suggestions above, and problem was not saved. Finally I changed a NDK, and problem was solved...

How to read multiple text files into a single RDD?

Use union as follows:

val sc = new SparkContext(...)
val r1 = sc.textFile("xxx1")
val r2 = sc.textFile("xxx2")
...
val rdds = Seq(r1, r2, ...)
val bigRdd = sc.union(rdds)

Then the bigRdd is the RDD with all files.

How to persist a property of type List<String> in JPA?

According to Java Persistence with Hibernate

mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard

If you were using Hibernate, you could do something like:

@org.hibernate.annotations.CollectionOfElements(
    targetElement = java.lang.String.class
)
@JoinTable(
    name = "foo",
    joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
    name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();

Update: Note, this is now available in JPA2.

Multiple WHERE clause in Linq

@Jon: Jon, are you saying using multiple where clauses e.g.

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" 
            where r.Field<string>("UserName") != "YYYY"
            select r;

is more restictive than using

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
            select r;

I think they are equivalent as far as the result goes.

However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY) or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")

Convert string to decimal, keeping fractions

Here is a solution I came up with for myself. This is ready to run as a command prompt project. You need to clean some stuff if not. Hope this helps. It accepts several input formats like: 1.234.567,89 1,234,567.89 etc

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Globalization;
    using System.Linq;

    namespace ConvertStringDecimal
    {
        class Program
        {
            static void Main(string[] args)
            {
                while(true)
                {
                    // reads input number from keyboard
                    string input = Console.ReadLine();
                    double result = 0;
                    // remove empty spaces
                    input = input.Replace(" ", "");
                    // checks if the string is empty
                    if (string.IsNullOrEmpty(input) == false)
                    {
                        // check if input has , and . for thousands separator and decimal place
                        if (input.Contains(",") && input.Contains("."))
                        {
                            // find the decimal separator, might be , or .
                            int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
                            // uses | as a temporary decimal separator
                            input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
                            // formats the output removing the , and . and replacing the temporary | with .
                            input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
                        }
                        // replaces , with .
                        if (input.Contains(","))
                        {
                            input = input.Replace(',', '.');
                        }
                        // checks if the input number has thousands separator and no decimal places
                        if(input.Count(item => item == '.') > 1)
                        {
                            input = input.Replace(".", "");
                        }
                        // tries to convert input to double
                        if (double.TryParse(input, out result) == true)
                        {
                            result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
                        }
                    }
                    // outputs the result
                    Console.WriteLine(result.ToString());
                    Console.WriteLine("----------------");
                }
            }
        }
    }

select dept names who have more than 2 employees whose salary is greater than 1000

My main advice would be to steer clear of the HAVING clause (see below):

WITH HighEarners AS
     ( SELECT EmpId, DeptId
         FROM EMPLOYEE
        WHERE Salary > 1000 ), 
     DeptmentHighEarnerTallies AS 
     ( SELECT DeptId, COUNT(*) AS HighEarnerTally
         FROM HighEarners
        GROUP 
           BY DeptId )
SELECT DeptName
  FROM DEPARTMENT NATURAL JOIN DeptmentHighEarnerTallies
 WHERE HighEarnerTally > 2;

The very early SQL implementations lacked derived tables and HAVING was a workaround for one of its most obvious drawbacks (how to select on the result of a set function from the SELECT clause). Once derived tables had become a thing, the need for HAVING went away. Sadly, HAVING itself didn't go away (and never will) because nothing is ever removed from standard SQL. There is no need to learn HAVING and I encourage fledgling coders to avoid using this historical hangover.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

iOS9 Untrusted Enterprise Developer with no option to trust

On iOS 9.2 Profiles renamed to Device Management.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

IndentationError: unindent does not match any outer indentation level

It could be because the function above it is not indented the same way. i.e.

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")

Reading specific XML elements from XML file

You could use an XPath, too. A bit old fashioned but still effective:

using System.Xml;

...

XmlDocument xmlDocument;

xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

foreach (XmlElement xmlElement in 
    xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
    Console.Out.WriteLine(xmlElement.OuterXml);
}

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

Try this it worked for me.

sudo /usr/local/mysql/support-files/mysql.server start

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Remove cascading from the child entity Transaction, it should be just:

@Entity class Transaction {
    @ManyToOne // no cascading here!
    private Account account;
}

(FetchType.EAGER can be removed as well as it's the default for @ManyToOne)

That's all!

Why? By saying "cascade ALL" on the child entity Transaction you require that every DB operation gets propagated to the parent entity Account. If you then do persist(transaction), persist(account) will be invoked as well.

But only transient (new) entities may be passed to persist (Transaction in this case). The detached (or other non-transient state) ones may not (Account in this case, as it's already in DB).

Therefore you get the exception "detached entity passed to persist". The Account entity is meant! Not the Transaction you call persist on.


You generally don't want to propagate from child to parent. Unfortunately there are many code examples in books (even in good ones) and through the net, which do exactly that. I don't know, why... Perhaps sometimes simply copied over and over without much thinking...

Guess what happens if you call remove(transaction) still having "cascade ALL" in that @ManyToOne? The account (btw, with all other transactions!) will be deleted from the DB as well. But that wasn't your intention, was it?

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

How to ignore SSL certificate errors in Apache HttpClient 4.0

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method to call when making post requests....

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue your request in the normal form

How to copy an object by value, not by reference

You need to do a deep copy from user to usercopy, and then after your login you can reassign your userCopy reference to user.

User userCopy = new User();
userCopy.Age = user.Age
userCopy.ID = user.ID

foreach(...) 
{ 
  user.Age = 1; 
  user.ID = -1; 

  UserDao.Update(user)     

  user = userCopy;       
}

What is the difference between typeof and instanceof and when should one be used vs. the other?

One more case is that You only can collate with instanceof - it returns true or false. With typeof you can get type of provided something

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

Numpy first occurrence of value greater than existing value

I would go with

i = np.min(np.where(V >= x))

where V is vector (1d array), x is the value and i is the resulting index.

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

CSS styling in Django forms

You can do:

<form action="" method="post">
    <table>
        {% for field in form %}
        <tr><td>{{field}}</td></tr>
        {% endfor %}
    </table>
    <input type="submit" value="Submit">
</form>

Then you can add classes/id's to for example the <td> tag. You can of course use any others tags you want. Check Working with Django forms as an example what is available for each field in the form ({{field}} for example is just outputting the input tag, not the label and so on).

How to cast from List<Double> to double[] in Java?

As per your question,

List<Double> frameList =  new ArrayList<Double>();
  1. First you have to convert List<Double> to Double[] by using

    Double[] array = frameList.toArray(new Double[frameList.size()]);
    
  2. Next you can convert Double[] to double[] using

    double[] doubleArray = ArrayUtils.toPrimitive(array);
    

You can directly use it in one line:

double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

You need to use bitwise operators | instead of or and & instead of and in pandas, you can't simply use the bool statements from python.

For much complex filtering create a mask and apply the mask on the dataframe.
Put all your query in the mask and apply it.
Suppose,

mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]

DevTools failed to load SourceMap: Could not load content for chrome-extension

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

Export to CSV using jQuery and html

From what I understand, you have your data on a table and you want to create the CSV from that data. However, you have problem creating the CSV.

My thoughts would be to iterate and parse the contents of the table and generate a string from the parsed data. You can check How to convert JSON to CSV format and store in a variable for an example. You are using jQuery in your example so that would not count as an external plugin. Then, you just have to serve the resulting string using window.open and use application/octetstream as suggested.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Registering the framework with IIS is what worked for me:

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool  # python equivalent
True

More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
'b'
>>> np.dtype('int64').kind                                                                                          
'i'
>>> np.dtype('float').kind                                                                                          
'f'
>>> np.dtype('half').kind                                                                                           
'f'

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False  
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype


# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype == np.int
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

Adding a background image to a <div> element

For the most part, the method is the same as setting the whole body

.divi{
    background-image: url('path');
}

</style>

<div class="divi"></div>

Apache redirect to another port

Found this out by trial and error. If your configuration specifies a ServerName, then your VirtualHost directive will need to do the same. In the following example, awesome.example.com and amazing.example.com would both be forwarded to some local service running on port 4567.

ServerName example.com:80

<VirtualHost example.com:80>
  ProxyPreserveHost On
  ProxyRequests Off
  ServerName awesome.example.com
  ServerAlias amazing.example.com
  ProxyPass / http://localhost:4567/
  ProxyPassReverse / http://localhost:4567/
</VirtualHost>

I know this doesn't exactly answer the question, but I'm putting it here because this is the top search result for Apache port forwarding. So I figure it'll help somebody someday.

C#: Waiting for all threads to complete

I was tying to figure out how to do this but i could not get any answers from google. I know this is an old thread but here was my solution:

Use the following class:

class ThreadWaiter
    {
        private int _numThreads = 0;
        private int _spinTime;

        public ThreadWaiter(int SpinTime)
        {
            this._spinTime = SpinTime;
        }

        public void AddThreads(int numThreads)
        {
            _numThreads += numThreads;
        }

        public void RemoveThread()
        {
            if (_numThreads > 0)
            {
                _numThreads--;
            }
        }

        public void Wait()
        {
            while (_numThreads != 0)
            {
                System.Threading.Thread.Sleep(_spinTime);
            }
        }
    }
  1. Call Addthreads(int numThreads) before executing a thread(s).
  2. Call RemoveThread() after each one has completed.
  3. Use Wait() at the point that you want to wait for all the threads to complete before continuing

.gitignore all the .DS_Store files in every folder and subfolder

You should add following lines while creating a project. It will always ignore .DS_Store to be pushed to the repository.

*.DS_Store this will ignore .DS_Store while code commit.
git rm --cached .DS_Store this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.

## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store

How do you roll back (reset) a Git repository to a particular commit?

git reset --hard <tag/branch/commit id>

Notes:

  • git reset without the --hard option resets the commit history, but not the files. With the --hard option the files in working tree are also reset. (credited user)

  • If you wish to commit that state so that the remote repository also points to the rolled back commit do: git push <reponame> -f (credited user)

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

How can I set multiple CSS styles in JavaScript?

I think is this a very simple way with regards to all solutions above:

const elm = document.getElementById("myElement")

const allMyStyle = [
  { prop: "position", value: "fixed" },
  { prop: "boxSizing", value: "border-box" },
  { prop: "opacity", value: 0.9 },
  { prop: "zIndex", value: 1000 },
];

allMyStyle.forEach(({ prop, value }) => {
  elm.style[prop] = value;
});

Delete all but the most recent X files in bash

ls -tQ | tail -n+4 | xargs rm

List filenames by modification time, quoting each filename. Exclude first 3 (3 most recent). Remove remaining.

EDIT after helpful comment from mklement0 (thanks!): corrected -n+3 argument, and note this will not work as expected if filenames contain newlines and/or the directory contains subdirectories.

ValueError: invalid literal for int () with base 10

As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:

With Python2, int(str(5/2)) gives you 2. With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'

If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:

int(float(myStr))

As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Can't escape the backslash with regex?

This solution fixed my problem while replacing br tag to '\n' .

alert(content.replace(/<br\/\>/g,'\n'));

How to access site through IP address when website is on a shared host?

serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.

As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.

67.225.235.59 somerandomservice.com www.somerandomservice.com

Replace duplicate spaces with a single space in T-SQL

You can try this:

select Regexp_Replace('single    spaces   only','( ){2,}', ' ') from dual;

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

How do I parse an ISO 8601-formatted date?

Several answers here suggest using datetime.datetime.strptime to parse RFC 3339 or ISO 8601 datetimes with timezones, like the one exhibited in the question:

2008-09-03T20:56:35.450686Z

This is a bad idea.

Assuming that you want to support the full RFC 3339 format, including support for UTC offsets other than zero, then the code these answers suggest does not work. Indeed, it cannot work, because parsing RFC 3339 syntax using strptime is impossible. The format strings used by Python's datetime module are incapable of describing RFC 3339 syntax.

The problem is UTC offsets. The RFC 3339 Internet Date/Time Format requires that every date-time includes a UTC offset, and that those offsets can either be Z (short for "Zulu time") or in +HH:MM or -HH:MM format, like +05:00 or -10:30.

Consequently, these are all valid RFC 3339 datetimes:

  • 2008-09-03T20:56:35.450686Z
  • 2008-09-03T20:56:35.450686+05:00
  • 2008-09-03T20:56:35.450686-10:30

Alas, the format strings used by strptime and strftime have no directive that corresponds to UTC offsets in RFC 3339 format. A complete list of the directives they support can be found at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior, and the only UTC offset directive included in the list is %z:

%z

UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

Example: (empty), +0000, -0400, +1030

This doesn't match the format of an RFC 3339 offset, and indeed if we try to use %z in the format string and parse an RFC 3339 date, we'll fail:

>>> from datetime import datetime
>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

(Actually, the above is just what you'll see in Python 3. In Python 2 we'll fail for an even simpler reason, which is that strptime does not implement the %z directive at all in Python 2.)

The multiple answers here that recommend strptime all work around this by including a literal Z in their format string, which matches the Z from the question asker's example datetime string (and discards it, producing a datetime object without a timezone):

>>> datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

Since this discards timezone information that was included in the original datetime string, it's questionable whether we should regard even this result as correct. But more importantly, because this approach involves hard-coding a particular UTC offset into the format string, it will choke the moment it tries to parse any RFC 3339 datetime with a different UTC offset:

>>> datetime.strptime("2008-09-03T20:56:35.450686+05:00", "%Y-%m-%dT%H:%M:%S.%fZ")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2008-09-03T20:56:35.450686+05:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

Unless you're certain that you only need to support RFC 3339 datetimes in Zulu time, and not ones with other timezone offsets, don't use strptime. Use one of the many other approaches described in answers here instead.

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

Core Data: Quickest way to delete all instances of an entity

Swift:

let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
fetchRequest.includesPropertyValues = false

var error:NSError?
if let results = context.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] {
    for result in results {
        context.deleteObject(result)
    }

    var error:NSError?
    if context.save(&error) {
        // do something after save

    } else if let error = error {
        println(error.userInfo)
    }

} else if let error = error {
    println("error: \(error)")
}

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

How can I generate a 6 digit unique number?

$six_digit_random_number = mt_rand(100000, 999999);

As all numbers between 100,000 and 999,999 are six digits, of course.

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to get the month name in C#?

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

Fatal error: "No Target Architecture" in Visual Studio

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

IntelliJ: Error:java: error: release version 5 not supported

I did everything above but had to do one more thing in IntelliJ:

Project Structure > Modules

I had to change every module's "language level"

Import-CSV and Foreach

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
    $IP
}

Get-content Filename returns an array of strings for each line.

On the first string only, I split it based on ",". Dumping it into $IP_Array.

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "2.2.2.2") {
    Write-Host "Found $IP"
  }
}

Javascript replace with reference to matched group?

For the replacement string and the replacement pattern as specified by $. here a resume:

enter image description here

link to doc : here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")



Note:

If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

How to change the pop-up position of the jQuery DatePicker control

A very simple jquery function.

$(".datepicker").focus(function(event){
                var dim = $(this).offset();
                $("#ui-datepicker-div").offset({
                    top     :   dim.top - 180,
                    left    :   dim.left + 150
                });
            });

Python date string to date object

For single value the datetime.strptime method is the fastest

import arrow
from datetime import datetime
import pandas as pd

l = ['24052010']

%timeit _ = list(map(lambda x: datetime.strptime(x, '%d%m%Y').date(), l))
6.86 µs ± 56.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit _ = list(map(lambda x: x.date(), pd.to_datetime(l, format='%d%m%Y')))
305 µs ± 6.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit _ = list(map(lambda x: arrow.get(x, 'DMYYYY').date(), l))
46 µs ± 978 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

For a list of values the pandas pd.to_datetime is the fastest

l = ['24052010'] * 1000

%timeit _ = list(map(lambda x: datetime.strptime(x, '%d%m%Y').date(), l))
6.32 ms ± 89.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit _ = list(map(lambda x: x.date(), pd.to_datetime(l, format='%d%m%Y')))
1.76 ms ± 27.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit _ = list(map(lambda x: arrow.get(x, 'DMYYYY').date(), l))
44.5 ms ± 522 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

For ISO8601 datetime format the ciso8601 is a rocket

import ciso8601

l = ['2010-05-24'] * 1000

%timeit _ = list(map(lambda x: ciso8601.parse_datetime(x).date(), l))
241 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

How do I get the logfile from an Android device?

A simple way is to make your own log collector methods or even just an existing log collector app from the market.

For my apps I made a report functionality which sends the logs to my email (or even to another place - once you get the log you can do whether you want with it).

Here is a simple example about how to get the log file from a device:

In Python, how to display current time in readable format

import time
time.strftime('%H:%M%p %Z on %b %d, %Y')

This may come in handy

Which command do I use to generate the build of a Vue app?

if you used vue-cli and webpack when you created your project.

you can use just

npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.

Node.js – events js 72 throw er unhandled 'error' event

I had the same problem. I closed terminal and restarted node. This worked for me.

In Chrome 55, prevent showing Download button for HTML 5 video

Google has added a new feature since the last answer was posted here. You can now add the controlList attribute as shown here:

<video width="512" height="380" controls controlsList="nodownload">
    <source data-src="mov_bbb.ogg" type="video/mp4">
</video>

You can find all options of the controllist attribute here:

https://developers.google.com/web/updates/2017/03/chrome-58-media-updates#controlslist

Fastest way to tell if two files have the same contents in Unix/Linux?

I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:

cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'

I can then run this in the terminal or with a ssh to check files against a constant file.

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you only want the orientation tag and nothing else and don't like to include another huge javascript library I wrote a little code that extracts the orientation tag as fast as possible (It uses DataView and readAsArrayBuffer which are available in IE10+, but you can write your own data reader for older browsers):

_x000D_
_x000D_
function getOrientation(file, callback) {_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(e) {_x000D_
_x000D_
        var view = new DataView(e.target.result);_x000D_
        if (view.getUint16(0, false) != 0xFFD8)_x000D_
        {_x000D_
            return callback(-2);_x000D_
        }_x000D_
        var length = view.byteLength, offset = 2;_x000D_
        while (offset < length) _x000D_
        {_x000D_
            if (view.getUint16(offset+2, false) <= 8) return callback(-1);_x000D_
            var marker = view.getUint16(offset, false);_x000D_
            offset += 2;_x000D_
            if (marker == 0xFFE1) _x000D_
            {_x000D_
                if (view.getUint32(offset += 2, false) != 0x45786966) _x000D_
                {_x000D_
                    return callback(-1);_x000D_
                }_x000D_
_x000D_
                var little = view.getUint16(offset += 6, false) == 0x4949;_x000D_
                offset += view.getUint32(offset + 4, little);_x000D_
                var tags = view.getUint16(offset, little);_x000D_
                offset += 2;_x000D_
                for (var i = 0; i < tags; i++)_x000D_
                {_x000D_
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)_x000D_
                    {_x000D_
                        return callback(view.getUint16(offset + (i * 12) + 8, little));_x000D_
                    }_x000D_
                }_x000D_
            }_x000D_
            else if ((marker & 0xFF00) != 0xFF00)_x000D_
            {_x000D_
                break;_x000D_
            }_x000D_
            else_x000D_
            { _x000D_
                offset += view.getUint16(offset, false);_x000D_
            }_x000D_
        }_x000D_
        return callback(-1);_x000D_
    };_x000D_
    reader.readAsArrayBuffer(file);_x000D_
}_x000D_
_x000D_
// usage:_x000D_
var input = document.getElementById('input');_x000D_
input.onchange = function(e) {_x000D_
    getOrientation(input.files[0], function(orientation) {_x000D_
        alert('orientation: ' + orientation);_x000D_
    });_x000D_
}
_x000D_
<input id='input' type='file' />
_x000D_
_x000D_
_x000D_

values:

-2: not jpeg
-1: not defined

enter image description here

For those using Typescript, you can use the following code:

export const getOrientation = (file: File, callback: Function) => {
  var reader = new FileReader();

  reader.onload = (event: ProgressEvent) => {

    if (! event.target) {
      return;
    }

    const file = event.target as FileReader;
    const view = new DataView(file.result as ArrayBuffer);

    if (view.getUint16(0, false) != 0xFFD8) {
        return callback(-2);
    }

    const length = view.byteLength
    let offset = 2;

    while (offset < length)
    {
        if (view.getUint16(offset+2, false) <= 8) return callback(-1);
        let marker = view.getUint16(offset, false);
        offset += 2;

        if (marker == 0xFFE1) {
          if (view.getUint32(offset += 2, false) != 0x45786966) {
            return callback(-1);
          }

          let little = view.getUint16(offset += 6, false) == 0x4949;
          offset += view.getUint32(offset + 4, little);
          let tags = view.getUint16(offset, little);
          offset += 2;
          for (let i = 0; i < tags; i++) {
            if (view.getUint16(offset + (i * 12), little) == 0x0112) {
              return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
          }
        } else if ((marker & 0xFF00) != 0xFF00) {
            break;
        }
        else {
            offset += view.getUint16(offset, false);
        }
    }
    return callback(-1);
  };

  reader.readAsArrayBuffer(file);
}

How can I analyze a heap dump in IntelliJ? (memory leak)

You can also use VisualVM Launcher to launch VisualVM from within IDEA. https://plugins.jetbrains.com/plugin/7115?pr=idea I personally find this more convenient.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Get last key-value pair in PHP array

As the key is needed, the accepted solution doesn't work.

This:

end($array);
return array(key($array) => array_pop($array));

will return exactly as the example in the question.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Annotate other components with @Component, for example REST Resource classes.

@Component
public class AdressComp{
    .......
    ...//some code here    
}

@Component is a generic stereotype for any Spring managed component.

@Controller, @Service and @Repository are Specializations of @Component for specific use cases.

@Component in Spring

"Component Specialization"

MySQL selecting yesterday's date

While the chosen answer is correct and more concise, I'd argue for the structure noted in other answers:

SELECT * FROM your_table
WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
  AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));

If you just need a bare date without timestamp you could also write it as the following:

SELECT * FROM your_table
WHERE DateVisited >= CAST(NOW() - INTERVAL 1 DAY AS DATE)
  AND DateVisited <= CAST(NOW() AS DATE);

The reason for using CAST versus SUBDATE is CAST is ANSI SQL syntax. SUBDATE is a MySQL specific implementation of the date arithmetic component of CAST. Getting into the habit of using ANSI syntax can reduce headaches should you ever have to migrate to a different database. It's also good to be in the habit as a professional practice as you'll almost certainly work with other DBMS' in the future.

None of the major DBMS systems are fully ANSI compliant, but most of them implement the broad set of ANSI syntax whereas nearly none of them outside of MySQL and its descendants (MariaDB, Percona, etc) will implement MySQL-specific syntax.

How to retrieve absolute path given relative

In case of find, it's probably easiest to just give the absolute path for it to search in, e.g.:

find /etc
find `pwd`/subdir_of_current_dir/ -type f

How to get back to the latest commit after checking out a previous commit?

Came across this question just now and have something to add

To go to the most recent commit:

git checkout $(git log --branches -1 --pretty=format:"%H")

Explanation:

git log --branches shows log of commits from all local branches
-1 limit to one commit → most recent commit
--pretty=format:"%H" format to only show commit hash
git checkout $(...) use output of subshell as argument for checkout

Note:

This will result in a detached head though (because we checkout directly to the commit). This can be avoided by extracting the branch name using sed, explained below.


To go to the branch of the most recent commit:

git checkout $(git log --branches -1 --pretty=format:'%D' | sed 's/.*, //g')

Explanation:

git log --branches shows log of commits from all local branches
-1 limit to one commit → most recent commit
--pretty=format:"%D" format to only show ref names
| sed 's/.*, //g' ignore all but the last of multiple refs (*)
git checkout $(...) use output of subshell as argument for checkout

*) HEAD and remote branches are listed first, local branches are listed last in alphabetically descending order, so the one remaining will be the alphabetically first branch name

Note:

This will always only use the (alphabetically) first branch name if there are multiple for that commit.


Anyway, I think the best solution would just be to display the ref names for the most recent commit to know where to checkout to:

git log --branches -1 --pretty=format:'%D'

E.g. create the alias git top for that command.

telnet to port 8089 correct command

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

Convert textbox text to integer

int num = int.Parse(textBox.Text);

try this. It worked for me