Programs & Examples On #Comctl32

Cannot find or open the PDB file in Visual Studio C++ 2010

This can also happen if you don't have Modify permissions on the symbol cache directory configured in Tools, Options, Debugging, Symbols.

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I also had this issue and it arose because I re-made the project and then forgot to re-link it by reference in a dependent project.

Thus it was linking by reference to the old project instead of the new one.

It is important to know that there is a bug in re-adding a previously linked project by reference. You've got to manually delete the reference in the vcxproj and only then can you re-add it. This is a known issue in Visual studio according to msdn.

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

HTML table headers always visible at top of window when viewing a large table

I've encountered this problem very recently. Unfortunately, I had to do 2 tables, one for the header and one for the body. It's probably not the best approach ever but here goes:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
    <title>oh hai</title>_x000D_
</head>_x000D_
<body>_x000D_
    <table id="tableHeader">_x000D_
        <tr>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
        </tr>_x000D_
    </table>_x000D_
    <div style="height:50px; overflow:auto; width:250px">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This worked for me, it's probably not the elegant way but it does work. I'll investigate so see if I can do something better, but it allows for multiple tables.

Go read on the overflow propriety to see if it fits your need

How to place a file on classpath in Eclipse?

Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder.

How to pass an array into a SQL Server stored procedure

I've been searching through all the examples and answers of how to pass any array to sql server without the hassle of creating new Table type,till i found this linK, below is how I applied it to my project:

--The following code is going to get an Array as Parameter and insert the values of that --array into another table

Create Procedure Proc1 


@UserId int, //just an Id param
@s nvarchar(max)  //this is the array your going to pass from C# code to your Sproc

AS

    declare @xml xml

    set @xml = N'<root><r>' + replace(@s,',','</r><r>') + '</r></root>'

    Insert into UserRole (UserID,RoleID)
    select 
       @UserId [UserId], t.value('.','varchar(max)') as [RoleId]


    from @xml.nodes('//root/r') as a(t)
END 

Hope you enjoy it

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

Getting current device language in iOS?

In Swift:

let languageCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

Splitting dataframe into multiple dataframes

  • First, the method in the OP works, but isn't efficient. It may have seemed to run forever, because the dataset was long.
  • Use .groupby on the 'method' column, and create a dict of DataFrames with unique 'method' values as the keys, with a dict-comprehension.
    • .groupby returns a groupby object, that contains information about the groups, where g is the unique value in 'method' for each group, and d is the DataFrame for that group.
  • The value of each key in df_dict, will be a DataFrame, which can be accessed in the standard way, df_dict['key'].
  • The original question wanted a list of DataFrames, which can be done with a list-comprehension
    • df_list = [d for _, d in df.groupby('method')]
import pandas as pd
import seaborn as sns  # for test dataset

# load data for example
df = sns.load_dataset('planets')

# display(df.head())
            method  number  orbital_period   mass  distance  year
0  Radial Velocity       1         269.300   7.10     77.40  2006
1  Radial Velocity       1         874.774   2.21     56.95  2008
2  Radial Velocity       1         763.000   2.60     19.84  2011
3  Radial Velocity       1         326.030  19.40    110.62  2007
4  Radial Velocity       1         516.220  10.50    119.47  2009


# Using a dict-comprehension, the unique 'method' value will be the key
df_dict = {g: d for g, d in df.groupby('method')}

print(df_dict.keys())
[out]:
dict_keys(['Astrometry', 'Eclipse Timing Variations', 'Imaging', 'Microlensing', 'Orbital Brightness Modulation', 'Pulsar Timing', 'Pulsation Timing Variations', 'Radial Velocity', 'Transit', 'Transit Timing Variations'])

# or a specific name for the key, using enumerate (e.g. df1, df2, etc.)
df_dict = {f'df{i}': d for i, (g, d) in enumerate(df.groupby('method'))}

print(df_dict.keys())
[out]:
dict_keys(['df0', 'df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7', 'df8', 'df9'])
  • df_dict['df1].head(3) or df_dict['Astrometry'].head(3)
  • There are only 2 in this group
         method  number  orbital_period  mass  distance  year
113  Astrometry       1          246.36   NaN     20.77  2013
537  Astrometry       1         1016.00   NaN     14.98  2010
  • df_dict['df2].head(3) or df_dict['Eclipse Timing Variations'].head(3)
                       method  number  orbital_period  mass  distance  year
32  Eclipse Timing Variations       1         10220.0  6.05       NaN  2009
37  Eclipse Timing Variations       2          5767.0   NaN    130.72  2008
38  Eclipse Timing Variations       2          3321.0   NaN    130.72  2008
  • df_dict['df3].head(3) or df_dict['Imaging'].head(3)
     method  number  orbital_period  mass  distance  year
29  Imaging       1             NaN   NaN     45.52  2005
30  Imaging       1             NaN   NaN    165.00  2007
31  Imaging       1             NaN   NaN    140.00  2004

Alternatively

  • This is a manual method to create separate DataFrames using pandas: Boolean Indexing
  • This is similar to the accepted answer, but .loc is not required.
  • This is an acceptable method for creating a couple extra DataFrames.
  • The pythonic way to create multiple objects, is by placing them in a container (e.g. dict, list, generator, etc.), as shown above.
df1 = df[df.method == 'Astrometry']
df2 = df[df.method == 'Eclipse Timing Variations']

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

Length of a JavaScript object

If you are using AngularJS 1.x you can do things the AngularJS way by creating a filter and using the code from any of the other examples such as the following:

// Count the elements in an object
app.filter('lengthOfObject', function() {
  return function( obj ) {
    var size = 0, key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) size++;
    }
   return size;
 }
})

Usage

In your controller:

$scope.filterResult = $filter('lengthOfObject')($scope.object)

Or in your view:

<any ng-expression="object | lengthOfObject"></any>

How to view the Folder and Files in GAC?

Launch the program "Run" (Windows Vista/7/8: type it in the start menu search bar) and type: C:\windows\assembly\GAC_MSIL

Then move to the parent folder (Windows Vista/7/8: by clicking on it in the explorer bar) to see all the GAC files in a normal explorer window. You can now copy, add and remove files as everywhere else.

How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

Basic authentication for REST API using spring restTemplate

As of Spring 5.1 you can use HttpHeaders.setBasicAuth

Create Basic Authorization header:

String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...

Pass the headers to the RestTemplate:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

Change text (html) with .animate

Following the suggestion by JiminP....

I made a jsFiddle that will "smoothly" transition between two spans in case anyone is interested in seeing this in action. You have two main options:

  1. one span fades out at the same time as the other span is fading in
  2. one span fades out followed by the other span fading in.

The first time you click the button, number 1 above will occur. The second time you click the button, number 2 will occur. (I did this so you can visually compare the two effects.)

Try it Out: http://jsfiddle.net/jWcLz/594/

Details:

Number 1 above (the more difficult effect) is accomplished by positioning the spans directly on top of each other via CSS with absolute positioning. Also, the jQuery animates are not chained together, so that they can execute at the same time.

HTML

<div class="onTopOfEachOther">
    <span id='a'>Hello</span>
    <span id='b' style="display: none;">Goodbye</span>
</div>

<br />
<br />

<input type="button" id="btnTest" value="Run Test" />

CSS

.onTopOfEachOther {
    position: relative;
}
.onTopOfEachOther span {
    position: absolute;
    top: 0px;
    left: 0px;
}

JavaScript

$('#btnTest').click(function() {        
    fadeSwitchElements('a', 'b');    
}); 

function fadeSwitchElements(id1, id2)
{
    var element1 = $('#' + id1);
    var element2 = $('#' + id2);

    if(element1.is(':visible'))
    {
        element1.fadeToggle(500);
        element2.fadeToggle(500);
    }
    else
    {
         element2.fadeToggle(500, function() {
            element1.fadeToggle(500);
        });   
    }    
}

jQuery trigger event when click outside the element

function handler(event) {
 var target = $(event.target);
 if (!target.is("div.menuWraper")) {
  alert("outside");
 }
}
$("#myPage").click(handler);

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

This happened to me when I imported a Java 1.8 project from Eclipse Luna into Eclipse Kepler.

  1. Right click on project > Build path > configure build path...
  2. Select the Libraries tab, you should see the Java 1.8 jre with an error
  3. Select the java 1.8 jre and click the Remove button
  4. Add Library... > JRE System Library > Next > workspace default > Finish
  5. Click OK to close the properties window
  6. Go to the project menu > Clean... > OK

Et voilà, that worked for me.

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

How to make a char string from a C macro's value?

#define TEST_FUN_NAME #FUNC_NAME

see here

Swift - How to detect orientation changes

Swift 3 Above code updated:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

grep -r --include=*.{cc,h} "hello" .

This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this . (current) directory

From another stackoverflow question

How to define optional methods in Swift protocol?

The other answers here involving marking the protocol as "@objc" do not work when using swift-specific types.

struct Info {
    var height: Int
    var weight: Int
} 

@objc protocol Health {
    func isInfoHealthy(info: Info) -> Bool
} 
//Error "Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C"

In order to declare optional protocols that work well with swift, declare the functions as variables instead of func's.

protocol Health {
    var isInfoHealthy: (Info) -> (Bool)? { get set }
}

And then implement the protocol as follows

class Human: Health {
    var isInfoHealthy: (Info) -> (Bool)? = { info in
        if info.weight < 200 && info.height > 72 {
            return true
        }
        return false
    }
    //Or leave out the implementation and declare it as:  
    //var isInfoHealthy: (Info) -> (Bool)?
}

You can then use "?" to check whether or not the function has been implemented

func returnEntity() -> Health {
    return Human()
}

var anEntity: Health = returnEntity()

var isHealthy = anEntity.isInfoHealthy(Info(height: 75, weight: 150))? 
//"isHealthy" is true

babel-loader jsx SyntaxError: Unexpected token

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

Then in your webpack.config.js

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

How can I get a side-by-side diff when I do "git diff"?

If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff:

$ pip install webdiff
$ git webdiff

This offers a number of advantages over traditional GUI difftools like tkdiff in that it can give you syntax highlighting and show image diffs.

Read more about it here.

Insert Data Into Temp Table with Query

use as at end of query

Select * into #temp (select * from table1,table2) as temp_table

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

Android Failed to install HelloWorld.apk on device (null) Error

Restarting the device works for me. Using adb install can get the apk installed, but it's annoying to use it everytime you launch the app when debugging within eclipse.

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

Detecting negative numbers

You could use a ternary operator like this one, to make it a one liner.

echo ($profitloss < 0) ? 'false' : 'true';

Trying to Validate URL Using JavaScript

It's not practical to parse URLs using regex. A full implementation of the RFC1738 rules would result in an enormously long regex (assuming it's even possible). Certainly your current expression fails many valid URLs, and passes invalid ones.

