Programs & Examples On #Database link

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

Google Maps API v3: Can I setZoom after fitBounds?

I use this to ensure the zoom level does not exceed a set level so that I know satellite images will be available.

Add a listener to the zoom_changed event. This has the added benefit of controlling the zoom control on the UI also.

Only execute setZoom if you need to, so an if statement is preferable to Math.max or to Math.min

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() > 19 ) { 
        map.setZoom(19); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

To prevent zooming out too far:

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() < 6 ) { 
        map.setZoom(6); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

PHP error: Notice: Undefined index:

This are just php notice messages,it seems php.ini configurations are not according vtiger standards, you can disable this message by setting error reporting to E_ALL & ~E_NOTICE in php.ini For example error_reporting(E_ALL&~E_NOTICE) and then restart apache to reflect changes.

GitHub "fatal: remote origin already exists"

If you need to check which remote repos you have connected with your local repos, theres a cmd:

git remote -v

Now if you want to remove the remote repo (say, origin) then what you can do is:

git remote rm origin

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

How to validate email id in angularJs using ng-pattern

According to the answer of @scx ,I created a validation for GUI

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

And simply add :

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>

Python string class like StringBuilder in C#?

I have used the code of Oliver Crow (link given by Andrew Hare) and adapted it a bit to tailor Python 2.7.3. (by using timeit package). I ran on my personal computer, Lenovo T61, 6GB RAM, Debian GNU/Linux 6.0.6 (squeeze).

Here is the result for 10,000 iterations:

method1:  0.0538418292999 secs
process size 4800 kb
method2:  0.22602891922 secs
process size 4960 kb
method3:  0.0605459213257 secs
process size 4980 kb
method4:  0.0544030666351 secs
process size 5536 kb
method5:  0.0551080703735 secs
process size 5272 kb
method6:  0.0542731285095 secs
process size 5512 kb

and for 5,000,000 iterations (method 2 was ignored because it ran tooo slowly, like forever):

method1:  5.88603997231 secs
process size 37976 kb
method3:  8.40748500824 secs
process size 38024 kb
method4:  7.96380496025 secs
process size 321968 kb
method5:  8.03666186333 secs
process size 71720 kb
method6:  6.68192911148 secs
process size 38240 kb

It is quite obvious that Python guys have done pretty great job to optimize string concatenation, and as Hoare said: "premature optimization is the root of all evil" :-)

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

How to set background color of a button in Java GUI?

Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in here to get a better result:

enter image description here

Using a different font with twitter bootstrap

First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.

matplotlib get ylim values

 ymin, ymax = axes.get_ylim()

If you are using the plt api directly, you can avoid calls to axes altogether:

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    plt.ylim([-0.5, len(values) - 0.5])
    plt.xlabel('My x-axis title')
    plt.ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

   # close figure
    plt.close(fig)

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Matplotlib - global legend and title aside subplots

Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:

import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)

Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:

 import matplotlib.pyplot as plt
 # plot stuff
 # ...
 plt.suptitle("Title centered above all subplots", fontsize=14)

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

Using $_POST to get select option value from HTML

Like this:

<?php
  $option = $_POST['taskOption'];
?>

The index of the $_POST array is always based on the value of the name attribute of any HTML input.

Excel how to fill all selected blank cells with text

To put the same text in a certain number of cells do the following:

  1. Highlight the cells you want to put text into
  2. Type into the cell you're currently in the data you want to be repeated
  3. Hold Crtl and press 'return'

You will find that all the highlighted cells now have the same data in them. Have a nice day.

What is the keyguard in Android?

In a nutshell, it is your lockscreen.

PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

ASP.NET Web API session or something?

Now in 2017 with ASP.Net Core you can do it as explained here.

The Microsoft.AspNetCore.Session package provides middleware for managing session state.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

From the Docs: Introduction to session and application state in ASP.NET Core

Already tested on a working project

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

This solution worked for me :

I preinstalled the environnement with anaconda (here is the code)

conda create -n YOURENVNAME python=3.6 // 3.6> incompatible with keras
conda activate YOURENVNAME
conda install tensorflow-gpu
conda install -c anaconda keras
conda install -c anaconda scikit-learn
conda install matplotlib

but after I had still these warnings

2020-02-23 13:31:44.910213: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

2020-02-23 13:31:44.925815: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll

2020-02-23 13:31:44.941384: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll

2020-02-23 13:31:44.947427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll

2020-02-23 13:31:44.965893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll

2020-02-23 13:31:44.982990: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll

2020-02-23 13:31:44.990036: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found

How I solved the first warning : I just download a zip file wich contained all the cudnn files (dll, etc) here : https://developer.nvidia.com/cudnn

How I solved the second warning : I looked the last missing file (cudart64_101.dll) in my virtual env created by conda and I just copy/pasted it in the same lib folder than for the .dll cudnn

How to scroll to top of a div using jQuery?

You could just use:

<div id="GridDiv">
// gridview inside...
</div>

<a href="#GridDiv">Scroll to top</a>

Change div width live with jQuery

You can't just use a percentage width for the div? Setting the width to 50% will make it 50% as wide as the window (assuming there is no parent element with a width assigned to it).

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

get enum name from enum value

You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.

public static String getNameByCode(int code){
  for(RelationActiveEnum e : RelationActiveEnum.values()){
    if(code == e.value) return e.name();
  }
  return null;
}

And call it like this:

RelationActiveEnum.getNameByCode(3);

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.

What is the difference between gravity and layout_gravity in Android?

If a we want to set the gravity of content inside a view then we will use "android:gravity", and if we want to set the gravity of this view (as a whole) within its parent view then we will use "android:layout_gravity".

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

Disable cache for some images

Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.

header ("Pragma-directive: no-cache");
header ("Cache-directive: no-cache");
header ("Cache-control: no-cache");
header ("Pragma: no-cache");
header ("Expires: 0");

How do I concatenate a boolean to a string in Python?

answer = “True”

myvars = “the answer is” + answer

print(myvars)

That should give you the answer is True easily as you have stored answer as a string by using the quotation marks

Why can't Visual Studio find my DLL?

I've experienced same problem with same lib, found a solution here on SO:

Search MSDN for "How to: Set Environment Variables for Projects". (It's Project>Properties>Configuration Properties>Debugging "Environment" and "Merge Environment" properties for those who are in a rush.)

The syntax is NAME=VALUE and macros can be used (for example, $(OutDir)).

For example, to prepend C:\Windows\Temp to the PATH:

PATH=C:\WINDOWS\Temp;%PATH%

Similarly, to append $(TargetDir)\DLLS to the PATH:

PATH=%PATH%;$(TargetDir)\DLLS

(answered by Multicollinearity here: How do I set a path in visual studio?

Migrating from VMWARE to VirtualBox

This error occurs because VMware has a bug that uses the absolute path of the disk file in certain situations.

If you look at the top of that small *.vmdk file you'll likely see an incorrect absolute path to the original VMDK file that needs to be corrected.

Where is the itoa function in Linux?

itoa is not a standard C function. You can implement your own. It appeared in the first edition of Kernighan and Ritchie's The C Programming Language, on page 60. The second edition of The C Programming Language ("K&R2") contains the following implementation of itoa, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
}  

The function reverse used above is implemented two pages earlier:

 #include <string.h>

 /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
}  

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

The only way I've figured out how to do this is to have two properties for my class. One as the boolean for the programming API which is not included in the mapping. It's getter and setter reference a private char variable which is Y/N. I then have another protected property which is included in the hibernate mapping and it's getters and setters reference the private char variable directly.

EDIT: As has been pointed out there are other solutions that are directly built into Hibernate. I'm leaving this answer because it can work in situations where you're working with a legacy field that doesn't play nice with the built in options. On top of that there are no serious negative consequences to this approach.

Difference between Spring MVC and Spring Boot

Spring MVC is a sub-project of the Spring Framework, targeting design and development of applications that use the MVC (Model-View-Controller) pattern. Spring MVC is designed to integrate fully and completely with the Spring Framework and transitively, most other sub-projects.

Spring Boot can be understood quite well from this article by the Spring Engineering team. It is supposedly opinionated, i.e. it heavily advocates a certain style of rapid development, but it is designed well enough to accommodate exceptions to the rule, if you will. In short, it is a convention over configuration methodology that is willing to understand your need to break convention when warranted.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

For the Swift-inclined:

if let registration: AnyObject = NSClassFromString("UIUserNotificationSettings") { // iOS 8+
    let notificationTypes: UIUserNotificationType = (.Alert | .Badge | .Sound)
    let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(notificationSettings)
} else { // iOS 7
    application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}

