Programs & Examples On #Qbwc

The QuickBooks Web Connector provides an API for interfacing web-based applications with desktop Intuit QuickBooks software.

How to populate HTML dropdown list with values from database

<?php
 $query = "select username from users";
 $res = mysqli_query($connection, $query);   
?>


<form>
  <select>
     <?php
       while ($row = $res->fetch_assoc()) 
       {
         echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
       }
    ?>
  </select>
</form>

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

Simple solution for this problem to have quick chat with person who has owner role in gitlab. He can push one file READ.md or similar to just start with. Later, everything will be working as earlier.

How to use bootstrap-theme.css with bootstrap 3?

Upon downloading Bootstrap 3.x, you'll get bootstrap.css and bootstrap-theme.css (not to mention the minified versions of these files that are also present).

bootstrap.css

bootstrap.css is completely styled and ready to use, if such is your desire. It is perhaps a bit plain but it is ready and it is there.

You do not need to use bootstrap-theme.css if you don't want to and things will be just fine.

bootstrap-theme.css

bootstrap-theme.css is just what the name of the file is trying to suggest: it is a theme for bootstrap that is creatively considered 'THE bootstrap theme'. The name of the file confuses things just a bit since the base bootstrap.css already has styling applied and I, for one, would consider those styles to be the default. But that conclusion is apparently incorrect in light of things said in the Bootstrap documentation's examples section in regard to this bootstrap-theme.css file:

"Load the optional Bootstrap theme for a visually enhanced experience."

The above quote is found here http://getbootstrap.com/getting-started/#examples on a thumbnail that links to this example page http://getbootstrap.com/examples/theme/. The idea is that bootstrap-theme.css is THE bootstrap theme AND it's optional.

Themes at BootSwatch.com

About the themes at BootSwatch.com: These themes are not implemented like bootstrap-theme.css. The BootSwatch themes are modified versions of the original bootstrap.css. So, you should definitely NOT use a theme from BootSwatch AND the bootstrap-theme.css file at the same time.

Custom Theme

About Your Own Custom Theme: You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?

In L2S you can add

public partial class NWDataContext
{
    partial void InsertCategory(Category instance)
    {
        if(Instance.Date == null)
            Instance.Data = DateTime.Now;

        ExecuteDynamicInsert(instance);
    }
}

EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.

Getting the "real" Facebook profile picture URL from graph API

$url = 'http://graph.facebook.com/100000771470028/picture?type=large';
$rray=get_headers($url);
$hd = $rray[4];
echo(substr($hd,strpos($hd,'http')));

This will return the url that you asked, and the problem of changing the url by facebook doesn't matter because you are dynamically calling the url from the original url.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

condition binding must have optinal type which mean that you can only bind optional values in if let statement

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        // Delete the row from the data source

        if let tv = tableView as UITableView? {


        }
    }
}

This will work fine but make sure when you use if let it must have optinal type "?"

Write a number with two decimal places SQL Server

If you're fine with rounding the number instead of truncating it, then it's just:

ROUND(column_name,decimals)

"Are you missing an assembly reference?" compile error - Visual Studio

In my case it was a project defined using Target Framework: ".NET Framework 4.0 Client Profile " that tried to reference dll projects defined using Target Framework: ".NET Framework 4.0".

Once I changed the project settings to use Target Framework: ".NET Framework 4.0" everything was built nicely.

Right Click the project->Properties->Application->Target Framework

Change DataGrid cell colour based on values

This may be of help to you. It isn't the stock WPF datagrid however.

I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.

Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.

Example

Viewmodel.cs

namespace ViewModel
{
    [POCOViewModel]
    public class Table2DViewModel
    {
        public ITable2DView Table2DView { get; set; }

        public DataTable ItemsTable { get; set; }


        public Table2DViewModel()
        {
        }

        public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
        {
            Table2DView = table2DView;   
            CreateTable();
        }

        private void CreateTable()
        {
            var dt = new DataTable();
            var xAxisStrings = new string[]{"X1","X2","X3"};
            var yAxisStrings = new string[]{"Y1","Y2","Y3"};

            //TODO determine your min, max number for your colours
            var minValue = 0;
            var maxValue = 100;
            Table2DView.SetColorFormatter(minValue,maxValue, null);

            //Add the columns
            dt.Columns.Add(" ", typeof(string));
            foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

            //Add all the values
            double z = 0;
            for (var y = 0; y < yAxisStrings.Length; y++)
            {
                var dr = dt.NewRow();
                dr[" "] = yAxisStrings[y];
                for (var x = 0; x < xAxisStrings.Length; x++)
                {
                    //TODO put your actual values here!
                    dr[xAxisStrings[x]] = z++; //Add a random values
                }
                dt.Rows.Add(dr);
            }
            ItemsTable = dt;
        }


        public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
        {
            var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
            return factory(mainViewModel, table2DView);
        }
    }

}

IView.cs

namespace Interfaces
    {
        public interface ITable2DView
        {
            void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
        }
    }

View.xaml.cs

namespace View
{
    public partial class Table2DView : ITable2DView
    {
        public Table2DView()
        {
            InitializeComponent();
        }

        static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
        {
            ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
            ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
            ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
        };

        public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
        {
            if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
            ConditionBehavior.MinValue = minValue;
            ConditionBehavior.MaxValue = maxValue;
            ConditionBehavior.ColorScaleFormat = colorScaleFormat;
        }
    }
}

DynamicConditionBehavior.cs

namespace Behaviors
{
    public class DynamicConditionBehavior : Behavior<GridControl>
    {
        GridControl Grid => AssociatedObject;

        protected override void OnAttached()
        {
            base.OnAttached();
            Grid.ItemsSourceChanged += OnItemsSourceChanged;
        }

        protected override void OnDetaching()
        {
            Grid.ItemsSourceChanged -= OnItemsSourceChanged;
            base.OnDetaching();
        }

        public ColorScaleFormat ColorScaleFormat { get; set;}
        public float MinValue { get; set; }
        public float MaxValue { get; set; }

        private void OnItemsSourceChanged(object sender, EventArgs e)
        {
            var view = Grid.View as TableView;

            if (view == null) return;

            view.FormatConditions.Clear();

            foreach (var col in Grid.Columns)
            {
                view.FormatConditions.Add(new ColorScaleFormatCondition
                {
                    MinValue = MinValue,
                    MaxValue = MaxValue,
                    FieldName = col.FieldName,
                    Format = ColorScaleFormat,
                });
            }

        }
    }
}

View.xaml

<UserControl x:Class="View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" 
             xmlns:ViewModels="clr-namespace:ViewModel"
             xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
             xmlns:behaviors="clr-namespace:Behaviors"
             xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
             DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

    <UserControl.Resources>
        <Style TargetType="{x:Type dxg:GridColumn}">
            <Setter Property="Width" Value="50"/>
            <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
        </Style>

        <Style TargetType="{x:Type dxg:HeaderItemsControl}">
            <Setter Property="FontWeight" Value="DemiBold"/>
        </Style>
    </UserControl.Resources>

        <!--<dxmvvm:Interaction.Behaviors>
            <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
        </dxmvvm:Interaction.Behaviors>-->
        <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                     AutoGenerateColumns="AddNew"
                     EnableSmartColumnsGeneration="True">

        <dxmvvm:Interaction.Behaviors >
            <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
            </dxmvvm:Interaction.Behaviors>
            <dxg:GridControl.View>
                <dxg:TableView ShowGroupPanel="False"
                           AllowPerPixelScrolling="True"/>
            </dxg:GridControl.View>
        </dxg:GridControl>
  </UserControl>

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

Mergesort with Python

def merge(x):
    if len(x) == 1:
        return x
    else:
        mid = int(len(x) / 2)
        l = merge(x[:mid])
        r = merge(x[mid:])
    i = j = 0
    result = []
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            j += 1
    result += l[i:]
    result += r[j:]
    return result

Non-recursive depth first search algorithm

Here is a link to a java program showing DFS following both reccursive and non-reccursive methods and also calculating discovery and finish time, but no edge laleling.

    public void DFSIterative() {
    Reset();
    Stack<Vertex> s = new Stack<>();
    for (Vertex v : vertices.values()) {
        if (!v.visited) {
            v.d = ++time;
            v.visited = true;
            s.push(v);
            while (!s.isEmpty()) {
                Vertex u = s.peek();
                s.pop();
                boolean bFinished = true;
                for (Vertex w : u.adj) {
                    if (!w.visited) {
                        w.visited = true;
                        w.d = ++time;
                        w.p = u;
                        s.push(w);
                        bFinished = false;
                        break;
                    }
                }
                if (bFinished) {
                    u.f = ++time;
                    if (u.p != null)
                        s.push(u.p);
                }
            }
        }
    }
}