Instead:

a. use a proper URL parser that actually follows the real rules. (I don't know of one for JavaScript; it would probably be overkill. You could do it on the server side though). Or,

b. just trim away any leading or trailing spaces, then check it has one of your preferred schemes on the front (typically ‘http://’ or ‘https://’), and leave it at that. Or,

c. attempt to use the URL and see what lies at the end, for example by sending it am HTTP HEAD request from the server-side. If you get a 404 or connection error, it's probably wrong.

it return true even if url is something like "http://wwww".

Well, that is indeed a perfectly valid URL.

If you want to check whether a hostname such as ‘wwww’ actually exists, you have no choice but to look it up in the DNS. Again, this would be server-side code.

How do you change the width and height of Twitter Bootstrap's tooltips?

Define the max-width with "important!" and use data-container="body"

CSS file

.tooltip-inner {
    max-width: 500px !important;
}

HTML tag

<a data-container="body" title="Looooooooooooooooooooooooooooooooooooooong Message" href="#" class="tooltiplink" data-toggle="tooltip" data-placement="bottom" data-html="true"><i class="glyphicon glyphicon-info-sign"></i></a>

JS script

$('.tooltiplink').tooltip();

Accessing MVC's model property from Javascript

Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.

var closedStatusId = @(Model.ClosedStatusId);

Changing CSS for last <li>

If you know there are three li's in the list you're looking at, for example, you could do this:

li + li + li { /* Selects third to last li */
}

In IE6 you can use expressions:

li {
    color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}

I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child selector gets better support.

Is it possible to opt-out of dark mode on iOS 13?

Objective-c version

 if (@available(iOS 13.0, *)) {
        _window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }

Java String - See if a string contains only numbers and not letters

Here is a sample. Find only the digits in a String and Process formation as needed.

text.replaceAll("\\d(?!$)", "$0 ");

For more info check google Docs https://developer.android.com/reference/java/util/regex/Pattern Where you can use Pattern

How to create a drop shadow only on one side of an element?

It is better to look up shadow:

.header{
    -webkit-box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
    -moz-box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
    box-shadow: 0 -8px 73px 0 rgba(0,0,0,0.2);
}

this code is currently using on stackoverflow web.

Concatenate text files with Windows command line, dropping leading lines

I use this, and it works well for me:

TYPE \\Server\Share\Folder\*.csv >> C:\Folder\ConcatenatedFile.csv

Of course, before every run, you have to DELETE C:\Folder\ConcatenatedFile.csv

The only issue is that if all files have headers, then it will be repeated in all files.

Should you commit .gitignore into the Git repos?

Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.

Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

Try:

SELECT convert(datetime, '23/07/2009', 103)

this is British/French standard.

Disabling swap files creation in vim

I found the answer here:

vim -n <file>

opens file without swapfile.

In addition:

set dir=/tmp

in .vimrc creates the swapfiles in /tmp.

How can I preview a merge in git?

Pull Request - I've used most of the already submitted ideas but one that I also often use is ( especially if its from another dev ) doing a Pull Request which gives a handy way to review all of the changes in a merge before it takes place. I know that is GitHub not git but it sure is handy.

href around input type submit

Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?

Either submit the form:

<input type="submit" class="button_active" value="1" />

Or go to another page:

<input type="button" class="button_active" onclick="location.href='1.html';" />

Limiting the number of characters per line with CSS

Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.

Set a default parameter value for a JavaScript function

_x000D_
_x000D_
function throwIfNoValue() {_x000D_
throw new Error('Missing argument');_x000D_
}_x000D_
function foo(argValue = throwIfNoValue()) {_x000D_
return argValue ;_x000D_
}
_x000D_
_x000D_
_x000D_

Here foo() is a function which has a parameter named argValue. If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue. This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.

This example has been taken from here

Convert InputStream to JSONObject

You can use this api https://code.google.com/p/google-gson/
It's simple and very useful,

Here's how to use the https://code.google.com/p/google-gson/ Api to resolve your problem

public class Test {
  public static void main(String... strings) throws FileNotFoundException  {
    Reader reader = new FileReader(new File("<fullPath>/json.js"));
    JsonElement elem = new JsonParser().parse(reader);
    Gson gson  = new GsonBuilder().create();
   TestObject o = gson.fromJson(elem, TestObject.class);
   System.out.println(o);
  }


}

class TestObject{
  public String fName;
  public String lName;
  public String toString() {
    return fName +" "+lName;
  }
}


json.js file content :

{"fName":"Mohamed",
"lName":"Ali"
}

What is the difference between synchronous and asynchronous programming (in node.js)

The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

CSS3 Transparency + Gradient

This is some really cool stuff! I needed pretty much the same, but with horizontal gradient from white to transparent. And it is working just fine! Here ist my code:

.gradient{
        /* webkit example */
        background-image: -webkit-gradient(
          linear, right top, left top, from(rgba(255, 255, 255, 1.0)),
          to(rgba(255, 255, 255, 0))
        );

        /* mozilla example - FF3.6+ */
        background-image: -moz-linear-gradient(
          right center,
          rgba(255, 255, 255, 1.0) 20%, rgba(255, 255, 255, 0) 95%
        );

        /* IE 5.5 - 7 */
        filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColorStr=#FFFFFF
        );

        /* IE8 uses -ms-filter for whatever reason... */
        -ms-filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColoStr=#FFFFFF
        );
    }

Check whether a table contains rows or not sql server 2005

Like Other said you can use something like that:

IF NOT EXISTS (SELECT 1 FROM Table)
  BEGIN 
    --Do Something
  END 
ELSE
  BEGIN
    --Do Another Thing
  END

How to mock private method for testing using PowerMock?

With no argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");

With String argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
                .withArguments(anyString()).thenReturn("mocked result");

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Create a circular button in BS3

Boostrap 3 has a component for exactly this. It's:

<span class="badge">100</span>

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

Stretch Image to Fit 100% of Div Height and Width

will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.

I am getting pretty close results with:

 .rightdiv img {
        max-width: 25vw;
        min-height: 100vh;
    }

the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.

filename.whl is not supported wheel on this platform

Change the filename to scipy-0.15.1-cp33-none-any.whl and then run this command:

pip install scipy-0.15.1-cp33-none-any.whl

It should work :-)

How do I convert a String to a BigInteger?

If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")

In this case you could do it like this way:

public  BigInteger stringToBigInteger(String string){
    byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
    StringBuilder asciiString = new StringBuilder();
    for(byte asciiCharacter:asciiCharacters){
        asciiString.append(Byte.toString(asciiCharacter));
    }
    BigInteger bigInteger = new BigInteger(asciiString.toString());
    return bigInteger;
}

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

The following code worked for me:

public vidOff() {

      let stream = this.video.nativeElement.srcObject;
      let tracks = stream.getTracks();

      tracks.forEach(function (track) {
          track.stop();
      });

      this.video.nativeElement.srcObject = null;
      this.video.nativeElement.stop();
  }

What's the difference between the atomic and nonatomic attributes?

If you are using atomic, it means the thread will be safe and read-only. If you are using nonatomic, it means the multiple threads access the variable and is thread unsafe, but it is executed fast, done a read and write operations; this is a dynamic type.

Using % for host when creating a MySQL user

If you want connect to user@'%' from localhost use mysql -h192.168.0.1 -uuser -p.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Python function as a function argument?

def x(a):
    print(a)
    return a

def y(a):
    return a

y(x(1))

How to sort by dates excel?

The hashes are just because your column width is not enough to display the "number".

About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).

Regards

Split string to equal length substrings in Java

I'd rather this simple solution:

String content = "Thequickbrownfoxjumps";
while(content.length() > 4) {
    System.out.println(content.substring(0, 4));
    content = content.substring(4);
}
System.out.println(content);

Java Equivalent of C# async/await?

async and await are syntactic sugars. The essence of async and await is state machine. The compiler will transform your async/await code into a state machine.

At the same time, in order for async/await to be really practicable in real projects, we need to have lots of Async I/O library functions already in place. For C#, most original synchronized I/O functions has an alternative Async version. The reason we need these Async functions is because in most cases, your own async/await code will boil down to some library Async method.