Quick unix command to display specific lines in the middle of a file?

You can use the ex command, a standard Unix editor (part of Vim now), e.g.

  • display a single line (e.g. 2nd one):

    ex +2p -scq file.txt
    

    corresponding sed syntax: sed -n '2p' file.txt

  • range of lines (e.g. 2-5 lines):

    ex +2,5p -scq file.txt
    

    sed syntax: sed -n '2,5p' file.txt

  • from the given line till the end (e.g. 5th to the end of the file):

    ex +5,p -scq file.txt
    

    sed syntax: sed -n '2,$p' file.txt

  • multiple line ranges (e.g. 2-4 and 6-8 lines):

    ex +2,4p +6,8p -scq file.txt
    

    sed syntax: sed -n '2,4p;6,8p' file.txt

Above commands can be tested with the following test file:

seq 1 20 > file.txt

Explanation:

  • + or -c followed by the command - execute the (vi/vim) command after file has been read,
  • -s - silent mode, also uses current terminal as a default output,
  • q followed by -c is the command to quit editor (add ! to do force quit, e.g. -scq!).

Registry key Error: Java version has value '1.8', but '1.7' is required

I had this error on some windows services running Java. In the end, on my machine I tried to uninstall the other versions of java.

I left only 1.8 and now everything is working.

Concatenating elements in an array to a string

Arrays.toString() can be used to convert String Array to String. The extra characters can be removed by using Regex expressions or simply by using replace method.

Arrays.toString(strArray).replace(",", "").replace("[", "").replace("]", "");

Java 8 has introduced new method for String join public static String join(CharSequence delimiter, CharSequence... elements)

String.join("", strArray);

Get the generated SQL statement from a SqlCommand object?

Extended Kon's code to help debug a stored procedure:

    private void ExtractSqlCommandForDebugging(SqlCommand cmd)
    {
        string sql = "exec " + cmd.CommandText;
        bool first = true;
        foreach (SqlParameter p in cmd.Parameters)
        {
            string value = ((p.Value == DBNull.Value) ? "null"
                            : (p.Value is string) ? "'" + p.Value + "'"
                            : p.Value.ToString());
            if (first)
            {
                sql += string.Format(" {0}={1}", p.ParameterName, value);
                first = false;
            }
            else
            {
                sql += string.Format("\n , {0}={1}", p.ParameterName, value);
            }
        }
        sql += "\nGO";
        Debug.WriteLine(sql);
    }

In my first test case, it generated:

exec dbo.MyStoredProcName @SnailMail=False
 , @Email=True
 , @AcceptSnailMail=False
 , @AcceptEmail=False
 , @DistanceMiles=-1
 , @DistanceLocationList=''
 , @ExcludeDissatisfied=True
 , @ExcludeCodeRed=True
 , @MinAge=null
 , @MaxAge=18
 , @GenderTypeID=-1
 , @NewThisYear=-1
 , @RegisteredThisYear=-1
 , @FormersTermGroupList=''
 , @RegistrationStartDate=null
 , @RegistrationEndDate=null
 , @DivisionList='25'
 , @LocationList='29,30'
 , @OneOnOneOPL=-1
 , @JumpStart=-1
 , @SmallGroup=-1
 , @PurchasedEAP=-1
 , @RedeemedEAP=-1
 , @ReturnPlanYes=False
 , @MinNetPromoter=-1
 , @MinSurveyScore=-1
 , @VIPExclusionTypes='-2'
 , @FieldSelectionMask=65011584
 , @DisplayType=0
GO

You will probably need to add some more conditional "..is..." type assignments, e.g. for dates and times.

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

Gson library in Android Studio

Gradle:

dependencies {
   implementation 'com.google.code.gson:gson:2.8.5'
}

Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version> 
</dependency>

Gson jar downloads are available from Maven Central.

How to write a:hover in inline CSS?

While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.

Approach CSS only

CSS


/* Set your parent color for the inherit property */
.sidebar {
  color: green;
}

/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
  color: inherit
}

.list-item a:hover {
  color: inherit
}

/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
  color: inherit !important;
}

Then your markup will be somewhat like:

Markup

<nav class="sidebar">
  <ul>
    <li class="list-item">
      <a
        href="/foo"
        class="dynamic-hover-color"
        style="color: #{{category.color}};"
      >
        Category
      </a>
    </li>
  </ul>
</nav>

I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)

How to add an image to an svg container using D3.js