Full source here.

How do you remove a specific revision in the git history?

If all you want to do is remove the changes made in revision 3, you might want to use git revert.

Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.

What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.

This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

use this command /usr/libexec/java_home to check the JAVA_HOME

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

What does it mean by select 1 from table?

If you don't know there exist any data in your table or not, you can use following query:

SELECT cons_value FROM table_name;

For an Example:

SELECT 1 FROM employee;
  1. It will return a column which contains the total number of rows & all rows have the same constant value 1 (for this time it returns 1 for all rows);
  2. If there is no row in your table it will return nothing.

So, we use this SQL query to know if there is any data in the table & the number of rows indicates how many rows exist in this table.

Specify system property to Maven project

I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.

            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>${maven.exec.plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>${exec.main-class}</mainClass>
                <systemProperties>
                    <systemProperty>
                        <key>myproperty</key>
                        <value>myvalue</value>
                    </systemProperty>
                </systemProperties>
            </configuration>
        </plugin>

SQL variable to hold list of integers

You can't do it like this, but you can execute the entire query storing it in a variable.

For example:

DECLARE @listOfIDs NVARCHAR(MAX) = 
    '1,2,3'

DECLARE @query NVARCHAR(MAX) = 
    'Select *
     From TabA
     Where TabA.ID in (' + @listOfIDs + ')'

Exec (@query)

Communicating between a fragment and an activity - best practices

There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle

implementation 'androidx.fragment:fragment:1.3.0-rc01'

Inline SVG in CSS

Inline SVG coming from 3rd party sources (like Google charts) may not contain XML namespace attribute (xmlns="http://www.w3.org/2000/svg") in SVG element (or maybe it's removed once SVG is rendered - neither browser inspector nor jQuery commands from browser console show the namespace in SVG element).

When you need to re-purpose these svg snippets for your other needs (background-image in CSS or img element in HTML) watch out for the missing namespace. Without the namespace browsers may refuse to display SVG (regardless of the encoding utf8 or base64).

cannot load such file -- bundler/setup (LoadError)

i had the same issue and tried all the answers without any luck.

steps i did to reproduce:

  1. rvm instal 2.1.10
  2. rvm gemset create my_gemset
  3. rvm use 2.1.10@my_gemset
  4. bundle install

however bundle install installed Rails, but i still got cannot load such file -- bundler/setup (LoadError)

finally running gem install rails -v 4.2 fixed it

How to create a GUID / UUID

This one is based on date, and add a random suffix to "ensure" uniqueness. Works well for css identifiers. It always returns something like and is easy to hack:

uid-139410573297741

var getUniqueId = function (prefix) {
            var d = new Date().getTime();
            d += (parseInt(Math.random() * 100)).toString();
            if (undefined === prefix) {
                prefix = 'uid-';
            }
            d = prefix + d;
            return d;
        };

How can I check if a string contains a character in C#?

You can use the extension method .Contains() from the namespace System.Linq:

using System.Linq;

    ...

    if (abc.ToLower().Contains('s')) { }

And no, to check if a boolean expression is true, you don't need == true

Since the Contains method is an extension method, my solution appeared to be confusing to some. Here are two versions that don't require you to add using System.Linq;:

if (abc.ToLower().IndexOf('s') != -1) { }

// or:

if (abc.IndexOf("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }

Update

If you want to, you can write your own extensions method for easier reuse:

public static class MyStringExtensions
{
    public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
    }

    public static bool ContainsAnyCase(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
    }
}

Then you can call them like this:

if (def.ContainsAnyCaseInvariant('s')) { }
// or
if (def.ContainsAnyCase('s')) { }

In most cases when dealing with user data, you actually want to use CurrentCultureIgnoreCase (or the ContainsAnyCase extension method), because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.

For example: In Turkish, the uppercase letter I in lowercase is i (without a dot), and not i (with a dot).

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

This is a slight modification to Edens answer - which for me in chrome didn't catch the error. Although you'll still get an error in the console: "Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'sameorigin'." At least this will catch the error message and then you can deal with it.

 <iframe id="myframe" src="https://google.ca"></iframe>

 <script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

Generate a dummy-variable

Using dummies::dummy():

library(dummies)

# example data
df1 <- data.frame(id = 1:4, year = 1991:1994)

df1 <- cbind(df1, dummy(df1$year, sep = "_"))

df1
#   id year df1_1991 df1_1992 df1_1993 df1_1994
# 1  1 1991        1        0        0        0
# 2  2 1992        0        1        0        0
# 3  3 1993        0        0        1        0
# 4  4 1994        0        0        0        1

Mark error in form using Bootstrap

Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

Does --disable-web-security Work In Chrome Anymore?

Just create this batch file and run it on windows. It basically would kill all chrome instances and then would start chrome with disabling security. Save the following script in batch file say ***.bat and double click on it.

TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security –-allow-file-access-from-files

Excel VBA App stops spontaneously with message "Code execution has been halted"

I would like to add more details to Stan's answer #2 for below reasons:

  • I faced this issue myself more than dozen times and depending on project conditions, I chose between stan's voodoo magic answer #1 or #2. When I kept on facing it again, I become more inquistive that why it happens in first place.

  • I'd like to add answer for Mac users too.

  • There are limitations with both these possible answers:

    • if the code is protected (and you don't know password) then answer #1 won't help.
    • if the code is unprotected then answer #2 won't let you debug the code.

  1. It may happen due to any of the below reasons:

    • Operating system not allocating system resources to the Excel process. (Solution: One needs to just start the operating system - success rate is very low but has known to work many times)

    • P-code is the intermediate code that was used in Visual Basic (before .NET) and hence it is still used in the VBA. It enabled a more compact executable at the expense of slower execution. Why I am talking about p-code? Because it gets corrupted sometimes between multiple executions and large files or just due to installation of the software (Excel) went corrupt somewhere. When p-code corrupts. the code execution keeps getting interrupted. Solution: In these cases, it is assumed that your code has started to corrupt and chances in future are that your Excel workbook also get corrupt giving you messages like "excel file corrupted and cannot be opened". Hence, as a quick solution, you can rely on answer #1 or answer #2 as per your requirements. However, never ignore the signs of corruption. It's better to copy your code modules in notepad, delete the modules, save & close the workbook, close the excel. Now, re-open the workbook and start creating new modules with the code copied earlier to notepad.

  2. Mac users, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version

    • Ctrl + Pause
    • Ctrl + ScrLk
    • Esc + Esc (Press twice consecutively)

You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. This is replacement of Step 2.

  1. Solution: To overcome the limitation of using answer #1 and answer #2, I use xlErrorHandler along with Resume statement in the Error Handler if the error code is 18. Then, the interrupt is sent to the running procedure as an error, trappable by an error handler set up with an On Error GoTo statement. The trappable error code is 18. The current procedure is interrupted, and the user can debug or end the procedure. Microsoft gives caution that do not use this if your error handler has resume statement else your error handler always returns to the same statement. That's exactly we want in unwanted meaningless interruptions of code execution.

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

How to format a QString?

You can use the sprintf method, however the arg method is preferred as it supports unicode.

QString str;
str.sprintf("%s %d", "string", 213);

%Like% Query in spring JpaRepository

answer exactly will be

-->` @Query("select u from Category u where u.categoryName like %:input%")
     List findAllByInput(@Param("input") String input);

How to change value of object which is inside an array using JavaScript or jQuery?

We can also use Array's map function to modify object of an array using Javascript.

function changeDesc(value, desc){
   projects.map((project) => project.value == value ? project.desc = desc : null)
}

changeDesc('jquery', 'new description')

How do you make websites with Java?

You are asking a few different questions...

  • How can I create websites with Java?

The simplest way to start making websites with Java is to use JSP. JSP stands for Java Server Pages, and it allows you to embed HTML in Java code files for dynamic page creation. In order to compile and serve JSPs, you will need a Servlet Container, which is basically a web server that runs Java classes. The most popular basic Servlet Container is called Tomcat, and it's provided free by The Apache Software Foundation. Follow the tutorial that cletus provided here.

Once you have Tomcat up and running, and have a basic understanding of how to deploy JSPs, you'll probably want to start creating your own JSPs. I always like IBM developerWorks tutorials. They have a JSP tutorial here that looks alright (though a bit dated).

You'll find out that there is a lot more to Java web development than JSPs, but these tutorials will get you headed in the right direction.

  • PHP vs. Java

This is a pretty subjective question. PHP and Java are just tools, and in the hands of a bad programmer, any tool is useless. PHP and Java both have their strengths and weaknesses, and the discussion of them is probably outside of the scope of this post. I'd say that if you already know Java, stick with Java.

  • File I/O vs. MySQL

MySQL is better suited for web applications, as it is designed to handle many concurrent users. You should know though that Java can use MySQL just as easily as PHP can, through JDBC, Java's database connectivity framework.

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

Convert Int to String in Swift

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45

Set a cookie to never expire

Can't you just say a never ending loop, cookie expires as current date + 1 so it never hits the date it's supposed to expire on because it's always tomorrow? A bit overkill but just saying.

Join a list of items with different types as string in Python

For example:

lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]

lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']

As to me, I want to add a str before each str list:

# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']

Or single list:

lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

How to skip the OPTIONS preflight request?

As what Ray said, you can stop it by modifying content-header like -

 $http.defaults.headers.post["Content-Type"] = "text/plain";

For Example -

angular.module('myApp').factory('User', ['$resource','$http',
    function($resource,$http){
        $http.defaults.headers.post["Content-Type"] = "text/plain";
        return $resource(API_ENGINE_URL+'user/:userId', {}, {
            query: {method:'GET', params:{userId:'users'}, isArray:true},
            getLoggedIn:{method:'GET'}
        });
    }]);

Or directly to a call -

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': 'text/plain'
 },
 data: { test: 'test' }
}

$http(req).then(function(){...}, function(){...});

This will not send any pre-flight option request.

NOTE: Request should not have any custom header parameter, If request header contains any custom header then browser will make pre-flight request, you cant avoid it.

Objective-C and Swift URL encoding

Swift iOS:

Just For Information : I have used this:

extension String {

    func urlEncode() -> CFString {
        return CFURLCreateStringByAddingPercentEscapes(
            nil,
            self,
            nil,
            "!*'();:@&=+$,/?%#[]",
            CFStringBuiltInEncodings.UTF8.rawValue
        )
    }

}// end extension String

java.math.BigInteger cannot be cast to java.lang.Long

Imagine d.getId is a Long, then wrap like this:

BigInteger l  = BigInteger.valueOf(d.getId());

How do I use cx_freeze?

  • Add import sys as the new topline
  • You misspelled "executables" on the last line.
  • Remove script = on last line.

The code should now look like:

import sys
from cx_Freeze import setup, Executable

setup(
    name = "On Dijkstra's Algorithm",
    version = "3.1",
    description = "A Dijkstra's Algorithm help tool.",
    executables = [Executable("Main.py", base = "Win32GUI")])

Use the command prompt (cmd) to run python setup.py build. (Run this command from the folder containing setup.py.) Notice the build parameter we added at the end of the script call.

Not able to access adb in OS X through Terminal, "command not found"

For me, I ran into this issue after switching over from bash to zsh so I could get my console to look all awesome fantastic-ish with Hyper and the snazzy theme. I was trying to run my react-native application using react-native run-android and running into the op's issue. Adding the following into my ~.zshrc file solved the issue for me:

export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools

How to get Tensorflow tensor dimensions (shape) as int values?

for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:

rows, columns = map(lambda i: i.value, tensor.get_shape())

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Reverse a string in Java

package logicprogram;
import java.io.*;

public class Strinrevers {
public static void main(String args[])throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("enter data");
    String data=br.readLine();
    System.out.println(data);
    String str="";
    char cha[]=data.toCharArray();

    int l=data.length();
    int k=l-1;
    System.out.println(l);


    for(int i=0;k>=i;k--)
    {

        str+=cha[k];


    }
    //String text=String.valueOf(ch);
    System.out.println(str);

}

}

SSIS Excel Connection Manager failed to Connect to the Source

It seems like the 32-bit version of Excel was not installed. Remember that SSDT is a 32-bit IDE. Therefore, when data is access from SSDT the 32-bit data providers are used. When running the package outside of SSDT it runs in 64-bit mode (not always, but mostly) and uses the 64-bit data providers.

Always keep in mind that if you want to run your package in 64-bit (which you should aim for) you will need both the 32-bit data providers (for development in SSDT) as well as the 64-bit data providers (for executing the package in production).

I downloaded the 32-bit access drivers from:

After installation, I could see the worksheets


Source:

Is it possible to get only the first character of a String?

The string has a substring method that returns the string at the specified position.

String name="123456789";
System.out.println(name.substring(0,1));

How do I make a transparent canvas in html5?

I believe you are trying to do exactly what I just tried to do: I want two stacked canvases... the bottom one has a static image and the top one contains animated sprites. Because of the animation, you need to clear the background of the top layer to transparent at the start of rendering every new frame. I finally found the answer: it's not using globalAlpha, and it's not using a rgba() color. The simple, effective answer is:

context.clearRect(0,0,width,height);

Duplicate Symbols for Architecture arm64

On upgrading to Xcode 8, I got a message to upgrade to recommended settings. I accepted and everything was updated. I started getting compile time issue :

Duplicate symbol for XXXX Duplicate symbol for XXXX Duplicate symbol for XXXX

A total of 143 errors. Went to Target->Build settings -> No Common Blocks -> Set it to NO. This resolved the issue. The issue was that the integrated projects had code blocks in common and hence was not able to compile it. Explanation can be found here.

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

How to change the color of a button?

You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.

XML:

<Button
    android:background="@android:color/white"
    android:textColor="@android:color/black"
/>

You can also use hex values ex.

android:background="@android:color/white"

Coding:

//btn represents your button object

btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);

int to hex string

Previous answer is not good for negative numbers. Use a short type instead of int

        short iValue = -1400;
        string sResult = iValue.ToString("X2");
        Console.WriteLine("Value={0} Result={1}", iValue, sResult);

Now result is FA88

Using port number in Windows host file

What you want can be achieved by modifying the hosts file through Fiddler 2 application.

Follow these steps:

  1. Install Fiddler2

  2. Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)

  3. Add a line like this:-

    localhost:8080 www.mydomainname.com

  4. Save the file & then checkout www.mydomainname.com in browser.

Python: Figure out local timezone

Here's a way to get the local timezone using only the standard library, (only works in a *nix environment):

>>> '/'.join(os.path.realpath('/etc/localtime').split('/')[-2:])
'Australia/Sydney'

You can use this to create a pytz timezone:

>>> import pytz
>>> my_tz_name = '/'.join(os.path.realpath('/etc/localtime').split('/')[-2:])
>>> my_tz = pytz.timezone(my_tz_name)
>>> my_tz
<DstTzInfo 'Australia/Sydney' LMT+10:05:00 STD>

...which you can then apply to a datetime:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2014, 9, 3, 9, 23, 24, 139059)

>>> now.replace(tzinfo=my_tz)
>>> now
datetime.datetime(2014, 9, 3, 9, 23, 24, 139059, tzinfo=<DstTzInfo 'Australia/Sydney' LMT+10:05:00 STD>)

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

You Can Use [AllowHtml] To Your Project For Example

 [AllowHtml]
 public string Description { get; set; }

For Use This Code To Class Library You Instal This Package

Install-Package Microsoft.AspNet.Mvc

After Use This using

using System.Web.Mvc;

How to get rid of underline for Link component of React Router?

style={{ backgroundImage: "none" }}

Only this worked for me

How to Convert Int to Unsigned Byte and Back

Except char, every other numerical data type in Java are signed.

As said in a previous answer, you can get the unsigned value by performing an and operation with 0xFF. In this answer, I'm going to explain how it happens.

int i = 234;
byte b = (byte) i;
System.out.println(b);  // -22

int i2 = b & 0xFF;      
// This is like casting b to int and perform and operation with 0xFF

System.out.println(i2); // 234

If your machine is 32-bit, then the int data type needs 32-bits to store values. byte needs only 8-bits.

The int variable i is represented in the memory as follows (as a 32-bit integer).

0{24}11101010

Then the byte variable b is represented as:

11101010

As bytes are unsigned, this value represent -22. (Search for 2's complement to learn more on how to represent negative integers in memory)

Then if you cast is to int it will still be -22 because casting preserves the sign of a number.

1{24}11101010

The the casted 32-bit value of b perform and operation with 0xFF.

 1{24}11101010 & 0{24}11111111
=0{24}11101010

Then you get 234 as the answer.

selected value get from db into dropdown select box option using php mysql error

for example ..and please use mysqli() next time because mysql() is deprecated.

<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'"; 
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>

<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type='client'";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>

git status shows modifications, git checkout -- <file> doesn't remove them

Nothing else on this page worked. This finally worked for me. Showing no untracked, or commited files.

git add -A
git reset --hard

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

Does bootstrap have builtin padding and margin classes?

Bootstrap 4 has a new notation for margin and padding classes. Refer to Bootstrap 4.0 Documentation - Spacing.

From the documentation:

Notation

Spacing utilities that apply to all breakpoints, from xs to xl, have no breakpoint abbreviation in them. This is because those classes are applied from min-width: 0 and up, and thus are not bound by a media query. The remaining breakpoints, however, do include a breakpoint abbreviation.

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Examples

.mt-0 { margin-top: 0 !important; }

.p-3 { padding: $spacer !important; }

403 Forbidden You don't have permission to access /folder-name/ on this server

Solved issue using below steps :

1) edit file "/etc/apache2/sites-enabled/000-default.conf"

    DocumentRoot "dir_name"

    ServerName <server_IP>

    <Directory "dir_name">
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
    </Directory>

    <Directory "dir_name">
       AllowOverride None
       # Allow open access:
       Require all granted

2) change folder permission sudo chmod -R 777 "dir_name"

Is there an embeddable Webkit component for Windows / C# development?

There's a WebKit-Sharp component on Mono's Subversion Server. I can't find any web-viewable documentation on it, and I'm not even sure if it's WinForms or GTK# (can't grab the source from here to check at the moment), but it's probably your best bet, either way.

I think this component is CLI wrapper around webkit for Ubuntu. So this wrapper most likely could be not working on win32

Try check another variant - project awesomium - wrapper around google project "Chromium" that use webkit. Also awesomium has features like to should interavtive web pages on 3D objects under WPF

How to export library to Jar in Android Studio?

I was able to build a library source code to compiled .jar file, using approach from this solution: https://stackoverflow.com/a/19037807/1002054

Here is the breakdown of what I did:

1. Checkout library repository

In may case it was a Volley library

2. Import library in Android Studio.

I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.

3. Modify your build.gradle file

// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.3'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 17
    buildToolsVersion = 17

    sourceSets {
        main  {
            // Here is the path to your source code
            java {
                srcDir 'src'
            }
        }
    }
}

// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
    delete 'build/libs/myCompiledLibrary.jar'
}

task makeJar(type: Copy) {
    from('build/bundles/release/')
    into('build/libs/')
    include('classes.jar')
    rename ('classes.jar', 'myCompiledLibrary.jar')
}

makeJar.dependsOn(clearJar, build)

4. Run gradlew makeJar command from your project root.

I my case I had to copy gradlew.bat and gradle files from new android project into my library project root. You should find your compiled library file myCompiledLibrary.jar in build\libs directory.

I hope someone finds this useful.

Edit:

Caveat

Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar file (eg. modules have own library directory, that is referenced in build.gradle of given module).

In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library

Django Reverse with arguments '()' and keyword arguments '{}' not found

This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:

from django.test import Client
from django.core.urlresolvers import reverse

#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4)) 

Postgresql - unable to drop database because of some auto connections to DB

REVOKE CONNECT will not prevent the connections from the db owner or superuser. So if you don't want anyone to connect the db, follow command may be useful.

alter database pilot allow_connections = off;

Then use:

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'pilot';

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

jQuery Mobile: Stick footer to bottom of page

This script seemed to work for me...

$(function(){
    checkWindowHeight();
    $(document).bind('orientationchange',function(event){
        checkWindowHeight();
    })
});

function checkWindowHeight(){
        $('[data-role=content]').each(function(){
        var containerHeight = parseInt($(this).css('height'));
        var windowHeight = parseInt(window.innerHeight);
        if(containerHeight+118 < windowHeight){
            var newHeight = windowHeight-118;
            $(this).css('min-height', newHeight+'px');
        }
    });
}

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

Windows-1252 to UTF-8 encoding

How would you expect recode to know that a file is Windows-1252? In theory, I believe any file is a valid Windows-1252 file, as it maps every possible byte to a character.

Now there are certainly characteristics which would strongly suggest that it's UTF-8 - if it starts with the UTF-8 BOM, for example - but they wouldn't be definitive.

One option would be to detect whether it's actually a completely valid UTF-8 file first, I suppose... again, that would only be suggestive.

I'm not familiar with the recode tool itself, but you might want to see whether it's capable of recoding a file from and to the same encoding - if you do this with an invalid file (i.e. one which contains invalid UTF-8 byte sequences) it may well convert the invalid sequences into question marks or something similar. At that point you could detect that a file is valid UTF-8 by recoding it to UTF-8 and seeing whether the input and output are identical.

Alternatively, do this programmatically rather than using the recode utility - it would be quite straightforward in C#, for example.

Just to reiterate though: all of this is heuristic. If you really don't know the encoding of a file, nothing is going to tell you it with 100% accuracy.

PG::ConnectionBad - could not connect to server: Connection refused

check the file postgresql.conf (on ubuntu is in /etc/postgresql/X.X/main/postgresql.conf ) and look for the line that says:

listen_addresses="localhost"

try change it to:

listen_addresses="*"

it would be accepting every IP's, next check the line that says:

port=5432

and check if is the same port of your database.yml, by default on my postgresql-9.2 use 5433 instead 5432, don't forget to restart the postgres server,

Good Luck!

Double free or corruption after queue::push

You need to define a copy constructor, assignment, operator.

class Test {
   Test(const Test &that); //Copy constructor
   Test& operator= (const Test &rhs); //assignment operator
}

Your copy that is pushed on the queue is pointing to the same memory your original is. When the first is destructed, it deletes the memory. The second destructs and tries to delete the same memory.

How do you get a query string on Flask?

This can be done using request.args.get(). For example if your query string has a field date, it can be accessed using

date = request.args.get('date')

Don't forget to add "request" to list of imports from flask, i.e.

from flask import request

Printing result of mysql query from variable

From php docs:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

http://php.net/manual/en/function.mysql-query.php

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

SQL Server - SELECT FROM stored procedure

You can

  1. create a table variable to hold the result set from the stored proc and then
  2. insert the output of the stored proc into the table variable, and then
  3. use the table variable exactly as you would any other table...

... sql ....

Declare @T Table ([column definitions here])
Insert @T Exec storedProcname params 
Select * from @T Where ...

Passing parameters on button action:@selector

I have another solution in some cases.

store your parameter in a hidden UILabel. then add this UILabel as subview of UIButton.

when button is clicked, we can have a check on UIButton's all subviews. normally only 2 UILabel in it.

one is UIButton's title, the other is the one you just added. read that UILabel's text property, you will get the parameter.

This only apply for text parameter.

How can I make a ComboBox non-editable in .NET?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Link to the documentation for the ComboBox DropDownStyle property on MSDN.

Getting data from Yahoo Finance

As from the answer from BrianC use the YQL console. But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:

Stock Quotes:

  • yahoo.finance.quotes
  • yahoo.finance.historicaldata

Fundamental analysis:

  • yahoo.finance.keystats
  • yahoo.finance.balancesheet
  • yahoo.finance.incomestatement
  • yahoo.finance.analystestimates
  • yahoo.finance.dividendhistory

Technical analysis:

  • yahoo.finance.historicaldata
  • yahoo.finance.quotes
  • yahoo.finance.quant
  • yahoo.finance.option*

General financial information:

  • yahoo.finance.industry
  • yahoo.finance.sectors
  • yahoo.finance.isin
  • yahoo.finance.quoteslist
  • yahoo.finance.xchange

2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880

SQL Server Group By Month

If you need to do this frequently, I would probably add a computed column PaymentMonth to the table:

ALTER TABLE dbo.Payments ADD PaymentMonth AS MONTH(PaymentDate) PERSISTED

It's persisted and stored in the table - so there's really no performance overhead querying it. It's a 4 byte INT value - so the space overhead is minimal, too.

Once you have that, you could simplify your query to be something along the lines of:

SELECT ItemID, IsPaid,
(SELECT SUM(Amount) FROM Payments WHERE Year = 2010 And PaymentMonth = 1 AND UserID = 100) AS 'Jan',
(SELECT SUM(Amount) FROM Payments WHERE Year = 2010 And PaymentMonth = 2 AND UserID = 100) AS 'Feb',
.... and so on .....
FROM LIVE L 
INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY 
WHERE UserID = 16178 

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Python error "ImportError: No module named"

Yup. You need the directory to contain the __init__.py file, which is the file that initializes the package. Here, have a look at this.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Create a new Ruby on Rails application using MySQL instead of SQLite

database.yml

# MySQL. Versions 5.1.10 and up are supported.
#
# Install the MySQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html
#
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost
  database: database_name
  username: username
  password: secret

development:
  <<: *default

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default

# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
#   DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
#   production:
#     url: <%= ENV['DATABASE_URL'] %>
#
production:
  <<: *default

Gemfile:

# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4', '< 0.6.0'

Different ways of clearing lists

It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.

This may be useful for large lists, but for small list it should be negligible.

Edit: As Algorias, it doesn't matter.

Note that

del old_list[ 0:len(old_list) ]

is equivalent to

del old_list[:]

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

SELECT 
    p1.kArtikel, 
    p1.cName, 
    p1.cKurzBeschreibung, 
    p1.dLetzteAktualisierung, 
    p1.dErstellt, 
    p1.cSeo,
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad  
FROM 
    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
WHERE
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
ORDER BY 
  p1.kArtikel DESC
LIMIT
    100;

JavaScript Editor Plugin for Eclipse

JavaScript that allows for syntax checking

JSHint-Eclipse

and autosuggestions for .js files in Eclipse?

  1. Use JSDoc more as JSDT has nice support for the standard, so you will get more suggestions for your own code.
  2. There is new TernIDE that provide additional hints for .js and AngulatJS .html. Get them together as Anide from http://www.nodeclipse.org/updates/anide/

As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub

Redirect to external URI from ASP.NET MVC controller

Try this (I've used Home controller and Index View):

return RedirectToAction("Index", "Home");

jQuery get the id/value of <li> element after click function

you can get the value of the respective li by using this method after click

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>show the value of li</title>
    <link rel="stylesheet"  href="pathnameofcss">
</head>
<body>

    <div id="user"></div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul id="pageno">
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjs" type="text/javascript"></script>
</body>
</html>

JS:-

$("li").click(function ()
{       
var a = $(this).attr("value");

$("#user").html(a);//here the clicked value is showing in the div name user
console.log(a);//here the clicked value is showing in the console
});

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

Why is AJAX returning HTTP status code 0?

In an attempt to win the prize for most dumbest reason for the problem described.

Forgetting to call

xmlhttp.send(); //yes, you need this pivotal line!

Yes, I was still getting status returns of zero from the 'open' call.

White space at top of page

Old question, but I just ran into this. Sometimes your files are UTF-8 with a BOM at the start, and your template engine doesn't like that. So when you include your template, you get another (invisible) BOM inserted into your page...

<body>{INVISIBLE BOM HERE}...</body>

This causes a gap at the start of your page, where the browser renders the BOM, but it looks invisible to you (and in the inspector, just shows up as whitespace/quotes.

Save your template files as UTF-8 without BOM, or change your template engine to correctly handle UTF8/BOM documents.

How to get C# Enum description from value?

Update

The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

In Enums.NET you'd use:

string description = ((MyEnum)value).AsString(EnumFormat.Description);

Original post

I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description

I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

How can I make a program wait for a variable change in javascript?

JavaScript is one of the worst program\scripting language ever!

"Wait" seems to be impossible in JavaScript! (Yes, like in the real life, sometimes waiting is the best option!)

I tried "while" loop and "Recursion" (a function calls itself repeatedly until ...), but JavaScript refuses to work anyway! (This is unbelievable, but anyway, see the codes below:)

while loop:

<!DOCTYPE html>

<script>

var Continue = "no";
setTimeout(function(){Continue = "yes";}, 5000);    //after 5 seconds, "Continue" is changed to "yes"

while(Continue === 'no'){};    //"while" loop will stop when "Continue" is changed to "yes" 5 seconds later

    //the problem here is that "while" loop prevents the "setTimeout()" to change "Continue" to "yes" 5 seconds later
    //worse, the "while" loop will freeze the entire browser for a brief time until you click the "stop" script execution button

</script>

Recursion:

<!DOCTYPE html>

1234

<script>

function Wait_If(v,c){
if (window[v] === c){Wait_If(v,c)};
};

Continue_Code = "no"
setTimeout(function(){Continue_Code = "yes";}, 5000);    //after 5 seconds, "Continue_Code" is changed to "yes"

Wait_If('Continue_Code', 'no');

    //the problem here, the javascript console trows the "too much recursion" error, because "Wait_If()" function calls itself repeatedly!

document.write('<br>5678');     //this line will not be executed because of the "too much recursion" error above!

</script>

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

Return row of Data Frame based on value in a column - R

Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]

> df[which.min(df$Amount),]
  Name Amount
2    B    120

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

CSS3 transition events

If you simply want to detect only a single transition end, without using any JS framework here's a little convenient utility function:

function once = function(object,event,callback){
    var handle={};

    var eventNames=event.split(" ");

    var cbWrapper=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
        callback.apply(this,arguments);
    };

    eventNames.forEach(function(e){
        object.addEventListener(e,cbWrapper,false);
    });

    handle.cancel=function(){
        eventNames.forEach(function(e){
            object.removeEventListener(e,cbWrapper, false );
        });
    };

    return handle;
};

Usage:

var handler = once(document.querySelector('#myElement'), 'transitionend', function(){
   //do something
});

then if you wish to cancel at some point you can still do it with

handler.cancel();

It's good for other event usages as well :)

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

What is LDAP used for?

  • LDAP main usage is to provider faster retrieval of data . It acts as a central repository for storing user details that can be accessed by various application at same time .

  • The data that is read various time but we rarely update the data then LDAP is better option as it is faster to read in it because of its structure but updating(add/updatee or delete) is bit tedious job in case of LDAP

  • Security provided by LDAP : LDAP can work with SSL & TLS and thus can be used for sensitive information .

  • LDAP also can work with number of database providing greater flexibility to choose database best suited for our environment

  • Can be a better option for synchronising information between master and its replicase
  • LDAP apart from supporting the data recovery capability .Also , allows us to export data into LDIF file that can be read by various software available in the market

Moment.js - how do I get the number of years since a date, not rounded up?

This method is easy and powerful.

Value is a date and "DD-MM-YYYY" is the mask of the date.

moment().diff(moment(value, "DD-MM-YYYY"), 'years');

A cycle was detected in the build path of project xxx - Build Path Problem

I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree

INNER JOIN vs INNER JOIN (SELECT . FROM)

Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough

It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.

But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Oh well, I looked up for scrollable table with fixed column to understand the need of this specific requirement and your question was one of it with no close answers..

I answered this question Large dynamically sized html table with a fixed scroll row and fixed scroll column which inspired to showcase my work as a plugin https://github.com/meetselva/fixed-table-rows-cols

The plugin basically converts a well formatted HTML table to a scrollable table with fixed table header and columns.

The usage is as below,

$('#myTable').fxdHdrCol({
    fixedCols    : 3,       /* 3 fixed columns */
    width        : "100%",  /* set the width of the container (fixed or percentage)*/
    height       : 500      /* set the height of the container */
});

You can check the demo and documentation here

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How to extract a value from a string using regex and a shell?

you can use the shell(bash for example)

$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45

Oracle SQL query for Date format

if you are using same date format and have select query where date in oracle :

   select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';

To_DATE provided by oracle

Building executable jar with maven?

If you don't want execute assembly goal on package, you can use next command:

mvn package assembly:single

Here package is keyword.

Pandas: Looking up the list of sheets in an excel file

You should explicitly specify the second parameter (sheetname) as None. like this:

 df = pandas.read_excel("/yourPath/FileName.xlsx", None);

"df" are all sheets as a dictionary of DataFrames, you can verify it by run this:

df.keys()

result like this:

[u'201610', u'201601', u'201701', u'201702', u'201703', u'201704', u'201705', u'201706', u'201612', u'fund', u'201603', u'201602', u'201605', u'201607', u'201606', u'201608', u'201512', u'201611', u'201604']

please refer pandas doc for more details: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Just type git init into your command line and press enter. Then run your command again, you probably were running git remote add origin [your-repository].

That should work, if it doesn't, just let me know.

Get Substring - everything before certain char

You can use regular expressions for this purpose, but it's good to avoid extra exceptions when input string mismatches against regular expression.

First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:

String reStrEnding = Regex.Escape("-");

I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "=", but it will make difference for example if character is @"\".

Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)

Regex re = new Regex("^(.*?)" + reStrEnding);

If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.

And finally match against string and extract matched pattern:

String matched = re.Match(str).Groups[1].ToString();

And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I've wrote now using both notations - inline lambda function (does not allow default parameter) or separate function call.

using System;
using System.Text.RegularExpressions;

static class Helper
{
    public static string GetUntilOrEmpty(this string text, string stopAt = "-")
    {
        return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Regex re = new Regex("^(.*?)-");
        Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };

        Console.WriteLine(untilSlash("223232-1.jpg"));
        Console.WriteLine(untilSlash("443-2.jpg"));
        Console.WriteLine(untilSlash("34443553-5.jpg"));
        Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
        Console.WriteLine(untilSlash(""));
        // Throws exception: Console.WriteLine(untilSlash(null));

        Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
    }
}

Btw - changing regex pattern to "^(.*?)(-|$)" will allow to pick up either until "-" pattern or if pattern was not found - pick up everything until end of string.

SQL Server 2012 can't start because of a login failure

I don't know how good of a solution this is it, but after following some of the other answer to this question without success, i resolved setting the connection user of the service MSSQLSERVER to "Local Service".

N.B: i'm using SQL Server 2017.

Where are environment variables stored in the Windows Registry?

CMD:

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment

PowerShell:

Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment

Powershell/.NET: (see EnvironmentVariableTarget Enum)

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

How to enable CORS in ASP.NET Core

you have three ways to enable CORS:

  • In middleware using a named policy or default policy.
  • Using endpoint routing.
  • With the [EnableCors] attribute.

Enable CORS with named policy:

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                 builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(CorsPolicy);

        // app.UseResponseCaching();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

UseCors must be called before UseResponseCaching when using UseResponseCaching.

Enable CORS with default policy:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                     builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Enable CORS with endpoint

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy ";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                  builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                     .RequireCors(CorsPolicy)
        });
    }
}

Enable CORS with attributes

you have tow option

  • [EnableCors] specifies the default policy.
  • [EnableCors("{Policy String}")] specifies a named policy.

Output PowerShell variables to a text file

The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.

$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

This creates an array of three items.

$computer,$Speed,$Regcheck
FYKJ
100
YES

vs. concatenation of three items separated by commas.

$computer + "," + $Speed + "," + $Regcheck
FYKJ,100,YES

RedirectToAction with parameter

It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

So the url would be:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

These can then be referenced by your controller:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }

Maven fails to find local artifact

When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/> element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository> it started working.

For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>, I suppose.

-bash: export: `=': not a valid identifier

First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux) go to the bottom, you would see something like this,

export LD_LIBRARY_PATH = /usr/local/lib

change this like that( remove blank point around the = ),

export LD_LIBRARY_PATH=/usr/local/lib

it should be useful.

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'firstname'=>'value',
    'lastname'=>'value',
    'email'=>'value',
    'address'=>'value',
    'tree' => array(
        'tree1'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree2'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree3'=>array(
            'fruit'=>'value',
            'height'=>'value'
        )
    )
)

difference between variables inside and outside of __init__()

This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

Kotlin Ternary Conditional Operator

When working with apply(), let seems very handy when dealing with ternary operations, as it is more elegant and give you room

val columns: List<String> = ...
val band = Band().apply {
    name = columns[0]
    album = columns[1]
    year = columns[2].takeIf { it.isNotEmpty() }?.let { it.toInt() } ?: 0
}

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

How to set a default row for a query that returns no rows?

This would be eliminate the select query from running twice and be better for performance:

Declare @rate int

select 
    @rate = rate 
from 
    d_payment_index
where 
    fy = 2007
    and payment_year = 2008
    and program_id = 18

IF @@rowcount = 0
    Set @rate = 0

Select @rate 'rate'

Android set bitmap to Imageview

Please try this:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

There's a handy function, oidvectortypes, that makes this a lot easier.

SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes)) 
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';