The Async version library functions in C# is kind of like the AsynchronousChannel concept in Java. For example, we have AsynchronousFileChannel.read which can either return a Future or execute a callback after the read operation is done. But it’s not exactly the same. All C# Async functions return Tasks (similar to Future but more powerful than Future).

So let’s say Java do support async/await, and we write some code like this:

public static async Future<Byte> readFirstByteAsync(String filePath) {
    Path path = Paths.get(filePath);
    AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);

    ByteBuffer buffer = ByteBuffer.allocate(100_000);
    await channel.read(buffer, 0, buffer, this);
    return buffer.get(0);
}

Then I would imagine the compiler will transform the original async/await code into something like this:

public static Future<Byte> readFirstByteAsync(String filePath) {

    CompletableFuture<Byte> result = new CompletableFuture<Byte>();

    AsyncHandler ah = new AsyncHandler(result, filePath);

    ah.completed(null, null);

    return result;
}

And here is the implementation for AsyncHandler:

class AsyncHandler implements CompletionHandler<Integer, ByteBuffer>
{
    CompletableFuture<Byte> future;
    int state;
    String filePath;

    public AsyncHandler(CompletableFuture<Byte> future, String filePath)
    {
        this.future = future;
        this.state = 0;
        this.filePath = filePath;
    }

    @Override
    public void completed(Integer arg0, ByteBuffer arg1) {
        try {
            if (state == 0) {
                state = 1;
                Path path = Paths.get(filePath);
                AsynchronousFileChannel channel = AsynchronousFileChannel.open(path);

                ByteBuffer buffer = ByteBuffer.allocate(100_000);
                channel.read(buffer, 0, buffer, this);
                return;
            } else {
                Byte ret = arg1.get(0);
                future.complete(ret);
            }

        } catch (Exception e) {
            future.completeExceptionally(e);
        }
    }

    @Override
    public void failed(Throwable arg0, ByteBuffer arg1) {
        future.completeExceptionally(arg0);
    }
}

Call an overridden method from super class in typescript

The key is calling the parent's method using super.methodName();

class A {
    // A protected method
    protected doStuff()
    {
        alert("Called from A");
    }

    // Expose the protected method as a public function
    public callDoStuff()
    {
        this.doStuff();
    }
}

class B extends A {

    // Override the protected method
    protected doStuff()
    {
        // If we want we can still explicitly call the initial method
        super.doStuff();
        alert("Called from B");
    }
}

var a = new A();
a.callDoStuff(); // Will only alert "Called from A"

var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"

Try it here

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

Get the first key name of a JavaScript object

I use Lodash for defensive coding reasons.

In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.

A "fully defensive" approach with Lodash would use both keys as well as get:

const firstKey = _.get(_.keys(ahash), 0);

Sum of two input value by jquery

use parseInt

   var total = parseInt(a) + parseInt(b);


    $('#total_price').val(total);

Delayed rendering of React components

I think the most intuitive way to do this is by giving the children a "wait" prop, which hides the component for the duration that was passed down from the parent. By setting the default state to hidden, React will still render the component immediately, but it won't be visible until the state has changed. Then, you can set up componentWillMount to call a function to show it after the duration that was passed via props.

var Child = React.createClass({
    getInitialState : function () {
        return({hidden : "hidden"});
    },
    componentWillMount : function () {
        var that = this;
        setTimeout(function() {
            that.show();
        }, that.props.wait);
    },
    show : function () {
        this.setState({hidden : ""});
    },
    render : function () {
        return (
            <div className={this.state.hidden}>
                <p>Child</p>
            </div>
        )
    }
});

Then, in the Parent component, all you would need to do is pass the duration you want a Child to wait before displaying it.

var Parent = React.createClass({
    render : function () {
        return (
            <div className="parent">
                <p>Parent</p>
                <div className="child-list">
                    <Child wait={1000} />
                    <Child wait={3000} />
                    <Child wait={5000} />
                </div>
            </div>
        )
    }
});

Here's a demo

Git pull till a particular commit

First, fetch the latest commits from the remote repo. This will not affect your local branch.

git fetch origin

Then checkout the remote tracking branch and do a git log to see the commits

git checkout origin/master
git log

Grab the commit hash of the commit you want to merge up to (or just the first ~5 chars of it) and merge that commit into master

git checkout master
git merge <commit hash>

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I am facing a similar problem here. Our users are migrating their jobs from freestyle to pipeline. They do not want Jenkinsfile stored in their repos(historical reason) and still want to use "Git Parameter" plugin

So we have to use use "Pipeline script" and develop a different plugin which works like "Git Parameter".

This new plugin does not integrate with SCM setting in the project. The plugin is at https://plugins.jenkins.io/list-git-branches-parameter

Hope it helps you as well

Find out who is locking a file on a network share

Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.

Use the Menu "Find Handle" and then you can type a path like this

\Device\LanmanRedirector\server\share\

How to Maximize window in chrome using webDriver (python)

Try

ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");

How to close form

for example, if you want to close a windows form when an action is performed there are two methods to do it

1.To close it directly

Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();

2.We can also hide form without closing it

 private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        Form2 f2 = new Form2();
        int flag = 0;
        string u, p;
        u = textBox1.Text;
        p = textBox2.Text;
        if(u=="username" && p=="pasword")
        {
            flag = 1;
        }
        else
        {
          MessageBox.Show("enter correct details");
        }
        if(flag==1)
        {
            f2.Show();
            this.Hide();
        }

    }

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

Select current date by default in ASP.Net Calendar control

DateTime.Now will not work, use DateTime.Today instead.

Oracle SqlPlus - saving output in a file but don't show on screen

set termout off doesn't work from the command line, so create a file e.g. termout_off.sql containing the line:

set termout off

and call this from the SQL prompt:

SQL> @termout_off

How to increase editor font size?

I have the latest version of Android Studio installed (3.6.1).

I navigated to: File->Settings->Editor->Font. The dialog displays a warning message (yellow triangle) indicating that the Font is defined in the color scheme.

(Editing the Font here had no effect.)

Editor Font

I clicked on the dialog's warning message link.

This navigated to: File->Settings->Editor->Color Scheme->Color Scheme Font.

(Now I could edit the Font for my current scheme.)

Editor Color Scheme Color Scheme Font

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

Check if an object belongs to a class in Java

The instanceof keyword, as described by the other answers, is usually what you would want. Keep in mind that instanceof will return true for superclasses as well.

If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via getClass(). And you can statically access a specific class via ClassName.class.

So for example:

if (a.getClass() == X.class) {
  // do something
}

In the above example, the condition is true if a is an instance of X, but not if a is an instance of a subclass of X.

In comparison:

if (a instanceof X) {
    // do something
  }

In the instanceof example, the condition is true if a is an instance of X, or if a is an instance of a subclass of X.

Most of the time, instanceof is right.

How can I get Git to follow symlinks?

Use hard links instead. This differs from a soft (symbolic) link. All programs, including git will treat the file as a regular file. Note that the contents can be modified by changing either the source or the destination.

On macOS (before 10.13 High Sierra)

If you already have git and Xcode installed, install hardlink. It's a microscopic tool to create hard links.

To create the hard link, simply:

hln source destination

macOS High Sierra update

Does Apple File System support directory hard links?

Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.

From APFS FAQ on developer.apple.com

Follow https://github.com/selkhateeb/hardlink/issues/31 for future alternatives.

On Linux and other Unix flavors

The ln command can make hard links:

ln source destination

On Windows (Vista, 7, 8, …)

Use mklink to create a junction on Windows:

mklink /j "source" "destination"

delete image from folder PHP

First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.

              if (file_exists($filePath)) 
               {
                 unlink($filePath);
                  echo "File Successfully Delete."; 
              }
              else
              {
               echo "File does not exists"; 
              }

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

How can I add an empty directory to a Git repository?

As described in other answers, Git is unable to represent empty directories in its staging area. (See the Git FAQ.) However, if, for your purposes, a directory is empty enough if it contains a .gitignore file only, then you can create .gitignore files in empty directories only via:

find . -type d -empty -exec touch {}/.gitignore \;

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Storing and Retrieving ArrayList values from hashmap

You could try using MultiMap instead of HashMap

Initialising it will require fewer lines of codes. Adding and retrieving the values will also make it shorter.

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

would become:

Multimap<String, Integer> multiMap = ArrayListMultimap.create();

You can check this link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

How do I find out if first character of a string is a number?

regular expression starts with number->'^[0-9]' 
Pattern pattern = Pattern.compile('^[0-9]');
 Matcher matcher = pattern.matcher(String);

if(matcher.find()){

System.out.println("true");
}

What is the difference between linear regression and logistic regression?

Logistic Regression is used in predicting categorical outputs like Yes/No, Low/Medium/High etc. You have basically 2 types of logistic regression Binary Logistic Regression (Yes/No, Approved/Disapproved) or Multi-class Logistic regression (Low/Medium/High, digits from 0-9 etc)

On the other hand, linear regression is if your dependent variable (y) is continuous. y = mx + c is a simple linear regression equation (m = slope and c is the y-intercept). Multilinear regression has more than 1 independent variable (x1,x2,x3 ... etc)

Use dynamic variable names in JavaScript

what they mean is no, you can't. there is no way to get it done. so it was possible you could do something like this

function create(obj, const){
// where obj is an object and const is a variable name
function const () {}

const.prototype.myProperty = property_value;
// .. more prototype

return new const();

}

having a create function just like the one implemented in ECMAScript 5.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

How to send multiple data fields via Ajax?

Try to use :