I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);            
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));    
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`

How to have comments in IntelliSense for function in Visual Studio?

What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):

C#

///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
     return "blah";
}

VB

'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
    Return "blah"
End Function

Get a random boolean in python?

Adam's answer is quite fast, but I found that random.getrandbits(1) to be quite a lot faster. If you really want a boolean instead of a long then

bool(random.getrandbits(1))

is still about twice as fast as random.choice([True, False])

Both solutions need to import random

If utmost speed isn't to priority then random.choice definitely reads better

$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))" 
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop  # not takes about 20us of this

Added this one after seeing @Pavel's answer

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop

Formatting text in a TextBlock

You can do this in XAML easily enough:

<TextBlock>
  Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>

Concatenating Column Values into a Comma-Separated List

You can do a shortcut using coalesce to concatenate a series of strings from a record in a table, for example.

declare @aa varchar (200)
set @aa = ''

select @aa = 
    case when @aa = ''
    then CarName
    else @aa + coalesce(',' + CarName, '')
    end
  from Cars

print @aa

How to make a list of n numbers in Python and randomly select any number?

You can try this code

import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)

while count_list:
    value = count_list.pop()
    # do whatever you want with 'value'

MVC3 EditorFor readOnly

<div class="editor-field">
        @Html.EditorFor(model => model.userName)
</div>

Use jquery to disable

<script type="text/javascript">
   $(document).ready(function () {
      $('#userName').attr('disabled', true);
     });
</script>

How to sum columns in a dataTable?

There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable. 
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

I must add that if you do not need to filter the results, you can always pass an empty string:

sumObject = table.Compute("Sum(Total)", "")

How does setTimeout work in Node.JS?

The idea of non-blocking is that the loop iterations are quick. So to iterate for each tick should take short enough a time that the setTimeout will be accurate to within reasonable precision (off by maybe <100 ms or so).

In theory though you're right. If I write an application and block the tick, then setTimeouts will be delayed. So to answer you're question, who can assure setTimeouts execute on time? You, by writing non-blocking code, can control the degree of accuracy up to almost any reasonable degree of accuracy.

As long as javascript is "single-threaded" in terms of code execution (excluding web-workers and the like), that will always happen. The single-threaded nature is a huge simplification in most cases, but requires the non-blocking idiom to be successful.

Try this code out either in your browser or in node, and you'll see that there is no guarantee of accuracy, on the contrary, the setTimeout will be very late:

var start = Date.now();

// expecting something close to 500
setTimeout(function(){ console.log(Date.now() - start); }, 500);

// fiddle with the number of iterations depending on how quick your machine is
for(var i=0; i<5000000; ++i){}

Unless the interpreter optimises the loop away (which it doesn't on chrome), you'll get something in the thousands. Remove the loop and you'll see it's 500 on the nose...

Elegant way to read file into byte[] array in Java

This will also work:

import java.io.*;

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

What's the valid way to include an image with no src?

While there is no valid way to omit an image's source, there are sources which won't cause server hits. I recently had a similar issue with iframes and determined //:0 to be the best option. No, really!

Starting with // (omitting the protocol) causes the protocol of the current page to be used, preventing "insecure content" warnings in HTTPS pages. Skipping the host name isn't necessary, but makes it shorter. Finally, a port of :0 ensures that a server request can't be made (it isn't a valid port, according to the spec).

This is the only URL which I found caused no server hits or error messages in any browser. The usual choice — javascript:void(0) — will cause an "insecure content" warning in IE7 if used on a page served via HTTPS. Any other port caused an attempted server connection, even for invalid addresses. (Some browsers would simply make the invalid request and wait for them to time out.)

This was tested in Chrome, Safari 5, FF 3.6, and IE 6/7/8, but I would expect it to work in any browser, as it should be the network layer which kills any attempted request.

how to instanceof List<MyType>?

That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:

public class GenericList <T> extends ArrayList<T>
{
     private Class<T> genericType;

     public GenericList(Class<T> c)
     {
          this.genericType = c;
     }

     public Class<T> getGenericType()
     {
          return genericType;
     }
}

How to avoid using Select in Excel VBA

"... and am finding that my code would be more re-usable if I were able to use variables instead of Select functions."

While I cannot think of any more than an isolated handful of situations where .Select would be a better choice than direct cell referencing, I would rise to the defense of Selection and point out that it should not be thrown out for the same reasons that .Select should be avoided.

There are times when having short, time-saving macro sub routines assigned to hot-key combinations available with the tap of a couple of keys saves a lot of time. Being able to select a group of cells to enact the operational code on works wonders when dealing with pocketed data that does not conform to a worksheet-wide data format. Much in the same way that you might select a group of cells and apply a format change, selecting a group of cells to run special macro code against can be a major time saver.

Examples of Selection-based sub framework:

Public Sub Run_on_Selected()
    Dim rng As Range, rSEL As Range
    Set rSEL = Selection    'store the current selection in case it changes
    For Each rng In rSEL
        Debug.Print rng.Address(0, 0)
        'cell-by-cell operational code here
    Next rng
    Set rSEL = Nothing
End Sub

Public Sub Run_on_Selected_Visible()
    'this is better for selected ranges on filtered data or containing hidden rows/columns
    Dim rng As Range, rSEL As Range
    Set rSEL = Selection    'store the current selection in case it changes
    For Each rng In rSEL.SpecialCells(xlCellTypeVisible)
        Debug.Print rng.Address(0, 0)
        'cell-by-cell operational code here
    Next rng
    Set rSEL = Nothing
End Sub

Public Sub Run_on_Discontiguous_Area()
    'this is better for selected ranges of discontiguous areas
    Dim ara As Range, rng As Range, rSEL As Range
    Set rSEL = Selection    'store the current selection in case it changes
    For Each ara In rSEL.Areas
        Debug.Print ara.Address(0, 0)
        'cell group operational code here
        For Each rng In ara.Areas
            Debug.Print rng.Address(0, 0)
            'cell-by-cell operational code here
        Next rng
    Next ara
    Set rSEL = Nothing
End Sub

The actual code to process could be anything from a single line to multiple modules. I have used this method to initiate long running routines on a ragged selection of cells containing the filenames of external workbooks.

In short, don't discard Selection due to its close association with .Select and ActiveCell. As a worksheet property it has many other purposes.

(Yes, I know this question was about .Select, not Selection but I wanted to remove any misconceptions that novice VBA coders might infer.)

MySQL Workbench Dark Theme

try to disabled Dark Mode on Mysql Workbench run this on terminal

defaults write com.oracle.workbench.MySQLWorkbench NSRequiresAquaSystemAppearance -bool yes

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Set today's date as default date in jQuery UI datepicker

Its very simple you just add this script,

$("#mydate").datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date());

Here, setDate set today date & dateFormat define which format you want set or show.

Hope its simple script work..

Extracting an attribute value with beautifulsoup

I would actually suggest you a time saving way to go with this assuming that you know what kind of tags have those attributes.

suppose say a tag xyz has that attritube named "staininfo"..

full_tag = soup.findAll("xyz")

And i wan't you to understand that full_tag is a list

for each_tag in full_tag:
    staininfo_attrb_value = each_tag["staininfo"]
    print staininfo_attrb_value

Thus you can get all the attrb values of staininfo for all the tags xyz

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

You must modify the query like this

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

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

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

DROP TABLE #TMPGUARDIAN

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

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

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

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

Leave out quotes when copying from cell

To keep line breaks when pasting in notepad, replace this line in the macro:

strTemp = ActiveCell.Value

by:

strTemp = Replace(ActiveCell.Value, Chr(10), vbCrLf)

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..

So every visitor to my site helps in killing the sleeping processes..

<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

Add play-services-safetynet library in android build.gradle:

implementation 'com.google.android.gms:play-services-safetynet:+'

and add this code to your MainApplication.java:

@Override
  public void onCreate() {
    super.onCreate();
    upgradeSecurityProvider();
    SoLoader.init(this, /* native exopackage */ false);
  }

  private void upgradeSecurityProvider() {
    ProviderInstaller.installIfNeededAsync(this, new ProviderInstallListener() {
      @Override
      public void onProviderInstalled() {

      }

      @Override
      public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
//        GooglePlayServicesUtil.showErrorNotification(errorCode, MainApplication.this);
        GoogleApiAvailability.getInstance().showErrorNotification(MainApplication.this, errorCode);
      }
    });
  }

numbers not allowed (0-9) - Regex Expression in javascript

Something as simple as [a-z]+, or perhaps [\S]+, or even [a-zA-Z]+?

Database Structure for Tree Data Structure

Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.

The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.

The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;

Add Reference Assembly Screenshot

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

Two arrays in foreach loop

All fully tested

3 ways to create a dynamic dropdown from an array.

This will create a dropdown menu from an array and automatically assign its respective value.

Method #1 (Normal Array)

<?php

$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');

echo '<select name="countries">';

foreach($names AS $let=>$word){
    echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
 
?>


Method #2 (Normal Array)

<select name="countries">

<?php

$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>

</select>


Method #3 (Associative Array)

<?php

$my_array = array(
     'tn' => 'Tunisia',
     'us' => 'United States',
     'fr' => 'France'
);

echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
    echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

REST, HTTP DELETE and parameters

In addition to Alex's answer:

Note that http://server/resource/id?force_delete=true identifies a different resource than http://server/resource/id. For example, it is a huge difference whether you delete /customers/?status=old or /customers/.

How to use clock() in C++

#include <iostream>
#include <cstdio>
#include <ctime>

int main() {
    std::clock_t start;
    double duration;

    start = std::clock();

    /* Your algorithm here */

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout<<"printf: "<< duration <<'\n';
}

Difficulty with ng-model, ng-repeat, and inputs

I tried the solution above for my problem at it worked like a charm. Thanks!

http://jsfiddle.net/leighboone/wn9Ym/7/

Here is my version of that:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.models = [{
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }, {
        name: 'Device1',
        checked: true
    }];

}

and my HTML

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
         <h1>Fun with Fields and ngModel</h1>
        <p>names: {{models}}</p>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th></th>
                    <th>Feature 1</td>
                    <th>Feature 2</th>
                    <th>Feature 3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Device</td>
                   <td ng-repeat="modelCheck in models" class=""> <span>
                                    {{modelCheck.checked}}
                                </span>

                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Which devices?</label>
                    </td>
                    <td ng-repeat="model in models">{{model.name}}
                        <input type="checkbox" class="checkbox inline" ng-model="model.checked" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

Angular - How to apply [ngStyle] conditions

For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">

How to format strings in Java

I've wrote my simple method for it :

public class SomeCommons {
    /** Message Format like 'Some String {0} / {1}' with arguments */
    public static String msgFormat(String s, Object... args) {
        return new MessageFormat(s).format(args);
    }
}

so you can use it as:

SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");

What special characters must be escaped in regular expressions?

For Ionic (Typescript) you have to double slash in order to scape the characters. For example (this is to match some special characters):

"^(?=.*[\\]\\[!¡\'=ªº\\-\\_ç@#$%^&*(),;\\.?\":{}|<>\+\\/])"

Pay attention to this ] [ - _ . / characters. They have to be double slashed. If you don't do that, you are going to have a type error in your code.

Why is Event.target not Element in Typescript?

Could you create your own generic interface that extends Event. Something like this?

interface DOMEvent<T extends EventTarget> extends Event {
  target: T
}

Then you can use it like:

handleChange(event: DOMEvent<HTMLInputElement>) {
  this.setState({ value: event.target.value });
}

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

How to make node.js require absolute? (instead of relative)

I like to make a new node_modules folder for shared code, then let node and require do what it does best.

for example:

- node_modules // => these are loaded from your package.json
- app
  - node_modules // => add node-style modules
    - helper.js
  - models
    - user
    - car
- package.json
- .gitignore

For example, if you're in car/index.js you can require('helper') and node will find it!

How node_modules Work

node has a clever algorithm for resolving modules that is unique among rival platforms.

If you require('./foo.js') from /beep/boop/bar.js, node will look for ./foo.js in /beep/boop/foo.js. Paths that start with a ./ or ../ are always local to the file that calls require().

If however you require a non-relative name such as require('xyz') from /beep/boop/foo.js, node searches these paths in order, stopping at the first match and raising an error if nothing is found:

/beep/boop/node_modules/xyz
/beep/node_modules/xyz
/node_modules/xyz

For each xyz directory that exists, node will first look for a xyz/package.json to see if a "main" field exists. The "main" field defines which file should take charge if you require() the directory path.

For example, if /beep/node_modules/xyz is the first match and /beep/node_modules/xyz/package.json has:

{
  "name": "xyz",
  "version": "1.2.3",
  "main": "lib/abc.js"
}

then the exports from /beep/node_modules/xyz/lib/abc.js will be returned by require('xyz').

If there is no package.json or no "main" field, index.js is assumed:

/beep/node_modules/xyz/index.js

Div not expanding even with content inside

You have a fixed height on .infohold, so the .albumhold div will only add up to the height of .infohold (20px) + .albumpic (110px) plus any padding or margin which I haven't included there.

Try removing the fixed height on .infohold and see what happens.

Git Clone - Repository not found

Possibly you did login in another account, and that account doesn't have access rights to this repo, if you're using mac os, go to Keychain Access, search for gitlab.com and remove it and try to git clone again.

Throw keyword in function's signature

Well, while googling about this throw specification, I had a look at this article :- (http://blogs.msdn.com/b/larryosterman/archive/2006/03/22/558390.aspx)

I am reproducing a part of it here also, so that it can be used in future irrespective of the fact that the above link works or not.

   class MyClass
   {
    size_t CalculateFoo()
    {
        :
        :
    };
    size_t MethodThatCannotThrow() throw()
    {
        return 100;
    };
    void ExampleMethod()
    {
        size_t foo, bar;
        try
        {
            foo = CalculateFoo();
            bar = foo * 100;
            MethodThatCannotThrow();
            printf("bar is %d", bar);
        }
        catch (...)
        {
        }
    }
};

When the compiler sees this, with the "throw()" attribute, the compiler can completely optimize the "bar" variable away, because it knows that there is no way for an exception to be thrown from MethodThatCannotThrow(). Without the throw() attribute, the compiler has to create the "bar" variable, because if MethodThatCannotThrow throws an exception, the exception handler may/will depend on the value of the bar variable.

In addition, source code analysis tools like prefast can (and will) use the throw() annotation to improve their error detection capabilities - for example, if you have a try/catch and all the functions you call are marked as throw(), you don't need the try/catch (yes, this has a problem if you later call a function that could throw).

Creating email templates with Django

I have created Django Simple Mail to have a simple, customizable and reusable template for every transactional email you would like to send.

Emails contents and templates can be edited directly from django's admin.

With your example, you would register your email :

from simple_mail.mailer import BaseSimpleMail, simple_mailer


class WelcomeMail(BaseSimpleMail):
    email_key = 'welcome'

    def set_context(self, user_id, welcome_link):
        user = User.objects.get(id=user_id)
        return {
            'user': user,
            'welcome_link': welcome_link
        }


simple_mailer.register(WelcomeMail)

And send it this way :

welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
                   headers={}, cc=[], reply_to=[], fail_silently=False)

I would love to get any feedback.

makefiles - compile all c files at once

SRCS=$(wildcard *.c)

OBJS=$(SRCS:.c=.o)

all: $(OBJS)

sudo: port: command not found

if you use zsh.please add flowing string to the line 'export PATH="..."' in file '~/.zshrc'

:/opt/local/bin:/opt/local/sbin

Count distinct values

I think this link is pretty good.

Sample output from that link:

mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001   |                         2 |                264.33 | 
| CA002   |                         1 |                433.33 | 
| CA003   |                         2 |                256.67 | 
| CA004   |                         3 |                246.67 | 
| CA005   |                         3 |                245.75 | 
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)

Efficient SQL test query or validation query that will work across all (or most) databases

I use this for Firebird

select 1 from RDB$RELATION_FIELDS rows 1

How to split a delimited string into an array in awk?

Joke? :)

How about echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

This is my output:

p2> echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
112312

so I guess it's working after all..

Get selected row item in DataGrid WPF

if I select the second row -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText will be 646. This is VB, but you get it.

#define in Java

Comment space too small, so here is some more information for you on the use of static final. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:

You can see this in action by creating three classes (in separate files):

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

Compile these and run Test, which prints:

Int    = 0
Value  = A

Now, change Constants to have a different value for each and just compile class Constants. When you execute Test again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

Run Test without recompiling Test.java:

Int    = 0
Value  = X

Note that any other type used with static final is kept as a reference.

Similar to C/C++ #if/#endif, a constant literal or one defined through static final with primitives, used in a regular Java if condition and evaluates to false will cause the compiler to strip the byte code for the statements within the if block (they will not be generated).

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG to true then it would be.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

HTML5 and frameborder

I found a nice work around that will allow it to work in IE7 here. It bypasses the validator for the frameBorder attribute but keeps css for future browsers as explained in the post.

How to check that an element is in a std::set?

You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

For example: Suppose the set already has 20 as an element.

 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

If the element is newly inserted than pair::first will point to the position of new element in set.

Number of processors/cores in command line

I think the method you give is the most portable on Linux. Instead of spawning unnecessary cat and wc processes, you can shorten it a bit:

$ grep --count ^processor /proc/cpuinfo
2

How to append something to an array?

Use the Array.prototype.push method to append values to the end of an array:

_x000D_
_x000D_
// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);
_x000D_
_x000D_
_x000D_


You can use the push() function to append more than one value to an array in a single call:

_x000D_
_x000D_
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
_x000D_
_x000D_
_x000D_


Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

_x000D_
_x000D_
var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);
_x000D_
_x000D_
_x000D_

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

_x000D_
_x000D_
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
_x000D_
_x000D_
_x000D_

It also supports appending multiple values at once just like push.


Update

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.

_x000D_
_x000D_
const arr = [
  "Hi",
  "Hello",
  "Bonjour",
];

const newArr = [
  ...arr,
  "Salut",
];

console.log(newArr);
_x000D_
_x000D_
_x000D_

How do I format XML in Notepad++?

OK, here is how I did it in Notepad++:

  • Plugins
  • Plugin manager
  • Show plugin manager
  • Check XML tools
  • Install
  • Restart Notepad++
  • Open XML file
  • Plugins
  • XML tools
  • Pretty print (XML only -- with line breaks)

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

PHP ternary operator vs null coalescing operator

Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

How to enable GZIP compression in IIS 7.5

Filing this under #wow

Turns out that IIS has different levels of compression configurable from 1-9.

Some of my dynamic SOAP requests have been getting out of control recently. With the uncompressed SOAP being about 14MB and compressed 3MB.

I noticed that in Fiddler when I compressed my request under Transformer it came to about 470KB instead of the 3MB - so I figured there must be some way to get better compression.

Eventually found this very informative blog post

http://weblogs.asp.net/owscott/iis-7-compression-good-bad-how-much

I went ahead and ran this commnd (followed by iisreset):

C:\Windows\System32\Inetsrv\Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:9

Changed dynamic level up to 9 and now my compressed soap matches what Fiddler gave me - and it about 1/7th the size of the existing compressed file.

Milage will vary, but for SOAP this is a massive massive improvement.

Convert all data frame character columns to factors

I noticed "[" indexing columns fails to create levels when iterating:

for ( a_feature in convert.to.factors) {
feature.df[a_feature] <- factor(feature.df[a_feature]) }

It creates, e.g. for the "Status" column:

Status : Factor w/ 1 level "c(\"Success\", \"Fail\")" : NA NA NA ...

Which is remedied by using "[[" indexing:

for ( a_feature in convert.to.factors) {
feature.df[[a_feature]] <- factor(feature.df[[a_feature]]) }

Giving instead, as desired:

. Status : Factor w/ 2 levels "Success", "Fail" : 1 1 2 1 ...

How to Multi-thread an Operation Within a Loop in Python

You can split the processing into a specified number of threads using an approach like this:

import threading                                                                

def process(items, start, end):                                                 
    for item in items[start:end]:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')                                            


def split_processing(items, num_splits=4):                                      
    split_size = len(items) // num_splits                                       
    threads = []                                                                
    for i in range(num_splits):                                                 
        # determine the indices of the list this thread will handle             
        start = i * split_size                                                  
        # special case on the last chunk to account for uneven splits           
        end = None if i+1 == num_splits else (i+1) * split_size                 
        # create the thread                                                     
        threads.append(                                                         
            threading.Thread(target=process, args=(items, start, end)))         
        threads[-1].start() # start the thread we just created                  

    # wait for all threads to finish                                            
    for t in threads:                                                           
        t.join()                                                                



split_processing(items)

Trigger 404 in Spring-MVC controller?

Rewrite your method signature so that it accepts HttpServletResponse as a parameter, so that you can call setStatus(int) on it.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments

How to parse a query string into a NameValueCollection in .NET

There's a built-in .NET utility for this: HttpUtility.ParseQueryString

// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)

You may need to replace querystring with new Uri(fullUrl).Query.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

The same thing happened to me. Here is what I did in order to get it successfully installed. I downloaded KB2999226 update from Microsofts website here: https://www.microsoft.com/en-us/download/details.aspx?id=49093

After installing this package, I started the installation process again. That worked for me.

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

HTML list-style-type dash

Another way:

li:before {
  content: '\2014\00a0\00a0'; /* em-dash followed by two non-breaking spaces*/
}
li {
  list-style: none;
  text-indent: -1.5em;
  padding-left: 1.5em;    
}

HTML Input Box - Disable

You can Use both disabled or readonly attribute of input . Using disable attribute will omit that value at form submit, so if you want that values at submit event make them readonly instead of disable.

<input type="text" readonly> 

or

 <input type="text" disabled>

What is SuppressWarnings ("unchecked") in Java?

Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

Displaying splash screen for longer than default seconds

Swift 3

This is doable in a safe way by presenting the splash controller for what ever time you specify then remove it and display your normal rootViewController.

  1. First in LaunchingScreen.storyboard give your controller a StoryBoard identifier let's say "splashController"
  2. In Main.storyboard give your initial viewController a StoryBoard identifier let's say "initController". -This could be nav or tab bar etc...-

In AppDelegate you can create these 2 methods:

  1. private func extendSplashScreenPresentation(){
        // Get a refernce to LaunchScreen.storyboard
        let launchStoryBoard = UIStoryboard.init(name: "LaunchScreen", bundle: nil)
        // Get the splash screen controller
        let splashController = launchStoryBoard.instantiateViewController(withIdentifier: "splashController")
        // Assign it to rootViewController
        self.window?.rootViewController = splashController
        self.window?.makeKeyAndVisible()
        // Setup a timer to remove it after n seconds
        Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(dismissSplashController), userInfo: nil, repeats: false)
    }
    

2.

@objc private func dismissSplashController() {
    // Get a refernce to Main.storyboard
    let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
    // Get initial viewController
    let initController = mainStoryBoard.instantiateViewController(withIdentifier: "initController")
    // Assign it to rootViewController
    self.window?.rootViewController = initController
    self.window?.makeKeyAndVisible()
}

Now you call

 self.extendSplashScreenPresentation()

in didFinishLaunchingWithOptions.

You are set to go...

How do I view the SQL generated by the Entity Framework?

While there are good answers here, none solved my problem completely (I wished to get the entire SQL statement, including Parameters, from the DbContext from any IQueryable. The following code does just that. It is a combination of code snippets from Google. I have only tested it with EF6+.

Just an aside, this task took me way longer than I thought it would. Abstraction in Entity Framework is a bit much, IMHO.

First the using. You will need an explicit reference to 'System.Data.Entity.dll'.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data.Entity.Core.Objects;
using System.Data.Entity;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Reflection;

The following class converts an IQueryable into a DataTable. Modify as your need may be:

public class EntityFrameworkCommand
{
    DbContext Context;

    string SQL;

    ObjectParameter[] Parameters;

    public EntityFrameworkCommand Initialize<T>(DbContext context, IQueryable<T> query)
    {
        Context = context;
        var dbQuery = query as DbQuery<T>;
        // get the IInternalQuery internal variable from the DbQuery object
        var iqProp = dbQuery.GetType().GetProperty("InternalQuery", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        var iq = iqProp.GetValue(dbQuery, null);
        // get the ObjectQuery internal variable from the IInternalQuery object
        var oqProp = iq.GetType().GetProperty("ObjectQuery", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        var objectQuery = oqProp.GetValue(iq, null) as ObjectQuery<T>;
        SQL = objectQuery.ToTraceString();
        Parameters = objectQuery.Parameters.ToArray();
        return this;
    }

    public DataTable GetData()
    {
        DataTable dt = new DataTable();
        var connection = Context.Database.Connection;
        var state = connection.State;
        if (!(state == ConnectionState.Open))
            connection.Open();
        using (var cmd = connection.CreateCommand())
        {
            cmd.CommandText = SQL;
            cmd.Parameters.AddRange(Parameters.Select(p => new SqlParameter("@" + p.Name, p.Value)).ToArray());
            using (var da = DbProviderFactories.GetFactory(connection).CreateDataAdapter())
            {
                da.SelectCommand = cmd;
                da.Fill(dt);
            }
        }
        if (!(state == ConnectionState.Open))
            connection.Close();
        return dt;
    }
}

To use, simply call it as below:

var context = new MyContext();
var data = ....//Query, return type can be anonymous
    .AsQueryable();
var dt = new EntityFrameworkCommand()
    .Initialize(context, data)
    .GetData();

Update date + one year in mysql

You could use DATE_ADD : (or ADDDATE with INTERVAL)

UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR) 

Change application's starting activity

 <application
    android:icon="@drawable/YOUR_ICON"    <!-- THIS ICON(IMAGE) WILL BE SHOWN IN YOUR APPS -->
    android:label="MY APP NAME " >    <!-- HERE LABEL(APP NAME) -->
    <activity
        android:name=".application's starting activity"  <!-- (.)dot means current dir, if your activity is in another package then give full package name ex: com.xxx.Activity  -->
        android:label="LABEL FOR ACTIVITY "
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

How do I return clean JSON from a WCF Service?

When you are using GET Method the contract must be this.

[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();

with this we have a json without the boot parameter

Aldo Flores @alduar http://alduar.blogspot.com

Deleting Elements in an Array if Element is a Certain value VBA

When creating the array, why not just skip over the 0s and save yourself the time of having to worry about them later? As mentioned above, arrays are not well-suited for deletion.

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

Just set the selectIndex of the associated <select> tag to -1 as the last step of your processing event.

mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1; 

It works every time, removing the highlight and allowing you to select the same (or different) element again .

Remove icon/logo from action bar on android

    //disable application icon from ActionBar
    getActionBar().setDisplayShowHomeEnabled(false);

    //disable application name from ActionBar
    getActionBar().setDisplayShowTitleEnabled(false);

Custom domain for GitHub project pages

I just discovered, after a bit of frustration, that if you're using PairNIC, all you have to do is enable the "Web Forwarding" setting under "Custom DNS" and supply the username.github.io/project address and it will automatically set up both the apex and subdomain records for you. It appears to do exactly what's suggested in the accepted answer. However, it won't let you do the exact same thing by manually adding records. Very strange. Anyway, it took me a while to figure that out, so I thought I'd share to save everyone else the trouble.

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

Keep the h2 at the top, then pull-left on the p and pull-right on the login-box

<div class='container'>
  <div class='hero-unit'>

    <h2>Welcome</h2>

    <div class="pull-left">
      <p>Please log in</p>
    </div>

    <div id='login-box' class='pull-right control-group'>
        <div class='clearfix'>
            <input type='text' placeholder='Username' />
        </div>
        <div class='clearfix'>
            <input type='password' placeholder='Password' />
        </div>
        <button type='button' class='btn btn-primary'>Log in</button>
    </div>

    <div class="clearfix"></div>

  </div>
</div>

the default vertical-align on floated boxes is baseline, so the "Please log in" exactly lines up with the "Username" (check by changing the pull-right to pull-left).

Converting NSData to NSString in Objective c

Objective C includes a built-in way to detect a the encoding of a string embedded in NSData.

NSData* data = // Assign your NSData object...

NSString* string;
NSStringEncoding encoding = [NSString stringEncodingForData:data encodingOptions:nil convertedString:&string usedLossyConversion:nil];

How to find first element of array matching a boolean condition in JavaScript?

Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value.

const result = someArray.find(isNotNullNorUndefined);

Old answer:

I have to post an answer to stop these filter suggestions :-)

since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this?

You can use the some Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met. So we have to amend it a little:

function find(arr, test, ctx) {
    var result = null;
    arr.some(function(el, i) {
        return test.call(ctx, el, i, arr) ? ((result = el), true) : false;
    });
    return result;
}
var result = find(someArray, isNotNullNorUndefined);

Getting All Variables In Scope

In ECMAScript 6 it's more or less possible by wrapping the code inside a with statement with a proxy object. Note it requires non-strict mode and it's bad practice.

_x000D_
_x000D_
function storeVars(target) {_x000D_
  return new Proxy(target, {_x000D_
    has(target, prop) { return true; },_x000D_
    get(target, prop) { return (prop in target ? target : window)[prop]; }_x000D_
  });_x000D_
}_x000D_
var vars = {}; // Outer variable, not stored._x000D_
with(storeVars(vars)) {_x000D_
  var a = 1;   // Stored in vars_x000D_
  var b = 2;   // Stored in vars_x000D_
  (function() {_x000D_
    var c = 3; // Inner variable, not stored._x000D_
  })();_x000D_
}_x000D_
console.log(vars);
_x000D_
_x000D_
_x000D_

The proxy claims to own all identifiers referenced inside with, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let and const variables are not included.

Inspired by this answer by Bergi.

what is <meta charset="utf-8">?

The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.

UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

Absolute vs relative URLs

Let's say you have a site www.yourserver.com. In the root directory for web documents you have an images sub-directoy and in that you have myimage.jpg.

An absolute URL defines the exact location of the document, for example:

http://www.yourserver.com/images/myimage.jpg

A relative URL defines the location relative to the current directory, for example, given you are in the root web directory your image is in:

images/myimage.jpg

(relative to that root directory)

You should always use relative URLS where possible. If you move the site to www.anotherserver.com you would have to update all the absolute URLs that were pointing at www.yourserver.com, relative ones will just keep working as is.

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

How to "fadeOut" & "remove" a div in jQuery?

Have you tried this?

$("#notification").fadeOut(300, function(){ 
    $(this).remove();
});

That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

How to print last two columns using awk

using gawk exhibits the problem:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

Variable name as a string in Javascript

You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.

What determines the monitor my app runs on?

It's not exactly the answer to this question but I dealt with this problem with the Shift + Win + [left,right] arrow keys shortcut. You can move the currently active window to another monitor with it.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

How to create a multiline UITextfield?

You can fake a UITextField using UITextView. The problem you'll have is that you lose the place holder functionality.

If you choose to use a UITextView and need the placeholder, do this:

In your viewDidLoad set the color and text to placeholders:

myTxtView.textColor = .lightGray
myTxtView.text = "Type your thoughts here..."

Then make the placeholder disappear when your UITextView is selected:

func textViewDidBeginEditing (textView: UITextView) {
    if myTxtView.textColor.textColor == ph_TextColor && myTxtView.isFirstResponder() {
        myTxtView.text = nil
        myTxtView.textColor = .white
    }
}

When the user finishes editing, ensure there's a value. If there isn't, add the placeholder again:

func textViewDidEndEditing (textView: UITextView) {
    if myTxtView.text.isEmpty || myTxtView.text == "" {
        myTxtView.textColor = .lightGray
        myTxtView.text = "Type your thoughts here..."
    }
}

Other features you might need to fake:

UITextField's often capitalize every letter, you can add that feature to UITableView:

myTxtView.autocapitalizationType = .words

UITextField's don't usually scroll:

myTxtView.scrollEnabled = false

How to download a Nuget package without nuget.exe or Visual Studio extension?

Either make an account on the Nuget.org website, then log in, browse to the package you want and click on the Download link on the left menu.


Or guess the URL. They have the following format:

https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}

Then simply unzip the .nupkg file and extract the contents you need.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I sovled this errors by modifying the Database charset.Old Database charset is cp1252 and i conver to utf-8

Get HTML code using JavaScript with a URL

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<html>

<head>
    <script type="text/javascript">
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
              // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
              xmlhttp = new XMLHttpRequest();
            }
            else
            {
                // Code for Internet Explorer 6 and Internet Explorer 5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "ajax_info.txt", true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

phpMyAdmin says no privilege to create database, despite logged in as root user

I solved my issue like that. You need the change auth_type 'config' to 'http'. My older settings auth_type is 'config' then i changed to 'http' and problem solved.

When you changed that area and enter the phpMyAdmin, browser asks you a user and password. You just enter 'root' and dont fill the password area and press enter.

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'http';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

How do I use a char as the case in a switch-case?

Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).

What's the difference between ng-model and ng-bind

tosh's answer gets to the heart of the question nicely. Here's some additional information....

Filters & Formatters

ng-bind and ng-model both have the concept of transforming data before outputting it for the user. To that end, ng-bind uses filters, while ng-model uses formatters.

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

<div ng-bind="mystring | uppercase"></div>,

or more simply:

<div>{{mystring | uppercase}}</div>

Note that uppercase is a built-in angular filter, although you can also build your own filter.

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

Angular 1.3 also has getter/setter support for ngModel

Using android.support.v7.widget.CardView in my project (Eclipse)

In the most latest android, we implement card view like this:

build.gradle file:

dependencies {
    ...
    compile 'com.android.support:cardview-v7:24.0.0'
}

and in the xml file its referenced as:

<androidx.cardview.widget.CardView
…>
…
</androidx.cardview.widget.CardView>

this means its class has changed to: androidx.cardview.widget.CardView

How to calculate the median of an array?

Check out the Arrays.sort methods:

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html

You should also really abstract finding the median into its own method, and just return the value to the calling method. This will make testing your code much easier.

Download file and automatically save it to folder

If you don't want to use "WebClient" or/and need to use the System.Windows.Forms.WebBrowser e.g. because you want simulate a login first, you can use this extended WebBrowser which hooks the "URLDownloadToFile" Method from the Windows URLMON Lib and uses the Context of the WebBrowser

Infos: http://www.pinvoke.net/default.aspx/urlmon/URLDownloadToFile%20.html

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace dataCoreLib.Net.Webpage
{
        public class WebBrowserWithDownloadAbility : WebBrowser
        {
            /// <summary>
            /// The URLMON library contains this function, URLDownloadToFile, which is a way
            /// to download files without user prompts.  The ExecWB( _SAVEAS ) function always
            /// prompts the user, even if _DONTPROMPTUSER parameter is specified, for "internet
            /// security reasons".  This function gets around those reasons.
            /// </summary>
            /// <param name="callerPointer">Pointer to caller object (AX).</param>
            /// <param name="url">String of the URL.</param>
            /// <param name="filePathWithName">String of the destination filename/path.</param>
            /// <param name="reserved">[reserved].</param>
            /// <param name="callBack">A callback function to monitor progress or abort.</param>
            /// <returns>0 for okay.</returns>
            /// source: http://www.pinvoke.net/default.aspx/urlmon/URLDownloadToFile%20.html
            [DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)]
            static extern Int32 URLDownloadToFile(
                [MarshalAs(UnmanagedType.IUnknown)] object callerPointer,
                [MarshalAs(UnmanagedType.LPWStr)] string url,
                [MarshalAs(UnmanagedType.LPWStr)] string filePathWithName,
                Int32 reserved,
                IntPtr callBack);


            /// <summary>
            /// Download a file from the webpage and save it to the destination without promting the user
            /// </summary>
            /// <param name="url">the url with the file</param>
            /// <param name="destinationFullPathWithName">the absolut full path with the filename as destination</param>
            /// <returns></returns>
            public FileInfo DownloadFile(string url, string destinationFullPathWithName)
            {
                URLDownloadToFile(null, url, destinationFullPathWithName, 0, IntPtr.Zero);
                return new FileInfo(destinationFullPathWithName);
            }
        }
    }

Stop UIWebView from "bouncing" vertically?

Came across this searching for an answer and I eventually just lucked on an answer of my own by messing about. I did

[[webview scrollView] setBounces:NO];

and it worked.

MySQL VARCHAR size?

100 characters.

This is the var (variable) in varchar: you only store what you enter (and an extra 2 bytes to store length upto 65535)

If it was char(200) then you'd always store 200 characters, padded with 100 spaces

See the docs: "The CHAR and VARCHAR Types"

Display alert message and redirect after click on accept

that worked but try it this way.

echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';  
</script>";

alert on top then location next

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

How to get First and Last record from a sql query?

In all the exposed ways of do until now, must go through scan two times, one for the first row and one for the last row.

Using the Window Function "ROW_NUMBER() OVER (...)" plus "WITH Queries", you can scan only one time and get both items.

Window Function: https://www.postgresql.org/docs/9.6/static/functions-window.html

WITH Queries: https://www.postgresql.org/docs/9.6/static/queries-with.html

Example:

WITH scan_plan AS (
SELECT
    <some columns>,
    ROW_NUMBER() OVER (ORDER BY date DESC) AS first_row, /*It's logical required to be the same as major query*/
    ROW_NUMBER() OVER (ORDER BY date ASC) AS last_row /*It's rigth, needs to be the inverse*/
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC)

SELECT
    <some columns>
FROM scan_plan
WHERE scan_plan.first_row = 1 OR scan_plan.last_row = 1;

On that way you will do relations, filtrations and data manipulation only one time.

Try some EXPLAIN ANALYZE on both ways.

is there a tool to create SVG paths from an SVG file?

Surprised no one mentioned Illustrator's Save As > Format dropdown > .svg option.

Outputs an .svg file that contains the path (and the rest of the svg definition) within an .svg (xml) file.

The path itself is within <path d>.

Get drop down value

Like this:

$dd = document.getElementById("yourselectelementid");
$so = $dd.options[$dd.selectedIndex];

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
var keys = [];

for (var k in obj) keys.push(k);

console.log("total " + keys.length + " keys: " + keys);
_x000D_
_x000D_
_x000D_

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Taken from @J-Rou's comment

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

how to output every line in a file python

Firstly, as @l33tnerd said, f.close should be outside the for loop.

Secondly, you are only calling readline once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:

 if data.find('!masters') != -1:
     f = open('masters.txt')
     for line in f:
           print line,
           sck.send('PRIVMSG ' + chan + " " + line)
     f.close()

Finally, you were referring to the variable lines inside the loop; I assume you meant to refer to line.

Edit: Oh and you need to indent the contents of the if statement.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Give BinaryTree<T, Comparator>::Node a subtreeHeight data member, initialized to 0 in its constructor, and update automatically every time with:

template <typename T, typename Comparator>
inline void BinaryTree<T, Comparator>::Node::setLeft (std::shared_ptr<Node>& node) {
    const std::size_t formerLeftSubtreeSize = left ? left->subtreeSize : 0;
    left = node;
    if (node) {
        node->parent = this->shared_from_this();
        subtreeSize++;
        node->depthFromRoot = depthFromRoot + 1;
        const std::size_t h = node->subtreeHeight;
        if (right)
            subtreeHeight = std::max (right->subtreeHeight, h) + 1;
        else
            subtreeHeight = h + 1;
    }
    else {
        subtreeSize -= formerLeftSubtreeSize;
        subtreeHeight = right ? right->subtreeHeight + 1 : 0;
    }
}

template <typename T, typename Comparator>
inline void BinaryTree<T, Comparator>::Node::setRight (std::shared_ptr<Node>& node) {
    const std::size_t formerRightSubtreeSize = right ? right->subtreeSize : 0;
    right = node;
    if (node) {
        node->parent = this->shared_from_this();
        subtreeSize++;
        node->depthFromRoot = depthFromRoot + 1;
        const std::size_t h = node->subtreeHeight;
        if (left)
            subtreeHeight = std::max (left->subtreeHeight, h) + 1;
        else
            subtreeHeight = h + 1;
    }
    else {
        subtreeSize -= formerRightSubtreeSize;
        subtreeHeight = left ? left->subtreeHeight + 1 : 0;
    }
}

Note that data members subtreeSize and depthFromRoot are also updated. These functions are called when inserting a node (all tested), e.g.

template <typename T, typename Comparator>
inline std::shared_ptr<typename BinaryTree<T, Comparator>::Node>
BinaryTree<T, Comparator>::Node::insert (BinaryTree& tree, const T& t, std::shared_ptr<Node>& node) {
    if (!node) {
        std::shared_ptr<Node> newNode = std::make_shared<Node>(tree, t);
        node = newNode;
        return newNode;
    }
    if (getComparator()(t, node->value)) {
        std::shared_ptr<Node> newLeft = insert(tree, t, node->left);
        node->setLeft(newLeft);
    }
    else {
        std::shared_ptr<Node> newRight = insert(tree, t, node->right);
        node->setRight(newRight);
    }
    return node;
}

If removing a node, use a different version of removeLeft and removeRight by replacing subtreeSize++; with subtreeSize--;. Algorithms for rotateLeft and rotateRight can be adapted without much problem either. The following was tested and passed:

template <typename T, typename Comparator>
void BinaryTree<T, Comparator>::rotateLeft (std::shared_ptr<Node>& node) {  // The root of the rotation is 'node', and its right child is the pivot of the rotation.  The pivot will rotate counter-clockwise and become the new parent of 'node'.
    std::shared_ptr<Node> pivot = node->right;
    pivot->subtreeSize = node->subtreeSize;
    pivot->depthFromRoot--;
    node->subtreeSize--;  // Since 'pivot' will no longer be in the subtree rooted at 'node'.
    const std::size_t a = pivot->left ? pivot->left->subtreeHeight + 1 : 0;  // Need to establish node->heightOfSubtree before pivot->heightOfSubtree is established, since pivot->heightOfSubtree depends on it.
    node->subtreeHeight = node->left ? std::max(a, node->left->subtreeHeight + 1) : std::max<std::size_t>(a,1);
    if (pivot->right) {
        node->subtreeSize -= pivot->right->subtreeSize;  // The subtree rooted at 'node' loses the subtree rooted at pivot->right.
        pivot->subtreeHeight = std::max (pivot->right->subtreeHeight, node->subtreeHeight) + 1;
    }
    else
        pivot->subtreeHeight = node->subtreeHeight + 1;
    node->depthFromRoot++;
    decreaseDepthFromRoot(pivot->right);  // Recursive call for the entire subtree rooted at pivot->right.
    increaseDepthFromRoot(node->left);  // Recursive call for the entire subtree rooted at node->left.
    pivot->parent = node->parent;
    if (pivot->parent) {  // pivot's new parent will be its former grandparent, which is not nullptr, so the grandparent must be updated with a new left or right child (depending on whether 'node' was its left or right child).
        if (pivot->parent->left == node)
            pivot->parent->left = pivot;
        else
            pivot->parent->right = pivot;
    }
    node->setRightSimple(pivot->left);  // Since pivot->left->value is less than pivot->value but greater than node->value.  We use the NoSizeAdjustment version because the 'subtreeSize' values of 'node' and 'pivot' are correct already.
    pivot->setLeftSimple(node);
    if (node == root) {
        root = pivot;
        root->parent = nullptr; 
    }
}

where

inline void decreaseDepthFromRoot (std::shared_ptr<Node>& node) {adjustDepthFromRoot(node, -1);}
inline void increaseDepthFromRoot (std::shared_ptr<Node>& node) {adjustDepthFromRoot(node, 1);}

template <typename T, typename Comparator>
inline void BinaryTree<T, Comparator>::adjustDepthFromRoot (std::shared_ptr<Node>& node, int adjustment) {
    if (!node)
        return;
    node->depthFromRoot += adjustment;
    adjustDepthFromRoot (node->left, adjustment);
    adjustDepthFromRoot (node->right, adjustment);
}

Here is the entire code: http://ideone.com/d6arrv

Convert python datetime to epoch with strftime

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs... https://docs.python.org/2/library/time.html#module-time

Javascript form validation with password confirming

Just add onsubmit event handler for your form:

<form  action="insert.php" onsubmit="return myFunction()" method="post">

Remove onclick from button and make it input with type submit

<input type="submit" value="Submit">

And add boolean return statements to your function:

function myFunction() {
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    var ok = true;
    if (pass1 != pass2) {
        //alert("Passwords Do not match");
        document.getElementById("pass1").style.borderColor = "#E34234";
        document.getElementById("pass2").style.borderColor = "#E34234";
        return false;
    }
    else {
        alert("Passwords Match!!!");
    }
    return ok;
}

Remove credentials from Git

Execute the following command in a PowerShell console to clear Git Credentials Managers for Windows cache:

rm $env:LOCALAPPDATA\GitCredentialManager\tenant.cache

or in Cmd.exe

rm %LOCALAPPDATA%\GitCredentialManager\tenant.cache

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

Use Expect in a Bash script to provide a password to an SSH command

Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# Use the correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"
interact

Sample solution for bash could be:

#!/bin/bash
/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'

This will wait for Enter and then return to (for a moment) the interactive session.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

Returning data from Axios API

The axios library creates a Promise() object. Promise is a built-in object in JavaScript ES6. When this object is instantiated using the new keyword, it takes a function as an argument. This single function in turn takes two arguments, each of which are also functions — resolve and reject.

Promises execute the client side code and, due to cool Javascript asynchronous flow, could eventually resolve one or two things, that resolution (generally considered to be a semantically equivalent to a Promise's success), or that rejection (widely considered to be an erroneous resolution). For instance, we can hold a reference to some Promise object which comprises a function that will eventually return a response object (that would be contained in the Promise object). So one way we could use such a promise is wait for the promise to resolve to some kind of response.

You might raise we don't want to be waiting seconds or so for our API to return a call! We want our UI to be able to do things while waiting for the API response. Failing that we would have a very slow user interface. So how do we handle this problem?

Well a Promise is asynchronous. In a standard implementation of engines responsible for executing Javascript code (such as Node, or the common browser) it will resolve in another process while we don't know in advance what the result of the promise will be. A usual strategy is to then send our functions (i.e. a React setState function for a class) to the promise, resolved depending on some kind of condition (dependent on our choice of library). This will result in our local Javascript objects being updated based on promise resolution. So instead of getters and setters (in traditional OOP) you can think of functions that you might send to your asynchronous methods.

I'll use Fetch in this example so you can try to understand what's going on in the promise and see if you can replicate my ideas within your axios code. Fetch is basically similar to axios without the innate JSON conversion, and has a different flow for resolving promises (which you should refer to the axios documentation to learn).

GetCache.js

const base_endpoint = BaseEndpoint + "cache/";
// Default function is going to take a selection, date, and a callback to execute.
// We're going to call the base endpoint and selection string passed to the original function.
// This will make our endpoint.
export default (selection, date, callback) => {  
  fetch(base_endpoint + selection + "/" + date) 
     // If the response is not within a 500 (according to Fetch docs) our promise object
     // will _eventually_ resolve to a response. 
    .then(res => {
      // Lets check the status of the response to make sure it's good.
      if (res.status >= 400 && res.status < 600) {
        throw new Error("Bad response");
      }
      // Let's also check the headers to make sure that the server "reckons" its serving 
      //up json
      if (!res.headers.get("content-type").includes("application/json")) {
        throw new TypeError("Response not JSON");
      }
      return res.json();
    })
    // Fulfilling these conditions lets return the data. But how do we get it out of the promise? 
    .then(data => {
      // Using the function we passed to our original function silly! Since we've error 
      // handled above, we're ready to pass the response data as a callback.
      callback(data);
    })
    // Fetch's promise will throw an error by default if the webserver returns a 500 
    // response (as notified by the response code in the HTTP header). 
    .catch(err => console.error(err));
};

Now we've written our GetCache method, lets see what it looks like to update a React component's state as an example...

Some React Component.jsx

// Make sure you import GetCache from GetCache.js!

resolveData() {
    const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
    const setData = data => {
      this.setState({
        data: data,
        loading: false 
        // We could set loading to true and display a wee spinner 
        // while waiting for our response data, 
        // or rely on the local state of data being null.
      });
    };
  GetCache("mySelelection", date, setData);
  }

Ultimately, you don't "return" data as such, I mean you can but it's more idiomatic to change your way of thinking... Now we are sending data to asynchronous methods.

Happy Coding!

How to install a plugin in Jenkins manually

I have created a simple script that does the following:

  • Download one or more plugins to the plugin directory
  • Scan all plugins in that directory for missing dependencies
  • download this dependencies as well
  • loop until no open dependencies are left

The script requires no running jenkins - I use it to provision a docker box.

https://gist.github.com/micw/e80d739c6099078ce0f3

jQuery changing css class to div

$(document).ready(function () {

            $("#divId").toggleClass('cssclassname'); // toggle class
});

**OR**

$(document).ready(function() {
        $("#objectId").click(function() {  // click or other event to change the div class
                $("#divId").toggleClass("cssclassname");     // toggle class
        )}; 
)};

How to install pip for Python 3 on Mac OS X?

For a fresh new Mac, you need to follow below steps:-

  1. Make sure you have installed Xcode
  2. sudo easy_install pip
  3. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  4. brew doctor
  5. brew doctor
  6. brew install python3

And you are done, just type python3 on terminal and you will see python 3 installed.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

Without @Transactional annotation you can achieve the same goal with finding the entity from the DB and then removing that entity you got from the DB.

CrudRepositor -> void delete(T var1);

Convert JSON string to array of JSON objects in Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Changing the JFrame title

newTitle is a local variable where you create the fields. So when that functions ends, the variable newTitle, does not exist anymore. (The JTextField that was referenced by newTitle does still exist however.)

Thus, increase the scope of the variable, so that you can access it another method.

public SomeFrame extends JFrame {
   JTextField myTitle;//can be used anywhere in this class

   creationOfTheFields()
   {
   //other code
      myTitle = new JTextField("spam");  
      myTitle.setBounds(80, 40, 225, 20);
      options.add(myTitle);
   //blabla other code
   }

   private void New_Name()  
   {  
      this.setTitle(myTitle.getText());  
   } 
}

Select2 open dropdown on focus

For me using Select2.full.js Version 4.0.3 none of the above solutions was working the way it should be. So I wrote a combination of the solutions above. First of all I modified Select2.full.js to transfer the internal focus and blur events to jquery events as "Thomas Molnar" did in his answer.

EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'focus', 'blur'
    ];

And then I added the following code to handle focus and blur and focussing the next element

$("#myId").select2(   ...   ).one("select2:focus", select2Focus).on("select2:blur", function ()
{
    var select2 = $(this).data('select2');
    if (select2.isOpen() == false)
    {
        $(this).one("select2:focus", select2Focus);
    }
}).on("select2:close", function ()
{
    setTimeout(function ()
    {
        // Find the next element and set focus on it.
        $(":focus").closest("tr").next("tr").find("select:visible,input:visible").focus();            
    }, 0);
});
function select2Focus()
{
    var select2 = $(this).data('select2');
    setTimeout(function() {
        if (!select2.isOpen()) {
            select2.open();
        }
    }, 0);  
}

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Try to delete the maven folder at ~/.m2/repository/org/apache/maven and build your project again to force the maven libraries be downloaded. This worked for me the last time I faced this java.lang.NoClassDefFoundError: org/apache/maven/shared/filtering/MavenFilteringException.

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

AsyncTask Android example

Shortest example for just doing something asynchronously:

class MyAsyncTask extends android.os.AsyncTask {
    @Override
    protected Object doInBackground(Object[] objects) {
        // Do something asynchronously
        return null;
    }
}

To run it:

(new MyAsyncTask()).execute();

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

I got the same error and the cause was the directory:

U:.....WEB\WebRoot\WEB-INF\classes\com\yourcompany\cc\dao

was corrupted(directory or file not readable or damaged).. solved with

  • renaming the directory WEB-INF\classes as WEB-INF\classes_old
  • Eclipse's Project menu--> Clean (to recreate directories)
  • redeploy --> restart server.

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

How do you clear the SQL Server transaction log?

First check the database recovery model. By default, SQL Server Express Edition creates a database for the simple recovery model (if I am not mistaken).

Backup log DatabaseName With Truncate_Only:

DBCC ShrinkFile(yourLogical_LogFileName, 50)

SP_helpfile will give you the logical log file name.

Refer to:

Recover from a full transaction log in a SQL Server database

If your database is in Full Recovery Model and if you are not taking TL backup, then change it to SIMPLE.

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

How to delete a whole folder and content?

According to the documentation:

If this abstract pathname does not denote a directory, then this method returns null.

So you should check if listFiles is null and only continue if it's not

boolean deleteDirectory(File path) {
    if(path.exists()) {
        File[] files = path.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteDirectory(file);
            } else {
                boolean wasSuccessful = file.delete();
                if (wasSuccessful) {
                    Log.i("Deleted ", "successfully");
                }
            }
        }
    }
    return(path.delete());
}

Draw an X in CSS

_x000D_
_x000D_
#x{_x000D_
    width: 20px;_x000D_
    height: 20px;_x000D_
    background-color:orange;_x000D_
    position:relative;_x000D_
    border-radius:2px;_x000D_
}_x000D_
#x::after,#x::before{_x000D_
    position:absolute;_x000D_
    top:9px;_x000D_
    left:0px;_x000D_
    content:'';_x000D_
    display:block;_x000D_
    width:20px;_x000D_
    height:2px;_x000D_
    background-color:red;_x000D_
    _x000D_
}_x000D_
#x::after{_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -moz-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    -o-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}_x000D_
#x::before{_x000D_
    -webkit-transform: rotate(-45deg);_x000D_
    -moz-transform: rotate(-45deg);_x000D_
    -ms-transform: rotate(-45deg);_x000D_
    -o-transform: rotate(-45deg);_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div id=x>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to build a Debian/Ubuntu package from source?

For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".

Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing

zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules

Then make the changes you wanted to compile options, and build the package by doing

dpkg-buildpackage -rfakeroot -us -uc

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

How do I alter the position of a column in a PostgreSQL database table?

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

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

jQuery hyperlinks - href value?

Those "anchors" that exist solely to provide a click event, but do not actually link to other content, should really be button elements because that's what they really are.

It can be styled like so:

<button style="border:none; background:transparent; cursor: pointer;">Click me</button>

And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() .

How to modify a CSS display property from JavaScript?

CSS properties should be set by cssText property or setAttribute method.

// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black"; 
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only.

Python Matplotlib figure title overlaps axes label when using twiny

Just use plt.tight_layout() before plt.show(). It works well.

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Left padding a String with Zeros

If you need performance and know the maximum size of the string use this:

String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;

Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.

Hide console window from Process.Start C#

This should work, try;


Add a System Reference.

using System.Diagnostics;

Then use this code to run your command in a hiden CMD Window.

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();