Credit to Leo Hsu and Regina Obe at Postgres Online for pointing out oidvectortypes. I wrote similar functions before, but used complex nested expressions that this function gets rid of the need for.

See related answer.


(edit in 2016)

Summarizing typical report options:

-- Compact:
SELECT format('%I.%I(%s)', ns.nspname, p.proname, oidvectortypes(p.proargtypes))

-- With result data type: 
SELECT format(
       '%I.%I(%s)=%s', 
       ns.nspname, p.proname, oidvectortypes(p.proargtypes),
       pg_get_function_result(p.oid)
)

-- With complete argument description: 
SELECT format('%I.%I(%s)', ns.nspname, p.proname, pg_get_function_arguments(p.oid))

-- ... and mixing it.

-- All with the same FROM clause:
FROM pg_proc p INNER JOIN pg_namespace ns ON (p.pronamespace = ns.oid)
WHERE ns.nspname = 'my_namespace';

NOTICE: use p.proname||'_'||p.oid AS specific_name to obtain unique names, or to JOIN with information_schema tables — see routines and parameters at @RuddZwolinski's answer.


The function's OID (see pg_catalog.pg_proc) and the function's specific_name (see information_schema.routines) are the main reference options to functions. Below, some useful functions in reporting and other contexts.

--- --- --- --- ---
--- Useful overloads: 