$.ajax({
    type: "GET",
    url: "something.php",
    data: { "b": data1, "c": data2 },   
    dataType: "html",
    beforeSend: function() {},
    error: function() {
        alert("Error");
    },
    success: function(data) {                                                    
        $("#result").empty();
        $("#result").append(data);
    }
});

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient.

The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.

Split a python list into other "sublists" i.e smaller lists

chunks = [data[100*i:100*(i+1)] for i in range(len(data)/100 + 1)]

This is equivalent to the accepted answer. For example, shortening to batches of 10 for readability:

data = range(35)
print [data[x:x+10] for x in xrange(0, len(data), 10)]
print [data[10*i:10*(i+1)] for i in range(len(data)/10 + 1)]

Outputs:

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]

Should I use past or present tense in git commit messages?

Stick with the present tense imperative because

  • it's good to have a standard
  • it matches tickets in the bug tracker which naturally have the form "implement something", "fix something", or "test something."

Concatenate a list of pandas dataframes together

You also can do it with functional programming:

from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

When do you use varargs in Java?

In Java doc of Var-Args it is quite clear the usage of var args:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

about usage it says:

"So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

What is the difference between declarations, providers, and import in NgModule?

  1. declarations: This property tells about the Components, Directives and Pipes that belong to this module.
  2. exports: The subset of declarations that should be visible and usable in the component templates of other NgModules.
  3. imports: Other modules whose exported classes are needed by component templates declared in this NgModule.
  4. providers: Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
  5. bootstrap: The main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.

CSS : center form in page horizontally and vertically

The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:

HTML

<body>
    <div class="login_div">
        <form class="login_form" action="#">
        </form>
    </div>
</body>

CSS

.login_div {
    position: absolute;

    width: 300px;
    height: 300px;

    /* Center form on page horizontally & vertically */
    top: 50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -150px;
}

.login_form {
    width: 300px;
    height: 300px;

    background: gray;
    border-radius: 10px;

    margin: 0;
    padding: 0;
}

JSFiddle

Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

Access Control Request Headers, is added to header in AJAX request with jQuery

This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.

$.ajax({
    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

What is the difference between a generative and a discriminative algorithm?

A generative algorithm model will learn completely from the training data and will predict the response.

A discriminative algorithm job is just to classify or differentiate between the 2 outcomes.

When is del useful in Python?

One place I've found del useful is cleaning up extraneous variables in for loops:

for x in some_list:
  do(x)
del x

Now you can be sure that x will be undefined if you use it outside the for loop.

Android Studio: Can't start Git

Try this...

  1. Make sure, have you installed git on your machine. If not you can download(Windows user) from here and install it your system. For Mac user can download from here

  2. Get location of git.exe Get location of git.exe

  3. Test git.exe manually test

  4. Now you can set your git.exe location in android studio.

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

Finding rows that don't contain numeric data in Oracle

I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!

SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');

The property 'Id' is part of the object's key information and cannot be modified

Another strange behavior in my case I have a table without any primary key.EF itself creates composite primary key using all columns i.e.:

 <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="No" />
       <PropertyRef Name="Code" />
   </Key>

And whenever I do any update operation it throws this exception:

The property 'Code' is part of the object's key information and cannot be modified.

Solution: remove table from EF diagram and go to your DB add primary key on table that is creating problem and re-add table to EF diagram it's all now it will have single key i.e.

<Key>
        <PropertyRef Name="ID" />
</Key>

What does 'corrupted double-linked list' mean

This might be caused due to different reasons, some user have mentioned other possibilities and I add my case:

I got this error when using multi-threading (both std::pthread and std::thread) and the error occurred because I forgot to lock a variable which multi threads may change at the same time. this error comes randomly in some runs but not all because ... you know accident between to threads is random.

That variable in my case was a global std::vector which I tried to push_back() something into it in a function called by threads.. and then I used a std::mutex and never got this error again.

may help some

Center Plot title in ggplot2

If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.

personal_theme = theme(plot.title = 
element_text(hjust = 0.5))

Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.

p1 + personal_theme
p2 + personal_theme
p3 + personal_theme

dat <- data.frame(
  time = factor(c("Lunch","Dinner"), 
levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill, 
fill=time)) + 
  geom_bar(colour="black", fill="#DD8888", 
width=.8, stat="identity") + 
  guides(fill=FALSE) +
  xlab("Time of day") + ylab("Total bill") +
  ggtitle("Average bill for 2 people")

p1 + personal_theme

How can I determine if a variable is 'undefined' or 'null'?

You can check if the value is undefined or null by simply using typeof:

if(typeof value == 'undefined'){

Java Constructor Inheritance

Because constructing your subclass object may be done in a different way from how your superclass is constructed. You may not want clients of the subclass to be able to call certain constructors available in the superclass.

A silly example:

class Super {
    protected final Number value;
    public Super(Number value){
        this.value = value;
    }
}

class Sub {
    public Sub(){ super(Integer.valueOf(0)); }
    void doSomeStuff(){
        // We know this.value is an Integer, so it's safe to cast.
        doSomethingWithAnInteger((Integer)this.value);
    }
}

// Client code:
Sub s = new Sub(Long.valueOf(666L)): // Devilish invocation of Super constructor!
s.doSomeStuff(); // throws ClassCastException

Or even simpler:

class Super {
    private final String msg;
    Super(String msg){
        if (msg == null) throw new NullPointerException();
        this.msg = msg;
    }
}
class Sub {
    private final String detail;
    Sub(String msg, String detail){
        super(msg);
        if (detail == null) throw new NullPointerException();
        this.detail = detail;
    }
    void print(){
        // detail is never null, so this method won't fail
        System.out.println(detail.concat(": ").concat(msg));
    }
}
// Client code:
Sub s = new Sub("message"); // Calling Super constructor - detail is never initialized!
s.print(); // throws NullPointerException

From this example, you see that you'd need some way of declaring that "I want to inherit these constructors" or "I want to inherit all constructors except for these", and then you'd also have to specify a default constructor inheritance preference just in case someone adds a new constructor in the superclass... or you could just require that you repeat the constructors from the superclass if you want to "inherit" them, which arguably is the more obvious way of doing it.

MySQL Data - Best way to implement paging?

Define OFFSET for the query. For example

page 1 - (records 01-10): offset = 0, limit=10;

page 2 - (records 11-20) offset = 10, limit =10;

and use the following query :

SELECT column FROM table LIMIT {someLimit} OFFSET {someOffset};

example for page 2:

SELECT column FROM table
LIMIT 10 OFFSET 10;

How do I add the contents of an iterable to a set?

for item in items:
   extant_set.add(item)

For the record, I think the assertion that "There should be one-- and preferably only one --obvious way to do it." is bogus. It makes an assumption that many technical minded people make, that everyone thinks alike. What is obvious to one person is not so obvious to another.

I would argue that my proposed solution is clearly readable, and does what you ask. I don't believe there are any performance hits involved with it--though I admit I might be missing something. But despite all of that, it might not be obvious and preferable to another developer.

Writing String to Stream and reading it back does not work

I think it would be a lot more productive to use a TextWriter, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;.

stringAsStream = new MemoryStream();

// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
{
  sWriter.Write("Lorem ipsum.");
}
stringAsStream.Position = 0L; // rewind

Note that:

StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)

Also, you don't have to create a new UnicodeEncoding() usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.

And then, finally (as others have said) you're trying to convert the bytes directly to chars, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.

Set transparent background of an imageview on Android

Color definitions with transparency information may be in the form

#AARRGGBB or #ARGB.

You can use also the shorter value for full transparency: #0000.

Other values are e.g.:

white  grey   black
#FFFF  #F888  #F000 - full color
#EFFF  #E888  #E000
#DFFF  #D888  #D000
#CFFF  #C888  #C000
#BFFF  #B888  #B000
#AFFF  #A888  #A000
#9FFF  #9888  #9000
#8FFF  #8888  #8000
#7FFF  #7888  #7000
#6FFF  #6888  #6000
#5FFF  #5888  #5000
#4FFF  #4888  #4000
#3FFF  #3888  #3000
#2FFF  #2888  #2000
#1FFF  #1888  #1000
#0FFF  #0888  #0000 - full transparency

What is the best way to paginate results in SQL Server

For SQL Server 2000 you can simulate ROW_NUMBER() using a table variable with an IDENTITY column:

DECLARE @pageNo int -- 1 based
DECLARE @pageSize int
SET @pageNo = 51
SET @pageSize = 20

DECLARE @firstRecord int
DECLARE @lastRecord int
SET @firstRecord = (@pageNo - 1) * @pageSize + 1 -- 1001
SET @lastRecord = @firstRecord + @pageSize - 1   -- 1020

DECLARE @orderedKeys TABLE (
  rownum int IDENTITY NOT NULL PRIMARY KEY CLUSTERED,
  TableKey int NOT NULL
)

SET ROWCOUNT @lastRecord
INSERT INTO @orderedKeys (TableKey) SELECT ID FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate

SET ROWCOUNT 0

SELECT t.*
FROM Orders t
  INNER JOIN @orderedKeys o ON o.TableKey = t.ID
WHERE o.rownum >= @firstRecord
ORDER BY o.rownum

This approach can be extended to tables with multi-column keys, and it doesn't incur the performance overhead of using OR (which skips index usage). The downside is the amount of temporary space used up if the data set is very large and one is near the last page. I did not test cursor performance in that case, but it might be better.

Note that this approach could be optimized for the first page of data. Also, ROWCOUNT was used since TOP does not accept a variable in SQL Server 2000.

How do I get this javascript to run every second?

You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

inject bean reference into a Quartz job in Spring?

This is the right answer http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring/15211030#15211030. and will work for most of the folks. But if your web.xml does is not aware of all applicationContext.xml files, quartz job will not be able to invoke those beans. I had to do an extra layer to inject additional applicationContext files

public class MYSpringBeanJobFactory extends SpringBeanJobFactory
        implements ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {

        try {
                PathMatchingResourcePatternResolver pmrl = new PathMatchingResourcePatternResolver(context.getClassLoader());
                Resource[] resources = new Resource[0];
                GenericApplicationContext createdContext = null ;
                    resources = pmrl.getResources(
                            "classpath*:my-abc-integration-applicationContext.xml"
                    );

                    for (Resource r : resources) {
                        createdContext = new GenericApplicationContext(context);
                        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(createdContext);
                        int i = reader.loadBeanDefinitions(r);
                    }

            createdContext.refresh();//important else you will get exceptions.
            beanFactory = createdContext.getAutowireCapableBeanFactory();

        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle)
            throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

You can add any number of context files you want your quartz to be aware of.

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

I have faced the same problem and I solved as give db_owner permission too to the Database user.

Unknown version of Tomcat was specified in Eclipse

Probably, you are trying to point the tomcat directory having the source folder. Please download the tomcat binary version from here .For Linux environments, there you can find .zip and .tar.gz files under core section. Please download and extract them. after that, if you point this extracted directory, eclipse will be able to identify the tomcat version. Eclipse was not able to find the version of tomcat, since the directory you pointed out didn't contain the conf folder. Hope this helps!

What are type hints in Python 3.5?

I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on type hinting.

In a nutshell: Type hinting is literally what the words mean. You hint the type of the object(s) you're using.

Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard. This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs (PyCharm and PyDev come to mind) that are limited due to the fact that they don't have any indicator of what type the objects are. As a result they resort to trying to infer the type with (as mentioned in the presentation) around 50% success rate.


To take two important slides from the type hinting presentation:

Why type hints?

  1. Helps type checkers: By hinting at what type you want the object to be the type checker can easily detect if, for instance, you're passing an object with a type that isn't expected.
  2. Helps with documentation: A third person viewing your code will know what is expected where, ergo, how to use it without getting them TypeErrors.
  3. Helps IDEs develop more accurate and robust tools: Development Environments will be better suited at suggesting appropriate methods when know what type your object is. You have probably experienced this with some IDE at some point, hitting the . and having methods/attributes pop up which aren't defined for an object.

Why use static type checkers?

  • Find bugs sooner: This is self-evident, I believe.
  • The larger your project the more you need it: Again, makes sense. Static languages offer a robustness and control that dynamic languages lack. The bigger and more complex your application becomes the more control and predictability (from a behavioral aspect) you require.
  • Large teams are already running static analysis: I'm guessing this verifies the first two points.

As a closing note for this small introduction: This is an optional feature and, from what I understand, it has been introduced in order to reap some of the benefits of static typing.

You generally do not need to worry about it and definitely don't need to use it (especially in cases where you use Python as an auxiliary scripting language). It should be helpful when developing large projects as it offers much needed robustness, control and additional debugging capabilities.


Type hinting with mypy:

In order to make this answer more complete, I think a little demonstration would be suitable. I'll be using mypy, the library which inspired Type Hints as they are presented in the PEP. This is mainly written for anybody bumping into this question and wondering where to begin.

Before I do that let me reiterate the following: PEP 484 doesn't enforce anything; it is simply setting a direction for function annotations and proposing guidelines for how type checking can/should be performed. You can annotate your functions and hint as many things as you want; your scripts will still run regardless of the presence of annotations because Python itself doesn't use them.

Anyways, as noted in the PEP, hinting types should generally take three forms:

  • Function annotations (PEP 3107).
  • Stub files for built-in/user modules.
  • Special # type: type comments that complement the first two forms. (See: What are variable annotations? for a Python 3.6 update for # type: type comments)

Additionally, you'll want to use type hints in conjunction with the new typing module introduced in Py3.5. In it, many (additional) ABCs (abstract base classes) are defined along with helper functions and decorators for use in static checking. Most ABCs in collections.abc are included, but in a generic form in order to allow subscription (by defining a __getitem__() method).

For anyone interested in a more in-depth explanation of these, the mypy documentation is written very nicely and has a lot of code samples demonstrating/describing the functionality of their checker; it is definitely worth a read.

Function annotations and special comments:

First, it's interesting to observe some of the behavior we can get when using special comments. Special # type: type comments can be added during variable assignments to indicate the type of an object if one cannot be directly inferred. Simple assignments are generally easily inferred but others, like lists (with regard to their contents), cannot.

Note: If we want to use any derivative of containers and need to specify the contents for that container we must use the generic types from the typing module. These support indexing.

# Generic List, supports indexing.
from typing import List

# In this case, the type is easily inferred as type: int.
i = 0

# Even though the type can be inferred as of type list
# there is no way to know the contents of this list.
# By using type: List[str] we indicate we want to use a list of strings.
a = []  # type: List[str]

# Appending an int to our list
# is statically not correct.
a.append(i)

# Appending a string is fine.
a.append("i")

print(a)  # [0, 'i']

If we add these commands to a file and execute them with our interpreter, everything works just fine and print(a) just prints the contents of list a. The # type comments have been discarded, treated as plain comments which have no additional semantic meaning.

By running this with mypy, on the other hand, we get the following response:

(Python3)jimmi@jim: mypy typeHintsCode.py
typesInline.py:14: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"

Indicating that a list of str objects cannot contain an int, which, statically speaking, is sound. This can be fixed by either abiding to the type of a and only appending str objects or by changing the type of the contents of a to indicate that any value is acceptable (Intuitively performed with List[Any] after Any has been imported from typing).

Function annotations are added in the form param_name : type after each parameter in your function signature and a return type is specified using the -> type notation before the ending function colon; all annotations are stored in the __annotations__ attribute for that function in a handy dictionary form. Using a trivial example (which doesn't require extra types from the typing module):

def annotated(x: int, y: str) -> bool:
    return x < y

The annotated.__annotations__ attribute now has the following values:

{'y': <class 'str'>, 'return': <class 'bool'>, 'x': <class 'int'>}

If we're a complete newbie, or we are familiar with Python 2.7 concepts and are consequently unaware of the TypeError lurking in the comparison of annotated, we can perform another static check, catch the error and save us some trouble:

(Python3)jimmi@jim: mypy typeHintsCode.py
typeFunction.py: note: In function "annotated":
typeFunction.py:2: error: Unsupported operand types for > ("str" and "int")

Among other things, calling the function with invalid arguments will also get caught:

annotated(20, 20)

# mypy complains:
typeHintsCode.py:4: error: Argument 2 to "annotated" has incompatible type "int"; expected "str"

These can be extended to basically any use case and the errors caught extend further than basic calls and operations. The types you can check for are really flexible and I have merely given a small sneak peak of its potential. A look in the typing module, the PEPs or the mypy documentation will give you a more comprehensive idea of the capabilities offered.

Stub files:

Stub files can be used in two different non mutually exclusive cases:

  • You need to type check a module for which you do not want to directly alter the function signatures
  • You want to write modules and have type-checking but additionally want to separate annotations from content.

What stub files (with an extension of .pyi) are is an annotated interface of the module you are making/want to use. They contain the signatures of the functions you want to type-check with the body of the functions discarded. To get a feel of this, given a set of three random functions in a module named randfunc.py:

def message(s):
    print(s)

def alterContents(myIterable):
    return [i for i in myIterable if i % 2 == 0]

def combine(messageFunc, itFunc):
    messageFunc("Printing the Iterable")
    a = alterContents(range(1, 20))
    return set(a)

We can create a stub file randfunc.pyi, in which we can place some restrictions if we wish to do so. The downside is that somebody viewing the source without the stub won't really get that annotation assistance when trying to understand what is supposed to be passed where.

Anyway, the structure of a stub file is pretty simplistic: Add all function definitions with empty bodies (pass filled) and supply the annotations based on your requirements. Here, let's assume we only want to work with int types for our Containers.

# Stub for randfucn.py
from typing import Iterable, List, Set, Callable

def message(s: str) -> None: pass

def alterContents(myIterable: Iterable[int])-> List[int]: pass

def combine(
    messageFunc: Callable[[str], Any],
    itFunc: Callable[[Iterable[int]], List[int]]
)-> Set[int]: pass

The combine function gives an indication of why you might want to use annotations in a different file, they some times clutter up the code and reduce readability (big no-no for Python). You could of course use type aliases but that sometime confuses more than it helps (so use them wisely).


This should get you familiarized with the basic concepts of type hints in Python. Even though the type checker used has been mypy you should gradually start to see more of them pop-up, some internally in IDEs (PyCharm,) and others as standard Python modules.

I'll try and add additional checkers/related packages in the following list when and if I find them (or if suggested).

Checkers I know of:

  • Mypy: as described here.
  • PyType: By Google, uses different notation from what I gather, probably worth a look.

Related Packages/Projects:

  • typeshed: Official Python repository housing an assortment of stub files for the standard library.

The typeshed project is actually one of the best places you can look to see how type hinting might be used in a project of your own. Let's take as an example the __init__ dunders of the Counter class in the corresponding .pyi file:

class Counter(Dict[_T, int], Generic[_T]):
        @overload
        def __init__(self) -> None: ...
        @overload
        def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
        @overload
        def __init__(self, iterable: Iterable[_T]) -> None: ...

Where _T = TypeVar('_T') is used to define generic classes. For the Counter class we can see that it can either take no arguments in its initializer, get a single Mapping from any type to an int or take an Iterable of any type.


Notice: One thing I forgot to mention was that the typing module has been introduced on a provisional basis. From PEP 411:

A provisional package may have its API modified prior to "graduating" into a "stable" state. On one hand, this state provides the package with the benefits of being formally part of the Python distribution. On the other hand, the core development team explicitly states that no promises are made with regards to the the stability of the package's API, which may change for the next release. While it is considered an unlikely outcome, such packages may even be removed from the standard library without a deprecation period if the concerns regarding their API or maintenance prove well-founded.

So take things here with a pinch of salt; I'm doubtful it will be removed or altered in significant ways, but one can never know.


** Another topic altogether, but valid in the scope of type-hints: PEP 526: Syntax for Variable Annotations is an effort to replace # type comments by introducing new syntax which allows users to annotate the type of variables in simple varname: type statements.

See What are variable annotations?, as previously mentioned, for a small introduction to these.

PDOException “could not find driver”

On my Windows machine, I had to give the absolute path to the extension dir in my php.ini:

extension_dir = "c:\php5\ext"

How to transform array to comma separated words string?

Directly from the docs:

$comma_separated = implode(",", $array);

How to use OpenSSL to encrypt/decrypt files?

Additional comments to mti2935 good answer.

It seems the higher iteration the better protection against brute force, and you should use a high iteration as you can afford performance/resource wise.

On my my old Intel i3-7100 encrypting a rather big file 1.5GB:

 time openssl enc -aes256 -e -pbkdf2 -iter 10000 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds: 2,564s

 time openssl enc -aes256 -e -pbkdf2 -iter 262144 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds:  2,775s

Not really any difference, didn't check memory usage though(?)

With today's GPUs, and even faster tomorrows, I guess billion brute-force iteration seems possible every seconds.

12 years ago a NVIDIA GeForce 8800 Ultra could iterate over 200.000 millions/sec iterations (MD5 hashing though)

source: Ainane-Barrett-Johnson-Vivar-OpenSSL.pdf

Giving a border to an HTML table row, <tr>

Left cell:

style="border-style:solid;border-width: 1px 0px 1px 1px;"

midd cell(s):

style="border-style:solid;border-width: 1px 0px 1px 0px;"

right cell:

style="border-style:solid;border-width: 1px 1px 1px 0px;"

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

To my experience, using SINGLE_USER helps most of the times, however, one should be careful: I have experienced occasions in which between the time I start the SINGLE_USER command and the time it is finished... apparently another 'user' had gotten the SINGLE_USER access, not me. If that happens, you're in for a tough job trying to get the access to the database back (in my case, it was a specific service running for a software with SQL databases that got hold of the SINGLE_USER access before I did). What I think should be the most reliable way (can't vouch for it, but it is what I will test in the days to come), is actually:
- stop services that may interfere with your access (if there are any)
- use the 'kill' script above to close all connections
- set the database to single_user immediately after that
- then do the restore

In STL maps, is it better to use map::insert than []?

One note is that you can also use Boost.Assign:

using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope

void something()
{
    map<int,int> my_map = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
}

How to call a button click event from another method

For me this worked in WPF

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            RoutedEventArgs routedEventArgs = new RoutedEventArgs(ButtonBase.ClickEvent, Button_OK);
            Button_OK.RaiseEvent(routedEventArgs);
        }
    }

Should try...catch go inside or outside a loop?

While performance might be the same and what "looks" better is very subjective, there is still a pretty big difference in functionality. Take the following example:

Integer j = 0;
    try {
        while (true) {
            ++j;

            if (j == 20) { throw new Exception(); }
            if (j%4 == 0) { System.out.println(j); }
            if (j == 40) { break; }
        }
    } catch (Exception e) {
        System.out.println("in catch block");
    }

The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.

Before any details, here the other example:

Integer i = 0;
    while (true) {
        try {
            ++i;

            if (i == 20) { throw new Exception(); }
            if (i%4 == 0) { System.out.println(i); }
            if (i == 40) { break; }

        } catch (Exception e) { System.out.println("in catch block"); }
    }

Same logic as above, only difference is that the try/catch block is now inside the while loop.

Here comes the output (while in try/catch):

4
8
12 
16
in catch block

And the other output (try/catch in while):

4
8
12
16
in catch block
24
28
32
36
40

There you have quite a significant difference:

while in try/catch breaks out of the loop

try/catch in while keeps the loop active

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Swift presentViewController

For those getting blank/black screens this code worked for me.

    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)