CREATE FUNCTION oidvectortypes(p_oid int) RETURNS text AS $$
    SELECT oidvectortypes(proargtypes) FROM pg_proc WHERE oid=$1;
$$ LANGUAGE SQL IMMUTABLE;

CREATE FUNCTION oidvectortypes(p_specific_name text) RETURNS text AS $$
    -- Extract OID from specific_name and use it in oidvectortypes(oid).
    SELECT oidvectortypes(proargtypes) 
    FROM pg_proc WHERE oid=regexp_replace($1, '^.+?([^_]+)$', '\1')::int;
$$ LANGUAGE SQL IMMUTABLE;

CREATE FUNCTION pg_get_function_arguments(p_specific_name text) RETURNS text AS $$
    -- Extract OID from specific_name and use it in pg_get_function_arguments.
    SELECT pg_get_function_arguments(regexp_replace($1, '^.+?([^_]+)$', '\1')::int)
$$ LANGUAGE SQL IMMUTABLE;

--- --- --- --- ---
--- User customization: 

CREATE FUNCTION pg_get_function_arguments2(p_specific_name text) RETURNS text AS $$
    -- Example of "special layout" version.
    SELECT trim(array_agg( op||'-'||dt )::text,'{}') 
    FROM (
        SELECT data_type::text as dt, ordinal_position as op
        FROM information_schema.parameters 
        WHERE specific_name = p_specific_name 
        ORDER BY ordinal_position
    ) t