To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.

How do I copy the contents of one stream to another?

I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.

    public static void CopyTo(this Stream src, Stream dest)
    {
        int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
        byte[] buffer = new byte[size];
        int n;
        do
        {
            n = src.Read(buffer, 0, buffer.Length);
            dest.Write(buffer, 0, n);
        } while (n != 0);           
    }

    public static void CopyTo(this MemoryStream src, Stream dest)
    {
        dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));
    }

    public static void CopyTo(this Stream src, MemoryStream dest)
    {
        if (src.CanSeek)
        {
            int pos = (int)dest.Position;
            int length = (int)(src.Length - src.Position) + pos;
            dest.SetLength(length); 

            while(pos < length)                
                pos += src.Read(dest.GetBuffer(), pos, length - pos);
        }
        else
            src.CopyTo((Stream)dest);
    }

Any way to break if statement in PHP?

I'm late to the party but I wanted to contribute. I'm surprised that nobody suggested exit(). It's good for testing. I use it all the time and works like charm.

$a ='';
$b ='';
if($a == $b){
echo 'Clark Kent is Superman';
exit();
echo 'Clark Kent was never Superman';
}

The code will stop at exit() and everything after will not run.

Result

Clark Kent is Superman

It works with foreach() and while() as well. It works anywhere you place it really.

foreach($arr as $val)
{
  exit();
  echo "test";
}

echo "finish";

Result

nothing gets printed here.

Use it with a forloop()

for ($x = 2; $x < 12; $x++) {
    echo "Gru has $x minions <br>";
    if($x == 4){
    exit();
    }
}

Result

Gru has 2 minions
Gru has 3 minions
Gru has 4 minions

In a normal case scenario

$a ='Make hot chocolate great again!';
echo $a;
exit();
$b = 'I eat chocolate and make Charlie at the Factory pay for it.';

Result

Make hot chocolate great again!

Where is my .vimrc file?

From cmd (Windows):

C\Users\You> `vim foo.txt`

Now in Vim, enter command mode by typing: ":" (i.e. Shift + ;)

:tabedit $HOME/.vimrc

How do I obtain a list of all schemas in a Sql Server database

Try this query here:

SELECT * FROM sys.schemas

This will give you the name and schema_id for all defines schemas in the database you execute this in.

I don't really know what you mean by querying the "schema API" - these sys. catalog views (in the sys schema) are your best bet for any system information about databases and objects in those databases.

jQuery move to anchor location on page load

Put this right before the closing Body tag at the bottom of the page.

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

Best way to find os name and version in Unix/Linux platform

This work fine for all Linux environment.

#!/bin/sh
cat /etc/*-release

In Ubuntu:

$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"

or 12.04:

$ cat /etc/*-release

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"

In RHEL:

$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)

Or Use this Script:

#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.

OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`

GetVersionFromFile()
{
    VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}

if [ "${OS}" = "SunOS" ] ; then
    OS=Solaris
    ARCH=`uname -p` 
    OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
    OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
    KERNEL=`uname -r`
    if [ -f /etc/redhat-release ] ; then
        DIST='RedHat'
        PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/SuSE-release ] ; then
        DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
        REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
    elif [ -f /etc/mandrake-release ] ; then
        DIST='Mandrake'
        PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/debian_version ] ; then
        DIST="Debian `cat /etc/debian_version`"
        REV=""

    fi
    if [ -f /etc/UnitedLinux-release ] ; then
        DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
    fi

    OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"

fi

echo ${OSSTR}

How to bind a List<string> to a DataGridView control?

you can also use linq and anonymous types to achieve the same result with much less code as described here.

UPDATE: blog is down, here's the content:

(..) The values shown in the table represent the length of strings instead of string values (!) It may seem strange, but that’s how binding mechanism works by default – given an object it will try to bind to the first property of that object (the first property it can find). When passed an instance the String class the property it binds to is String.Length since there’s no other property that would provide the actual string itself.

That means that to get our binding right we need a wrapper object that will expose the actual value of a string as a property:

public class StringWrapper
    {
     string stringValue;
     public string StringValue { get { return stringValue; } set { stringValue = value; } }

     public StringWrapper(string s)
     {
     StringValue = s;
     }
  }   

   List<StringWrapper> testData = new List<StringWrapper>();

   // add data to the list / convert list of strings to list of string wrappers

  Table1.SetDataBinding(testdata);

While this solution works as expected it requires quite a few lines of code (mostly to convert list of strings to the list of string wrappers).

We can improve this solution by using LINQ and anonymous types- we’ll use LINQ query to create a new list of string wrappers (string wrapper will be an anonymous type in our case).

 var values = from data in testData select new { Value = data };

 Table1.SetDataBinding(values.ToList());

The last change we’re going to make is to move the LINQ code to an extension method:

public static class StringExtensions
  {
     public static IEnumerable CreateStringWrapperForBinding(this IEnumerable<string> strings)
     {
     var values = from data in strings
     select new { Value = data };

     return values.ToList();
     }

This way we can reuse the code by calling single method on any collection of strings:

Table1.SetDataBinding(testData.CreateStringWrapperForBinding());

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

How to access your website through LAN in ASP.NET

I'm not sure how stuck you are:

You must have a web server (Windows comes with one called IIS, but it may not be installed)

  1. Make sure you actually have IIS installed! Try typing http://localhost/ in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
  2. Set up IIS How to set up your first IIS Web site
  3. You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)

Installing your application

Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\. Read Installing ASP.NET Applications (IIS 6.0) for more information

Accessing the web site from another machine

In theory, once you have a web server running, and the application installed, you only need the IP address of your web server to access the application.

To find your IP address try: Start -> Run -> type cmd (hit ENTER) -> type ipconfig (hit ENTER)

Once

  • you have the IP address AND
  • IIS running AND
  • the application is installed

you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.

If you put your application in a directory called NewApp, you will need to type something like http://your_ip_address/NewApp/default.aspx

Turn off your firewall

If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

Unable to establish SSL connection, how do I fix my SSL cert?

The problem I faced was in client server environment. The client was trying to connect over http port 80 but wanted the server proxy to redirect the request to some other port and data was https. So basically asking secure information over http. So server should have http port 80 as well as the port client is requesting, let's say urla:1111\subB.

The issue was server was hosting this on some other port e,g urla:2222\subB; so the client was trying to access over 1111 was receiving the error. Correcting the port number should fix this issue. In this case to port number 1111.

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Can I restore a single table from a full mysql mysqldump file?

sed -n -e '/-- Table structure for table `my_table_name`/,/UNLOCK TABLES/p' database_file.sql > table_file.sql

This is a better solution than some of the others above because not all SQL dumps contain a DROP TABLE statement. This one will work will all kinds of dumps.

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Empty an array in Java / processing

Take double array as an example, if the initial input values array is not empty, the following code snippet is superior to traditional direct for-loop in time complexity:

public static void resetValues(double[] values) {
  int len = values.length;
  if (len > 0) {
    values[0] = 0.0;
  }
  for (int i = 1; i < len; i += i) {
    System.arraycopy(values, 0, values, i, ((len - i) < i) ? (len - i) : i);
  }
}

Value cannot be null. Parameter name: source

Somewhere inside the DbContext is a value that is IEnumerable and is queried with Any() (or Where() or Select() or any other LINQ-method), but this value is null.

Find out if you put a query together (somewhere outside your example code) where you are using a LINQ-method, or that you used an IEnumerable as a parameter which is NULL.

Tokenizing strings in C

Here is another strtok() implementation, which has the ability to recognize consecutive delimiters (standard library's strtok() does not have this)

The function is a part of BSD licensed string library, called zString. You are more than welcome to contribute :)

https://github.com/fnoyanisi/zString

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

As mentioned in previous posts, since strtok(), or the one I implmented above, relies on a static *char variable to preserve the location of last delimiter between consecutive calls, extra care should be taken while dealing with multi-threaded aplications.

Programmatically change the height and width of a UIImageView Xcode Swift

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

No module named _sqlite3

You need to install pysqlite in your python environment:

    $ pip install pysqlite

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The specific instructions for what you are looking for are in here: https://support.google.com/docs/answer/3093281

Remember your Google Spreadsheets Formulas might use semicolon (;) instead of comma (,) depending on Regional Settings.

Once made the replacement on some examples would look like this:

=GoogleFinance("CURRENCY:USDEUR")
=INDEX(GoogleFinance("USDEUR","price",today()-30,TODAY()),2,2)
=SPARKLINE(GoogleFinance("USDEUR","price",today()-30,today()))

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

How to perform a for loop on each character in a string in Bash?

${#var} returns the length of var

${var:pos:N} returns N characters from pos onwards

Examples:

$ words="abc"
$ echo ${words:0:1}
a
$ echo ${words:1:1}
b
$ echo ${words:2:1}
c

so it is easy to iterate.

another way:

$ grep -o . <<< "abc"
a
b
c

or

$ grep -o . <<< "abc" | while read letter;  do echo "my letter is $letter" ; done 

my letter is a
my letter is b
my letter is c

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

input file appears to be a text format dump. Please use psql

The answer above didn't work for me, this worked:

psql db_development < postgres_db.dump

Add new attribute (element) to JSON object using JavaScript

With ECMAScript since 2015 you can use Spread Syntax ( …three dots):

let  people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};

It's allow you to add sub objects:

people = { ...people, city: { state: 'California' }};

the result would be:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };

How to write to an existing excel file without overwriting data (using pandas)?

There is a better solution in pandas 0.24:

with pd.ExcelWriter(path, mode='a') as writer:
    s.to_excel(writer, sheet_name='another sheet', index=False)

before:

enter image description here

after:

enter image description here

so upgrade your pandas now:

pip install --upgrade pandas

How to create global variables accessible in all views using Express / Node.JS?

In your app.js you need add something like this

global.myvar = 100;

Now, in all your files you want use this variable, you can just access it as myvar

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.

How to draw circle in html page?

   <head>
       <style>

       #circle{
       width:200px;
       height:200px;
       border-radius:100px;
       background-color:red;
       }
       </style>
   </head>

    <body>
       <div id="circle"></div>
   </body>

simple and novice :)

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road... probably me!

I typed in instead of of in the ngFor expression.

Befor 2-beta.17, it should be:

<div *ngFor="#talk of talks">

As of beta.17, use the let syntax instead of #. See the UPDATE further down for more info.


Note that the ngFor syntax "desugars" into the following:

<template ngFor #talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor #talk [ngForIn]="talks">
  <div>...</div>
</template>

Since ngForIn isn't an attribute directive with an input property of the same name (like ngIf), Angular then tries to see if it is a (known native) property of the template element, and it isn't, hence the error.

UPDATE - as of 2-beta.17, use the let syntax instead of #. This updates to the following:

<div *ngFor="let talk of talks">

Note that the ngFor syntax "desugars" into the following:

<template ngFor let-talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor let-talk [ngForIn]="talks">
  <div>...</div>
</template>

How to fire a button click event from JavaScript in ASP.NET

document.FormName.btnSubmit.click(); 

works for me. Enjoy.

Is there possibility of sum of ArrayList without looping

Or switch to Groovy, it has a sum() function on a collection. [1,2,3,4,5,6].sum()

http://groovy.codehaus.org/JN1015-Collections

Runs on the same JVM as your java classes.

how to download file using AngularJS and calling MVC API?

Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:

$http({
    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    });
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL;
    a.target = '_blank';
    a.download = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"
    a.click(); //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error
});

Explanation of the code:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

Comparing the contents of two files in Sublime Text

UPDATE OCTOBER 2017 I never knew this feature existed in Sublime Text, but the interface appears to have changed slightly from the previous answer - at least on OS X. Here are the detailed steps I followed:

  1. In the Menu Bar click File -> Open...
  2. Navigate to the FOLDER that contains the files to be compared and with the FOLDER selected, click the Open button, this makes the FOLDERS sidebar appear
  3. In the FOLDERS sidebar, click on the first file to be compared
  4. Hold the Ctrl on Windows or ? on OS X, and click the second file
  5. With both files selected, right click on one and select Diff Files...

This opens a new tab showing the comparison. The first file in red, the second in green.

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I recently had this problem and it ended up being a port issue. My production SQL Server was set up at to be port 1427 instead 1433.

Just change the connection string to be

...data source=MySQLServerName,1427;initial catalog=MyDBName...

Hope this helps anyone who might be seeing this same issue.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

Spring Bean Scopes

About prototype bean(s) :

The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

ref : https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype

How to echo print statements while executing a sql script

I don't know if this helps:

suppose you want to run a sql script (test.sql) from the command line:

mysql < test.sql

and the contents of test.sql is something like:

SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";

The console will show something like:

CATALOG_NAME    SCHEMA_NAME            DEFAULT_CHARACTER_SET_NAME      
         def    information_schema     utf8
         def    mysql                  utf8
         def    performance_schema     utf8
         def    sys                    utf8
I like to party...

So you can execute terminal commands inside an sql statement by just using \!, provided the script is run via a command line.

\! #terminal_commands

Splitting String and put it on int array

Change the order in which you are doing things just a bit. You seem to be dividing by 2 for no particular reason at all.

While your application does not guarantee an input string of semi colon delimited variables you could easily make it do so:

package com;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        // Good practice to initialize before use
        Scanner keyboard = new Scanner(System.in);
        String input = "";
        // it's also a good idea to prompt the user as to what is going on
        keyboardScanner : for (;;) {
            input = keyboard.next();
            if (input.indexOf(",") >= 0) { // Realistically we would want to use a regex to ensure [0-9],...etc groupings 
                break keyboardScanner;  // break out of the loop
            } else { 
                keyboard = new Scanner(System.in);
                continue keyboardScanner; // recreate the scanner in the event we have to start over, just some cleanup
            }
        }

        String strarray[] = input.split(","); // move this up here      
        int intarray[] = new int[strarray.length];

        int count = 0; // Declare variables when they are needed not at the top of methods as there is no reason to allocate memory before it is ready to be used
        for (count = 0; count < intarray.length; count++) {
            intarray[count] = Integer.parseInt(strarray[count]);
        }

        for (int s : intarray) {
            System.out.println(s);
        }
    }
}

Android button with different background colors

You have to put the selector.xml file in the drwable folder. Then write: android:background="@drawable/selector". This takes care of the pressed and focussed states.

AngularJS: How can I pass variables between controllers?

The sample above worked like a charm. I just did a modification just in case I need to manage multiple values. I hope this helps!

app.service('sharedProperties', function () {

    var hashtable = {};

    return {
        setValue: function (key, value) {
            hashtable[key] = value;
        },
        getValue: function (key) {
            return hashtable[key];
        }
    }
});

How do you run JavaScript script through the Terminal?

I tried researching that too but instead ended up using jsconsole.com by Remy Sharp (he also created jsbin.com). I'm running on Ubuntu 12.10 so I had to create a special icon but if you're on Windows and use Chrome simply go to Tools>Create Application Shortcuts (note this doesn't work very well, or at all in my case, on Ubuntu). This site works very like the Mac jsc console: actually it has some cool features too (like loading libraries/code from a URL) that I guess jsc does not.

Hope this helps.

Asking the user for input until they give a valid response

You can write more general logic to allow user to enter only specific number of times, as the same use-case arises in many real-world applications.

def getValidInt(iMaxAttemps = None):
  iCount = 0
  while True:
    # exit when maximum attempt limit has expired
    if iCount != None and iCount > iMaxAttemps:
       return 0     # return as default value

    i = raw_input("Enter no")
    try:
       i = int(i)
    except ValueError as e:
       print "Enter valid int value"
    else:
       break

    return i

age = getValidInt()
# do whatever you want to do.

Losing Session State

I was having a situation in ASP.NET 4.0 where my session would be reset on every page request (and my SESSION_START code would run on each page request). This didn't happen to every user for every session, but it usually happened, and when it did, it would happen on each page request.

My web.config sessionState tag had the same setting as the one mentioned above.

cookieless="false"

When I changed it to the following...

cookieless="UseCookies"

... the problem seemed to go away. Apparently true|false were old choices from ASP.NET 1. Starting in ASP.Net 2.0, the enumerated choices started being available. I guess these options were deprecated. The "false" value has never presented a problem in the past - I've only noticed in on ASP.NET 4.0. I don't know if something has changed in 4.0 that no longer supports it correctly.

Also, I just found this out not long ago. Since the problem was intermittent before, I suppose I could still encounter it, but so far it's working with this new setting.

importing pyspark in python shell

On Windows 10 the following worked for me. I added the following environment variables using Settings > Edit environment variables for your account:

SPARK_HOME=C:\Programming\spark-2.0.1-bin-hadoop2.7
PYTHONPATH=%SPARK_HOME%\python;%PYTHONPATH%

(change "C:\Programming\..." to the folder in which you have installed spark)

Is there an alternative to string.Replace that is case-insensitive?

Based on Jeff Reddy's answer, with some optimisations and validations:

public static string Replace(string str, string oldValue, string newValue, StringComparison comparison)
{
    if (oldValue == null)
        throw new ArgumentNullException("oldValue");
    if (oldValue.Length == 0)
        throw new ArgumentException("String cannot be of zero length.", "oldValue");

    StringBuilder sb = null;

    int startIndex = 0;
    int foundIndex = str.IndexOf(oldValue, comparison);
    while (foundIndex != -1)
    {
        if (sb == null)
            sb = new StringBuilder(str.Length + (newValue != null ? Math.Max(0, 5 * (newValue.Length - oldValue.Length)) : 0));
        sb.Append(str, startIndex, foundIndex - startIndex);
        sb.Append(newValue);

        startIndex = foundIndex + oldValue.Length;
        foundIndex = str.IndexOf(oldValue, startIndex, comparison);
    }

    if (startIndex == 0)
        return str;
    sb.Append(str, startIndex, str.Length - startIndex);
    return sb.ToString();
}

How do I ignore files in Subversion?

Use the command svn status on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.

As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html. The book also describes more about using svn status.

Get the new record primary key ID from MySQL insert query?

If you need the value before insert a row:

CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
    RETURNS BIGINT
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

    DECLARE Value BIGINT;

    SELECT
        AUTO_INCREMENT INTO Value
    FROM
        information_schema.tables
    WHERE
        table_name = TableName AND
        table_schema = DATABASE();

    RETURN Value;

END

You can use this in a insert:

INSERT INTO
    document (Code, Title, Body)
VALUES (                
    sha1( concat (convert ( now() , char), ' ',   getAutoincrementalNextval ('document') ) ),
    'Title',
    'Body'
);

How to convert unix timestamp to calendar date moment.js

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment(value, 'MM/DD/YYYY', false).calendar(); 
    alert(dateString);
});

There is a strict mode and a Forgiving mode.

While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.

In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.

A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.

In strict mode, the following code results in 'Invalid Date' being displayed:

moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"

In forgiving mode using a format string, you get a wrong date:

moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"

another way would be

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment.unix(value).calendar(); 
    alert(dateString);
});

How do I split a string in Rust?

There is a special method split for struct String:

fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>

Split by char:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Split by string:

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

Split by closure:

let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

Spring Boot application as a Service

I just got around to doing this myself, so the following is where I am so far in terms of a CentOS init.d service controller script. It's working quite nicely so far, but I'm no leet Bash hacker, so I'm sure there's room for improvement, so thoughts on improving it are welcome.

First of all, I have a short config script /data/svcmgmt/conf/my-spring-boot-api.sh for each service, which sets up environment variables.

#!/bin/bash
export JAVA_HOME=/opt/jdk1.8.0_05/jre
export APP_HOME=/data/apps/my-spring-boot-api
export APP_NAME=my-spring-boot-api
export APP_PORT=40001

I'm using CentOS, so to ensure that my services are started after a server restart, I have a service control script in /etc/init.d/my-spring-boot-api:

#!/bin/bash
# description: my-spring-boot-api start stop restart
# processname: my-spring-boot-api
# chkconfig: 234 20 80

. /data/svcmgmt/conf/my-spring-boot-api.sh

/data/svcmgmt/bin/spring-boot-service.sh $1

exit 0

As you can see, that calls the initial config script to set up environment variables and then calls a shared script which I use for restarting all of my Spring Boot services. That shared script is where the meat of it all can be found:

#!/bin/bash

echo "Service [$APP_NAME] - [$1]"

echo "    JAVA_HOME=$JAVA_HOME"
echo "    APP_HOME=$APP_HOME"
echo "    APP_NAME=$APP_NAME"
echo "    APP_PORT=$APP_PORT"

function start {
    if pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    then
        echo "Service [$APP_NAME] is already running. Ignoring startup request."
        exit 1
    fi
    echo "Starting application..."
    nohup $JAVA_HOME/bin/java -jar $APP_HOME/$APP_NAME.jar \
        --spring.config.location=file:$APP_HOME/config/   \
        < /dev/null > $APP_HOME/logs/app.log 2>&1 &
}

function stop {
    if ! pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    then
        echo "Service [$APP_NAME] is not running. Ignoring shutdown request."
        exit 1
    fi

    # First, we will try to trigger a controlled shutdown using 
    # spring-boot-actuator
    curl -X POST http://localhost:$APP_PORT/shutdown < /dev/null > /dev/null 2>&1

    # Wait until the server process has shut down
    attempts=0
    while pkill -0 -f $APP_NAME.jar > /dev/null 2>&1
    do
        attempts=$[$attempts + 1]
        if [ $attempts -gt 5 ]
        then
            # We have waited too long. Kill it.
            pkill -f $APP_NAME.jar > /dev/null 2>&1
        fi
        sleep 1s
    done
}

case $1 in
start)
    start
;;
stop)
    stop
;;
restart)
    stop
    start
;;
esac
exit 0

When stopping, it will attempt to use Spring Boot Actuator to perform a controlled shutdown. However, in case Actuator is not configured or fails to shut down within a reasonable time frame (I give it 5 seconds, which is a bit short really), the process will be killed.

Also, the script makes the assumption that the java process running the appllication will be the only one with "my-spring-boot-api.jar" in the text of the process details. This is a safe assumption in my environment and means that I don't need to keep track of PIDs.

Node.js client for a socket.io server

After installing socket.io-client:

npm install socket.io-client

This is how the client code looks like:

var io = require('socket.io-client'),
socket = io.connect('localhost', {
    port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

Thanks alessioalex.

How to get current memory usage in android?

I refer few writings.

reference:

This getMemorySize() method is returned MemorySize that has total and free memory size.
I don't believe this code perfectly.
This code is testing on LG G3 cat.6 (v5.0.1)

    private MemorySize getMemorySize() {
        final Pattern PATTERN = Pattern.compile("([a-zA-Z]+):\\s*(\\d+)");

        MemorySize result = new MemorySize();
        String line;
        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
            while ((line = reader.readLine()) != null) {
                Matcher m = PATTERN.matcher(line);
                if (m.find()) {
                    String name = m.group(1);
                    String size = m.group(2);

                    if (name.equalsIgnoreCase("MemTotal")) {
                        result.total = Long.parseLong(size);
                    } else if (name.equalsIgnoreCase("MemFree") || name.equalsIgnoreCase("Buffers") ||
                            name.equalsIgnoreCase("Cached") || name.equalsIgnoreCase("SwapFree")) {
                        result.free += Long.parseLong(size);
                    }
                }
            }
            reader.close();

            result.total *= 1024;
            result.free *= 1024;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private static class MemorySize {
        public long total = 0;
        public long free = 0;
    }

I know that Pattern.compile() is expensive cost so You may move its code to class member.

How to generate a random string in Ruby

SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

Something from Devise

`require': no such file to load -- mkmf (LoadError)

You've Ruby 1.8 so you need to upgrade to at least 1.9 to make it working.

If so, then check How to install a specific version of a ruby gem?

If this won't help, then reinstalling ruby-dev again.