$$ LANGUAGE SQL IMMUTABLE;

What is the difference between a token and a lexeme?

a) Tokens are symbolic names for the entities that make up the text of the program; e.g. if for the keyword if, and id for any identifier. These make up the output of the lexical analyser. 5

(b) A pattern is a rule that specifies when a sequence of characters from the input constitutes a token; e.g the sequence i, f for the token if , and any sequence of alphanumerics starting with a letter for the token id.

(c) A lexeme is a sequence of characters from the input that match a pattern (and hence constitute an instance of a token); for example if matches the pattern for if , and foo123bar matches the pattern for id.

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, the problem was caused by not being logged in with Postman, so I opened a connection in another tab with a session cookie I took from the headers in my Chrome session.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

If you are using Java, you could just replace the x00 characters before the insert like following:

myValue.replaceAll("\u0000", "")

The solution was provided and explained by Csaba in following post:

https://www.postgresql.org/message-id/1171970019.3101.328.camel%40coppola.muc.ecircle.de

Respectively:

in Java you can actually have a "0x0" character in your string, and that's valid unicode. So that's translated to the character 0x0 in UTF8, which in turn is not accepted because the server uses null terminated strings... so the only way is to make sure your strings don't contain the character '\u0000'.

Possible to iterate backwards through a foreach?

When working with a list (direct indexing), you cannot do it as efficiently as using a for loop.

Edit: Which generally means, when you are able to use a for loop, it's likely the correct method for this task. Plus, for as much as foreach is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach for looping.

Extract parameter value from url using regular expressions

Why dont you take the string and split it

Example on the url

var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"

you can do a split as

var params = url.split("?")[1].split("&");

You will get array of strings with params as name value pairs with "=" as the delimiter.

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

'negative' pattern matching in python

 if not (line.startswith("OK ") or line.strip() == "."):
     print line

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a small module to do just that, called timexe:

  • Its simple,small reliable code and has no dependencies
  • Resolution is in milliseconds and has high precision over time
  • Cron like, but not compatible (reversed order and other Improvements)
  • I works in the browser too

Install:

npm install timexe

use:

var timexe = require('timexe');
//Every 30 sec
var res1=timexe(”* * * * * /30”, function() console.log(“Its time again”)});

//Every minute
var res2=timexe(”* * * * *”,function() console.log(“a minute has passed”)});

//Every 7 days
var res3=timexe(”* y/7”,function() console.log(“its the 7th day”)});

//Every Wednesdays 
var res3=timexe(”* * w3”,function() console.log(“its Wednesdays”)});

// Stop "every 30 sec. timer"
timexe.remove(res1.id);

you can achieve start/stop functionality by removing/re-adding the entry directly in the timexe job array. But its not an express function.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This question and answer helped me solve a specific problem with signing up new users in Parse.

Because the signUp( attrs, options ) function uses local storage to persist the session, if a user is in private browsing mode it throws the "QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." exception and the success/error functions are never called.

In my case, because the error function is never called it initially appeared to be an issue with firing the click event on the submit or the redirect defined on success of sign up.

Including a warning for users resolved the issue.

Parse Javascript SDK Reference https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp

Signs up a new user with a username (or email) and password. This will create a new Parse.User on the server, and also persist the session in localStorage so that you can access the user using {@link #current}.

How can we generate getters and setters in Visual Studio?

Rather than using Ctrl + K, X you can also just type prop and then hit Tab twice.

Debugging Stored Procedure in SQL Server 2008

Well the answer was sitting right in front of me the whole time.

In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.

I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.

SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.

So easy! Thanks for your help FinnNK.

Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.

How to find keys of a hash?

This is the best you can do, as far as I know...

var keys = [];
for (var k in h)keys.push(k);

Best practice for using assert?

The English language word assert here is used in the sense of swear, affirm, avow. It doesn't mean "check" or "should be". It means that you as a coder are making a sworn statement here:

# I solemnly swear that here I will tell the truth, the whole truth, 
# and nothing but the truth, under pains and penalties of perjury, so help me FSM
assert answer == 42

If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I've run into this issue when trying to build a fixed positioned sidebar with both vertically scrollable content and nested absolute positioned children to be displayed outside sidebar boundaries.

My approach consisted of separately apply:

  • an overflow: visible property to the sidebar element
  • an overflow-y: auto property to sidebar inner wrapper

Please check the example below or an online codepen.

_x000D_
_x000D_
html {_x000D_
  min-height: 100%;_x000D_
}_x000D_
body {_x000D_
  min-height: 100%;_x000D_
  background: linear-gradient(to bottom, white, DarkGray 80%);_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.sidebar {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  height: 100%;_x000D_
  width: 200px;_x000D_
  overflow: visible;  /* Just apply overflow-x */_x000D_
  background-color: DarkOrange;_x000D_
}_x000D_
_x000D_
.sidebarWrapper {_x000D_
  padding: 10px;_x000D_
  overflow-y: auto;   /* Just apply overflow-y */_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.element {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 100%;_x000D_
  background-color: CornflowerBlue;_x000D_
  padding: 10px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
<div class="sidebar">_x000D_
  <div class="sidebarWrapper">_x000D_
    <div class="element">_x000D_
      I'm a sidebar child element but I'm able to horizontally overflow its boundaries._x000D_
    </div>_x000D_
    <p>This is a 200px width container with optional vertical scroll.</p>_x000D_
    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

Best way to remove an event handler in jQuery?

I know this comes in late, but why not use plain JS to remove the event?

var myElement = document.getElementById("your_ID");
myElement.onclick = null;

or, if you use a named function as an event handler:

function eh(event){...}
var myElement = document.getElementById("your_ID");
myElement.addEventListener("click",eh); // add event handler
myElement.removeEventListener("click",eh); //remove it

How to group an array of objects by key

Timo's answer is how I would do it. Simple _.groupBy, and allow some duplications in the objects in the grouped structure.

However the OP also asked for the duplicate make keys to be removed. If you wanted to go all the way:

var grouped = _.mapValues(_.groupBy(cars, 'make'),
                          clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);

Yields:

{ audi:
   [ { model: 'r8', year: '2012' },
     { model: 'rs5', year: '2013' } ],
  ford:
   [ { model: 'mustang', year: '2012' },
     { model: 'fusion', year: '2015' } ],
  kia: [ { model: 'optima', year: '2012' } ] }

If you wanted to do this using Underscore.js, note that its version of _.mapValues is called _.mapObject.

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

Why is String immutable in Java?

If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

You can have multiple pointer String variable to point HELLO String.

But if HELLO is char Array then you can change HELLO to HILLO. Eg,

char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this

Answer:

Programming languages have immutable data variables so that it can be used as keys in key, value pair. String variables are used as keys/indices, so they are immutable.

How to log out user from web site using BASIC authentication?

function logout() {
  var userAgent = navigator.userAgent.toLowerCase();

  if (userAgent.indexOf("msie") != -1) {
    document.execCommand("ClearAuthenticationCache", false);
  }

  xhr_objectCarte = null;

  if(window.XMLHttpRequest)
    xhr_object = new XMLHttpRequest();
  else if(window.ActiveXObject)
    xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
  else
    alert ("Your browser doesn't support XMLHTTPREQUEST");

  xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
  xhr_object.send ("");
  xhr_object = null;

  document.location = 'http://yourserver.com'; 
  return false;
}

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

How to generate Javadoc from command line

Link to JavaDoc

I believe this will surely help you.

javadoc -d C:/javadoc/test com.mypackage

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

How to check if spark dataframe is empty?

Since Spark 2.4.0 there is Dataset.isEmpty.

It's implementation is :

def isEmpty: Boolean = 
  withAction("isEmpty", limit(1).groupBy().count().queryExecution) { plan =>
    plan.executeCollect().head.getLong(0) == 0
}

Note that a DataFrame is no longer a class in Scala, it's just a type alias (probably changed with Spark 2.0):

type DataFrame = Dataset[Row]

TypeError: $(...).autocomplete is not a function

Try this code, Let $ be defined

(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
        jQuery(document).ready(function($) {
      $("#search_text").autocomplete({
          source:results,
          minLength:2,
          position: { offset:'-30 0' },  
          select: function(event, ui ) { 
                  goTo(ui.item.value);
                  return false;
          }        
        }); 
        });
   }
  };
})(jQuery, Drupal);

Delete all data rows from an Excel table (apart from the first)

This VBA Sub will delete all data rows (apart from the first, which it will just clear) -

Sub DeleteTableRows(ByRef Table as ListObject)

        '** Work out the current number of rows in the table
        On Error Resume Next                    ' If there are no rows, then counting them will cause an error
        Dim Rows As Integer
        Rows = Table.DataBodyRange.Rows.Count   ' Cound the number of rows in the table
        If Err.Number <> 0 Then                 ' Check to see if there has been an error
            Rows = 0                            ' Set rows to 0, as the table is empty
            Err.Clear                           ' Clear the error
        End If
        On Error GoTo 0                         ' Reset the error handling

        '** Empty the table *'
        With Table
            If Rows > 0 Then ' Clear the first row
                .DataBodyRange.Rows(1).ClearContents
            End If
            If Rows > 1 Then ' Delete all the other rows
                .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
            End If
        End With

End Sub

JavaFX 2.1 TableView refresh items

I have been trying to find a way to refresh the tableView(ScalaFx) for 3-4 hours. Finally I got a answer. I just want to publish my solution because of i wasted already hours.

-To retrieve the rows from database, i used to declare a method which returns ObservableBuffer.

My JDBC CLASS

    //To get all customer details
def getCustomerDetails : ObservableBuffer[Customer] = {

val customerDetails = new ObservableBuffer[Customer]()
  try {

    val resultSet = statement.executeQuery("SELECT * FROM MusteriBilgileri")

    while (resultSet.next()) {

      val musteriId = resultSet.getString("MusteriId")
      val musteriIsmi = resultSet.getString("MusteriIsmi")
      val urununTakildigiTarih = resultSet.getDate("UrununTakildigiTarih").toString
      val bakimTarihi = resultSet.getDate("BakimTarihi").toString
      val urununIsmi = resultSet.getString("UrununIsmi")
      val telNo = resultSet.getString("TelNo")
      val aciklama = resultSet.getString("Aciklama")

      customerDetails += new Customer(musteriId,musteriIsmi,urununTakildigiTarih,bakimTarihi,urununIsmi,telNo,aciklama)

    }
  } catch {
    case e => e.printStackTrace
  }

  customerDetails
}

-And I have created a TableView object.

var table = new TableView[Customer](model.getCustomerDetails)
table.columns += (customerIdColumn,customerNameColumn,productInstallColumn,serviceDateColumn,
        productNameColumn,phoneNoColumn,detailColumn)

-And Finally i got solution. In the refresh button, i have inserted this code;

table.setItems(FXCollections.observableArrayList(model.getCustomerDetails.delegate))

model is the reference of my jdbc connection class

val model = new ScalaJdbcConnectSelect

This is the scalafx codes but it gives some idea to javafx

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

Tri-state Check box in HTML?

I think that the most semantic way is using readonly attribute that checkbox inputs can have. No css, no images, etc; a built-in HTML property!

See Fiddle:
http://jsfiddle.net/chriscoyier/mGg85/2/

As described here in last trick: http://css-tricks.com/indeterminate-checkboxes/

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How to use multiple databases in Laravel

In Laravel 5.1, you specify the connection:

$users = DB::connection('foo')->select(...);

Default, Laravel uses the default connection. It is simple, isn't it?

Read more here: http://laravel.com/docs/5.1/database#accessing-connections

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123
Connected.

How to extract IP Address in Spring MVC Controller get call?

The solution is

@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {

        System.out.println(workflow);
        System.out.println(value);
        System.out.println(dc);
        System.out.println(request.getRemoteAddr());
        // some other code
    }

Add HttpServletRequest request to your method definition and then use the Servlet API

Spring Documentation here said in

15.3.2.3 Supported handler method arguments and return types

Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).

Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest

Reverse Contents in Array

I would try to using pointers to solve this problem:

#include <iostream>

void displayArray(int table[], int size);

void rev(int table[], int size);


int main(int argc, char** argv) {

    int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

    rev(a, 10);
    displayArray(a, 10);

    return 0;
}

void displayArray(int table[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << table[i] << " ";
    }
    std::cout << std::endl;
}

void rev(int table[], int size) {

    int *start = table;
    int *end = table + (size - 1);

    for (int i = 0; i < size; i++) {

        if (start < end) {
            int temp = *end;
            *end = *start;
            *start = temp;
        }

        start++;
        end--;
    }
}

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.

I was able to fix it by doing the following:

sudo apt-get install gcc-multilib g++-multilib

If you've installed a version of gcc / g++ that doesn't ship by default (such as g++-4.8 on lucid) you'll want to match the version as well:

sudo apt-get install gcc-4.8-multilib g++-4.8-multilib

How to upload files in asp.net core?

 <form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">

     <div class="form-group">
        <input type="file" class="form-control" name="image" />
     </div>

     <div class="form-group">
        <button type="submit" class="btn btn-primary col-xs-12">Add</button>
     </div>
  </form>

My Action Is

        [HttpPost]
        public IActionResult AddNews(IFormFile image)
        {
            Tbl_News tbl_News = new Tbl_News();
            if (image!=null)
            {

                //Set Key Name
                string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);

                //Get url To Save
                string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);

                using(var stream=new FileStream(SavePath, FileMode.Create))
                {
                    image.CopyTo(stream);
                }
            }
            return View();
        }

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

jQuery checkbox check/uncheck

 $('mainCheckBox').click(function(){
    if($(this).prop('checked')){
        $('Id or Class of checkbox').prop('checked', true);
    }else{
        $('Id or Class of checkbox').prop('checked', false);
    }
});

How do I create a datetime in Python from milliseconds?

import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')

"fatal: Not a git repository (or any of the parent directories)" from git status

I had another problem. I was in a git directory, but got there through a symlink. I had to go into the directory directly (i.e. not through the symlink) then it worked fine.

CodeIgniter -> Get current URL relative to base url

For the parameter or without parameter URLs Use this :

Method 1:

 $currentURL = current_url(); //for simple URL
 $params = $_SERVER['QUERY_STRING']; //for parameters
 $fullURL = $currentURL . '?' . $params; //full URL with parameter

Method 2:

$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Method 3:

base_url(uri_string());

How to toggle font awesome icon on click?

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

Is it possible only to declare a variable without assigning any value in Python?

I usually initialize the variable to something that denotes the type like

var = ""

or

var = 0

If it is going to be an object then don't initialize it until you instantiate it:

var = Var()

How do I extend a class with c# extension methods?

We have improved our answer with detail explanation.Now it's more easy to understand about extension method

Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.

We can extend our custom classes ,.net framework classes etc.

Extension method is actually a special kind of static method that is defined in the static class.

As DateTime class is already taken above and hence we have not taken this class for the explanation.

Below is the example

//This is a existing Calculator class which have only one method(Add)

public class Calculator 
{
    public double Add(double num1, double num2)
    {
        return num1 + num2;
    }

}

// Below is the extension class which have one extension method.  
public static class Extension
{
    // It is extension method and it's first parameter is a calculator class.It's behavior is going to extend. 
    public static double Division(this Calculator cal, double num1,double num2){
       return num1 / num2;
    }   
}

// We have tested the extension method below.        
class Program
{
    static void Main(string[] args)
    {
        Calculator cal = new Calculator();
        double add=cal.Add(10, 10);
        // It is a extension method in Calculator class.
        double add=cal.Division(100, 10)

    }
}

How to perform Join between multiple tables in LINQ lambda

it has been a while but my answer may help someone:

if you already defined the relation properly you can use this:

        var res = query.Products.Select(m => new
        {
            productID = product.Id,
            categoryID = m.ProductCategory.Select(s => s.Category.ID).ToList(),
        }).ToList();

Find all CSV files in a directory using Python

use Python OS module to find csv file in a directory.

the simple example is here :

import os

# This is the path where you want to search
path = r'd:'

# this is the extension you want to detect
extension = '.csv'

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file

How to check whether a string contains a substring in Ruby

user_input = gets.chomp
user_input.downcase!

if user_input.include?('substring')
  # Do something
end

This will help you check if the string contains substring or not

puts "Enter a string"
user_input = gets.chomp  # Ex: Tommy
user_input.downcase!    #  tommy


if user_input.include?('s')
    puts "Found"
else
    puts "Not found"
end

How to loop through elements of forms with JavaScript?

You need to get a reference of your form, and after that you can iterate the elements collection. So, assuming for instance:

<form method="POST" action="submit.php" id="my-form">
  ..etc..
</form>

You will have something like:

var elements = document.getElementById("my-form").elements;

for (var i = 0, element; element = elements[i++];) {
    if (element.type === "text" && element.value === "")
        console.log("it's an empty textfield")
}

Notice that in browser that would support querySelectorAll you can also do something like:

var elements = document.querySelectorAll("#my-form input[type=text][value='']")

And you will have in elements just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:

var elements = document.querySelectorAll("#my-form input[type=text]")

for (var i = 0, element; element = elements[i++];) {
    if (element.value === "")
        console.log("it's an empty textfield")
}

You will basically save one check.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html

Specifically:

Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.

I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.

HTML img scaling

I know that this question has been asked for a long time but as of today one simple answer is:

<img src="image.png" style="width: 55vw; min-width: 330px;" />

The use of vw in here tells that the width is relative to 55% of the width of the viewport.

All the major browsers nowadays support this.

Check this link.

How to access data/data folder in Android device?

adb backup didn't work for me, so here's what I did (Xiaomi Redmi Note 4X, Android 6.0):
1. Go to Settings > Additional Settings > Backup & reset > Local backups.
2. Tap 'Back up' on the bottom of the screen.
3. Uncheck 'System' and 'Apps' checkmarks.
4. Tap detail disclosure button on the right of the 'Apps' cell to navigate to app selection screen.
5. Select the desired app and tap OK.
6. After the backup was completed, the actual file need to be located somehow. Mine could be found at /MIUI/backup/AllBackup/_FOLDER_NAMED_AFTER_BACKUP_CREATION_DATE_.
7. Then I followed the steps from this answer by RonTLV to actually convert the backup file (.bak in my case) to tar (duplicating from the original answer):
"
a) Go here and download: https://sourceforge.net/projects/adbextractor/
b) Extract the downloaded file and navigate to folder where you extracted.
c) run this with your own file names: java -jar abe.jar unpack c:\Intel\xxx.ab c:\Intel\xxx.tar
"

Convert floats to ints in Pandas?

Use the pandas.DataFrame.astype(<type>) function to manipulate column dtypes.

>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

EDIT:

To handle missing values:

>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

How to create a regex for accepting only alphanumeric characters?

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

What does the question mark in Java generics' type parameter mean?

A question mark is a signifier for 'any type'. ? alone means

Any type extending Object (including Object)

while your example above means

Any type extending or implementing HasWord (including HasWord if HasWord is a non-abstract class)

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Use <Image> with a local file

It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

Quick Way to Implement Dictionary in C

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */
}

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;
}

char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;
}

Note that if the hashes of two strings collide, it may lead to an O(n) lookup time. You can reduce the likelihood of collisions by increasing the value of HASHSIZE. For a complete discussion of the data structure, please consult the book.

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.