Programs & Examples On #Computer forensics

Examining digital media in a forensically sound manner with the aim of identifying, preserving, recovering, analyzing and presenting facts and opinions about the information.

How to insert date values into table

let suppose we create a table Transactions using SQl server management studio

txn_id int,

txn_type_id varchar(200),

Account_id int,

Amount int,

tDate date

);

with date datatype we can insert values in simple format: 'yyyy-mm-dd'

INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');

Moreover we can have differet time formats like

DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS 

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
    window.onhashchange=hashTriggerTab;
    window.onload=hashTriggerTab;
    
    function hashTriggerTab(){
        var current_hash=window.location.hash;
        if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
        if(current_hash!=''){
            var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
            if(trigger)trigger.click();
        }
    }
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

How can I check that JButton is pressed? If the isEnable() is not work?

JButton has a model which answers these question:

  • isArmed(),
  • isPressed(),
  • isRollOVer()

etc. Hence you can ask the model for the answer you are seeking:

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");

Write Array to Excel Range

In my case, the program queries the database which returns a DataGridView. I then copy that to an array. I get the size of the just created array and then write the array to an Excel spreadsheet. This code outputs over 5000 lines of data in about two seconds.

//private System.Windows.Forms.DataGridView dgvResults;
dgvResults.DataSource = DB.getReport();

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    var dgArray = new object[dgvResults.RowCount, dgvResults.ColumnCount+1];
    foreach (DataGridViewRow i in dgvResults.Rows)
    {
        if (i.IsNewRow) continue;
        foreach (DataGridViewCell j in i.Cells)
        {
            dgArray[j.RowIndex, j.ColumnIndex] = j.Value.ToString();
        }
    }

    Microsoft.Office.Interop.Excel.Range chartRange;

    int rowCount = dgArray.GetLength(0);
    int columnCount = dgArray.GetLength(1);
    chartRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[2, 1]; //I have header info on row 1, so start row 2
    chartRange = chartRange.get_Resize(rowCount, columnCount);
    chartRange.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dgArray);


    oXL.Visible = false;
    oXL.UserControl = false;
    string outputFile = "Output_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

    oWB.SaveAs("c:\\temp\\"+outputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
}
catch (Exception ex)
{
    //...
}

Statically rotate font-awesome icons

In case someone else stumbles upon this question and wants it here is the SASS mixin I use.

@mixin rotate($deg: 90){
    $sDeg: #{$deg}deg;

    -webkit-transform: rotate($sDeg);
    -moz-transform: rotate($sDeg);
    -ms-transform: rotate($sDeg);
    -o-transform: rotate($sDeg);
    transform: rotate($sDeg);
}

What's the difference between tilde(~) and caret(^) in package.json?

See the NPM docs and semver docs:

  • ~version “Approximately equivalent to version”, will update you to all future patch versions, without incrementing the minor version. ~1.2.3 will use releases from 1.2.3 to <1.3.0.

  • ^version “Compatible with version”, will update you to all future minor/patch versions, without incrementing the major version. ^2.3.4 will use releases from 2.3.4 to <3.0.0.

See Comments below for exceptions, in particular for pre-one versions, such as ^0.2.3

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

Edit package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

and Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

How do I configure Apache 2 to run Perl CGI scripts?

You'll need to take a look at your Apache error log to see what the "internal server error" is. The four most likely cases, in my experience would be:

  1. The CGI program is in a directory which does not have CGI execution enabled. Solution: Add the ExecCGI option to that directory via either httpd.conf or a .htaccess file.

  2. Apache is only configured to run CGIs from a dedicated cgi-bin directory. Solution: Move the CGI program there or add an AddHandler cgi-script .cgi statement to httpd.conf.

  3. The CGI program is not set as executable. Solution (assuming a *nix-type operating system): chmod +x my_prog.cgi

  4. The CGI program is exiting without sending headers. Solution: Run the program from the command line and verify that a) it actually runs rather than dying with a compile-time error and b) it generates the correct output, which should include, at the very minimum, a Content-Type header and a blank line following the last of its headers.

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

You could use a WHERE clause like:

WHERE DateColumn BETWEEN
    CAST(date_format(date_sub(NOW(), INTERVAL 1 MONTH),'%Y-%m-01') AS date)
    AND
    date_sub(now(), INTERVAL 1 MONTH)

What is the difference between java and core java?

"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.

Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.

Is it possible to run a .NET 4.5 app on XP?

The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.

The last version of Mono to support Windows XP was 3.2.3.

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

After updating Entity Framework model, Visual Studio does not see changes

This is apparently a bug in the Entity Framework that the model does not get updated when your Edmx file is located inside a folder. The workarounds available at the moment are:

  1. Install VS 2012 Update 1 which should fix the bug.
  2. If you are not in a position to install Update 1, you will have to right click on the model.tt T4 template file and click run custom tool. This will update the classes for you.

Hope that helps someone out there.

Link: http://thedatafarm.com/blog/data-access/watch-out-for-vs2012-edmx-code-generation-special-case/

subquery in codeigniter active record

    $where.= '(';
    $where.= 'admin_trek.trek='."%$search%".'  AND ';
    $where.= 'admin_trek.state_id='."$search".'  OR ';
    $where.= 'admin_trek.difficulty='."$search".' OR ';
    $where.= 'admin_trek.month='."$search".'  AND ';
    $where.= 'admin_trek.status = 1)';

    $this->db->select('*');
    $this->db->from('admin_trek');
    $this->db->join('admin_difficulty',admin_difficulty.difficulty_id = admin_trek.difficulty');
    $this->db->where($where); 
    $query = $this->db->get();

Why is enum class preferred over plain enum?

Because, as said in other answers, class enum are not implicitly convertible to int/bool, it also helps to avoid buggy code like:

enum MyEnum {
  Value1,
  Value2,
};
...
if (var == Value1 || Value2) // Should be "var == Value2" no error/warning

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

jQuery dialog popup

It's quite simple, first HTML must be added:

<div id="dialog"></div>

Then, it must be initialized:

<script type="text/javascript">
  jQuery( document ).ready( function() {
    jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
  });
</script>

After this you can show it by code:

jQuery( '#dialog' ).dialog( 'open' );

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

How to Programmatically Add Views to Views

This is late but this may help someone :) :) For adding the view programmatically try like

LinearLayout rlmain = new LinearLayout(this);      
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);          
LinearLayout   ll1 = new LinearLayout (this);

ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);              
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);              
setContentView(rlmain, llp);

This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

just update classpath 'com.android.tools.build:gradle:X.X.X' in Project Build.Gradle and replace X to the latest version do you have

Disabling Strict Standards in PHP 5.4

It worked for me, when I set error_reporting in two places at same time

somewhere in PHP code

ini_set('error_reporting', 30711);


and in .htaccess file

php_value error_reporting 30711

Colorized grep -- viewing the entire file with highlighted matches

As grep -E '|pattern' has already been suggested, just wanted to clarify it's possible to highlight the whole line too.

For example tail -f /somelog | grep --color -E '| \[2].*':

How to display loading message when an iFrame is loading?

You can use as below

$('#showFrame').on("load", function () {
        loader.hide();
});

Regular expression to match URLs in Java

This works too:

String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

Note:

String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>

So probably the first one is more useful for general use.

How do I manually configure a DataSource in Java?

I think the example is wrong - javax.sql.DataSource doesn't have these properties either. Your DataSource needs to be of the type org.apache.derby.jdbc.ClientDataSource, which should have those properties.

What does getActivity() mean?

Two likely definitions:

Check if a string within a list contains a specific string with Linq

LINQ Any() would do the job:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Find row in datatable with specific id

try this code

DataRow foundRow = FinalDt.Rows.Find(Value);

but set at lease one primary key

Python: list of lists

First, I strongly recommend that you rename your variable list to something else. list is the name of the built-in list constructor, and you're hiding its normal function. I will rename list to a in the following.

Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a it's referring to the same actual list object as last time. So when you call

listoflists.append((a, a[0]))

you can later change a and it changes what the first element of that tuple points to. This does not happen with a[0] because the object (which is an integer) pointed to by a[0] doesn't change (although a[0] points to different objects over the run of your code).

You can create a copy of the whole list a using the list constructor:

listoflists.append((list(a), a[0]))

Or, you can use the slice notation to make a copy:

listoflists.append((a[:], a[0]))

Setting up foreign keys in phpMyAdmin?

InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!

Difference between declaring variables before or in loop?

As a general rule, I declare my variables in the inner-most possible scope. So, if you're not using intermediateResult outside of the loop, then I'd go with B.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Firstly you can find duplicate rows and find count of rows is used how many times and order it by number like this;

_x000D_
_x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

after that create a table and insert result to it.

_x000D_
_x000D_
create table CopyTable _x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

Finally, delete dublicate rows.No is start 0. Except fist number of each group delete all dublicate rows.

_x000D_
_x000D_
delete from  CopyTable where No!= 0;
_x000D_
_x000D_
_x000D_

Remove numbers from string sql server

Quoting part of @Jatin answer with some modifications,

use this in your where statement:

    SELECT * FROM .... etc.
        Where 
         REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE (Name, '0', ''),
        '1', ''),
        '2', ''),
        '3', ''),
        '4', ''),
        '5', ''),
        '6', ''),
        '7', ''),
        '8', ''),
        '9', '') = P_SEARCH_KEY

When to catch java.lang.Error?

Generally you should always catch java.lang.Error and write it to a log or display it to the user. I work in support and see daily that programmers cannot tell what has happened in a program.

If you have a daemon thread then you must prevent it being terminated. In other cases your application will work correctly.

You should only catch java.lang.Error at the highest level.

If you look at the list of errors you will see that most can be handled. For example a ZipError occurs on reading corrupt zip files.

The most common errors are OutOfMemoryError and NoClassDefFoundError, which are both in most cases runtime problems.

For example:

int length = Integer.parseInt(xyz);
byte[] buffer = new byte[length];

can produce an OutOfMemoryError but it is a runtime problem and no reason to terminate your program.

NoClassDefFoundError occur mostly if a library is not present or if you work with another Java version. If it is an optional part of your program then you should not terminate your program.

I can give many more examples of why it is a good idea to catch Throwable at the top level and produce a helpful error message.

Code for Greatest Common Divisor in Python

Very concise solution using recursion:

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a%b)

How do I get my page title to have an icon?

They're called favicons, and are quite easy to make/use. Have a read of http://www.favicon.com/ for help.

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Preloading @font-face fonts?

Since 2017 you have preload

MDN: The preload value of the element's rel attribute allows you to write declarative fetch requests in your HTML , specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements.

<link rel="preload" href="/fonts/myfont.eot" as="font" crossorigin="anonymous" />

Always check browser compatibility.

It is most useful for font preloading (not waiting for the browser to find it in some CSS). You can also preload some logos, icons and scripts.

Create HTTP post request and receive response using C# console application

Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.

Also microsoft recommends to use the HttpClient on this article

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx

An example could look like this:

var client = new HttpClient();
var content = new MultipartFormDataContent
{
     { new StringContent("myUserId"), "userid"},
     { new StringContent("myFileName"), "filename"},
     { new StringContent("myPassword"), "password"},
     { new StringContent("myType"), "type"}
};

var responseMessage = await client.PostAsync("some url", content);        
var stream = await responseMessage.Content.ReadAsStreamAsync();

What is the difference between WCF and WPF?

Windows communication Fundation(WCF) is used for connecting different applications and passing the data's between them using endpoints.

Windows Presentation Foundation is used for designing rich internet applications in the format of xaml.

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

How to set environment variables in Python?

to Set Variable:

item Assignment method using key:

import os    
os.environ['DEBUSSY'] = '1'  #Environ Variable must be string not Int

to get or to check whether its existed or not,

since os.environ is an instance you can try object way.

Method 1:

os.environ.get('DEBUSSY') # this is error free method if not will return None by default

will get '1' as return value

Method 2:

os.environ['DEBUSSY'] # will throw an key error if not found!

Method 3:

'DEBUSSY' in os.environ  # will return Boolean True/False

Method 4:

os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements

How do I create a comma-separated list from an array in PHP?

A functional solution would go like this:

$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ','; 

array_reduce(
    $fruits,
    function($fruitsStr, $fruit) use ($sep) {
        return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
    },
    ''
);

Call angularjs function using jquery/javascript

Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.

Example:

_x000D_
_x000D_
angular.module("app", []).component("component", {_x000D_
  controller: ["$window", function($window) {_x000D_
    var self = this;_x000D_
    _x000D_
    self.logg = function() {_x000D_
      console.log("logging!");_x000D_
    };_x000D_
    _x000D_
    $window.angularControllerLogg = self.logg;_x000D_
  }_x000D_
});_x000D_
               _x000D_
window.angularControllerLogg();
_x000D_
_x000D_
_x000D_

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].

  1. Go to 'Object Explorer' of SQL Management Studio.
  2. Expand Security, then Login.
  3. Select the user you are working with, then right click and select Properties Windows.
  4. In Select a Page, Go to Server Roles
  5. Click on sysadmin and save.

jQuery delete all table rows except first

This worked in the following way in my case and working fine

$("#compositeTable").find("tr:gt(1)").remove();

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

How can I display a modal dialog in Redux that performs asynchronous actions?

Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch from props, do not pass mapDispatchToProps function to connect.

class ModalContainer extends React.Component {
  handleDelete = () => {
    const { dispatch, onClose } = this.props;
    dispatch({type: 'DELETE_POST'});

    someAsyncOperation().then(() => {
      dispatch({type: 'DELETE_POST_SUCCESS'});
      onClose();
    })
  }

  render() {
    const { onClose } = this.props;
    return <Modal onClose={onClose} onSubmit={this.handleDelete} />
  }
}

export default connect(/* no map dispatch to props here! */)(ModalContainer);

The App where the modal is rendered and its visibility state is set:

class App extends React.Component {
  state = {
    isModalOpen: false
  }

  handleModalClose = () => this.setState({ isModalOpen: false });

  ...

  render(){
    return (
      ...
      <ModalContainer onClose={this.handleModalClose} />  
      ...
    )
  }

}

Changing every value in a hash in Ruby

One method that doesn't introduce side-effects to the original:

h = {:a => 'a', :b => 'b'}
h2 = Hash[h.map {|k,v| [k, '%' + v + '%']}]

Hash#map may also be an interesting read as it explains why the Hash.map doesn't return a Hash (which is why the resultant Array of [key,value] pairs is converted into a new Hash) and provides alternative approaches to the same general pattern.

Happy coding.

[Disclaimer: I am not sure if Hash.map semantics change in Ruby 2.x]

How to restart counting from 1 after erasing table in MS Access?

I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0

enter image description here

INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;

This will insert one row with 0 value in AutoNumber column, later delete that row.

React - Preventing Form Submission

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

Example: http://jsbin.com/vowuley/edit?html,js,console,output

How to specify the actual x axis values to plot as x axis ticks in R

In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))

How to access Winform textbox control from another class?

You will need to have some access to the Form's Instance to access its Controls collection and thereby changing the Text Box's Text.

One of ways could be that You can have a Your Form's Instance Available as Public or More better Create a new Constructor For your Second Form and have it receive the Form1's instance during initialization.

How to convert integer to char in C?

A char in C is already a number (the character's ASCII code), no conversion required.

If you want to convert a digit to the corresponding character, you can simply add '0':

c = i +'0';

The '0' is a character in the ASCll table.

Python 3.1.1 string to hex

The easiest way to do it in Python 3.5 and higher is:

>>> 'halo'.encode().hex()
'68616c6f'

If you manually enter a string into a Python Interpreter using the utf-8 characters, you can do it even faster by typing b before the string:

>>> b'halo'.hex()
'68616c6f'

Equivalent in Python 2.x:

>>> 'halo'.encode('hex')
'68616c6f'

Android: how do I check if activity is running?

thanks kkudi! I was able to adapt your answer to work for an activity... here's what worked in my app..

public boolean isServiceRunning() { 

ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE); 
    List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE); 
    isServiceFound = false; 
    for (int i = 0; i < services.size(); i++) { 
        if (services.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.lyo.AutoMessage/com.lyo.AutoMessage.TextLogList}")) {
            isServiceFound = true;
        }
    } 
    return isServiceFound; 
} 

this example will give you a true or false if the topActivity matches what the user is doing. So if the activity your checking for is not being displayed (i.e. is onPause) then you won't get a match. Also, to do this you need to add the permission to your manifest..

<uses-permission  android:name="android.permission.GET_TASKS"/>

I hope this was helpful!

Java Does Not Equal (!=) Not Working?

you can use equals() method to statisfy your demands. == in java programming language has a different meaning!

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

Meaning of *& and **& in C++

This *& in theory as well as in practical its possible and called as reference to pointer variable. and it's act like same. This *& combination is used in as function parameter for 'pass by' type defining. unlike ** can also be used for declaring a double pointer variable.
The passing of parameter is divided into pass by value, pass by reference, pass by pointer. there are various answer about "pass by" types available. however the basic we require to understand for this topic is.

pass by reference --> generally operates on already created variable refereed while passing to function e.g fun(int &a);

pass by pointer --> Operates on already initialized 'pointer variable/variable address' passing to function e.g fun(int* a);

auto addControl = [](SomeLabel** label, SomeControl** control) {
    *label = new SomeLabel;
    *control = new SomeControl;
    // few more operation further.
};

addControl(&m_label1,&m_control1);
addControl(&m_label2,&m_control2);
addControl(&m_label3,&m_control3);

in the above example(this is the real life problem i came across) i am trying to init few pointer variable from the lambda function and for that we need to pass it by double pointer, so that comes with d-referencing of pointer for its all usage inside of that lambda + while passing pointer in function which takes double pointer, you need to pass reference to the pointer variable.

so with this same thing reference to the pointer variable, *& this combination helps. in below given way for the same example i have mentioned above.

auto addControl = [](SomeLabel*& label, SomeControl*& control) {
        label = new SomeLabel;
        control = new SomeControl;
        // few more operation further.
    };

addControl(m_label1,m_control1);
addControl(m_label2,m_control2);
addControl(m_label3,m_control3);

so here you can see that you neither require d-referencing nor we require to pass reference to pointer variable while passing in function, as current pass by type is already reference to pointer.

Hope this helps :-)

how to display employee names starting with a and then b in sql

select columns
  from table
 where (
         column like 'a%' 
      or column like 'b%' )
 order by column asc

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

ImportError: DLL load failed: %1 is not a valid Win32 application

I just hit this and the problem was that the package had at one point been installed in the per-user packages directory. (On Windows.) aka %AppData%\Python. So Python was looking there first, finding an old 32-bit version of the .pyd file, and failing with the listed error. Unfortunately pip uninstall by itself wasn't enough to clean this, and at this time pip 10.0.1 doesn't seem to have a --user parameter for uninstall, only for install.

tl;dr Deleting the old .pyd from %AppData%\python\python27\site-packages resolved this problem for me.

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

How to create a DataFrame from a text file in Spark

I have given different ways to create DataFrame from text file

val conf = new SparkConf().setAppName(appName).setMaster("local")
val sc = SparkContext(conf)

raw text file

val file = sc.textFile("C:\\vikas\\spark\\Interview\\text.txt")
val fileToDf = file.map(_.split(",")).map{case Array(a,b,c) => 
(a,b.toInt,c)}.toDF("name","age","city")
fileToDf.foreach(println(_))

spark session without schema

import org.apache.spark.sql.SparkSession
val sparkSess = 
SparkSession.builder().appName("SparkSessionZipsExample")
.config(conf).getOrCreate()

val df = sparkSess.read.option("header", 
"false").csv("C:\\vikas\\spark\\Interview\\text.txt")
df.show()

spark session with schema

import org.apache.spark.sql.types._
val schemaString = "name age city"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, 
StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header", 
"false").schema(schema).csv("C:\\vikas\\spark\\Interview\\text.txt")
dfWithSchema.show()

using sql context

import org.apache.spark.sql.SQLContext

val fileRdd = 
sc.textFile("C:\\vikas\\spark\\Interview\\text.txt").map(_.split(",")).map{x 
=> org.apache.spark.sql.Row(x:_*)}
val sqlDf = sqlCtx.createDataFrame(fileRdd,schema)
sqlDf.show()

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

How to remove all null elements from a ArrayList or String Array?

Similar to @Lithium answer but does not throw a "List may not contain type null" error:

   list.removeAll(Collections.<T>singleton(null));

JFrame in full screen Java

Add:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
frame.setUndecorated(true);
frame.setVisible(true);

HTML5 and frameborder

Since the frameborder attribute is only necessary for IE, there is another way to get around the validator. This is a lightweight way that doesn't require Javascript or any DOM manipulation.

<!--[if IE]>
   <iframe src="source" frameborder="0">?</iframe>
<![endif]-->
<!--[if !IE]>-->
   <iframe src="source" style="border:none">?</iframe>
<!-- <![endif]-->

Sorting list based on values from another list

I actually came here looking to sort a list by a list where the values matched.

list_a = ['foo', 'bar', 'baz']
list_b = ['baz', 'bar', 'foo']
sorted(list_b, key=lambda x: list_a.index(x))
# ['foo', 'bar', 'baz']

Custom sort function in ng-repeat

The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.

e.g. Given the following assignment:

$scope.cards = {
  "card2": {
    values: {
      opt1: 9,
      opt2: 12
    }
  },
  "card1": {
    values: {
      opt1: 9,
      opt2: 11
    }
  }
};

and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.

To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.

myApp.filter('orderByValue', function () {
  // custom value function for sorting
  function myValueFunction(card) {
    return card.values.opt1 + card.values.opt2;
  }

  return function (obj) {
    var array = [];
    Object.keys(obj).forEach(function (key) {
      // inject key into each object so we can refer to it from the template
      obj[key].name = key;
      array.push(obj[key]);
    });
    // apply a custom sorting function
    array.sort(function (a, b) {
      return myValueFunction(b) - myValueFunction(a);
    });
    return array;
  };
});

We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.

<ul ng-repeat="card in cards | orderByValue">
    <li>{{card.name}} {{value(card)}}</li>
</ul>

Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/

Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332

How can I sort a List alphabetically?

By using Collections.sort(), we can sort a list.

public class EmployeeList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<String> empNames= new ArrayList<String>();

        empNames.add("sudheer");
        empNames.add("kumar");
        empNames.add("surendra");
        empNames.add("kb");

        if(!empNames.isEmpty()){

            for(String emp:empNames){

                System.out.println(emp);
            }

            Collections.sort(empNames);

            System.out.println(empNames);
        }
    }
}

output:

sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.

How to make inactive content inside a div?

Using jquery you might do something like this:

// To disable 
$('#targetDiv').children().attr('disabled', 'disabled');

// To enable
$('#targetDiv').children().attr('enabled', 'enabled');

Here's a jsFiddle example: http://jsfiddle.net/monknomo/gLukqygq/

You could also select the target div's children and add a "disabled" css class to them with different visual properties as a callout.

//disable by adding disabled class
$('#targetDiv').children().addClass("disabled");

//enable by removing the disabled class
$('#targetDiv').children().removeClass("disabled");

Here's a jsFiddle with the as an example: https://jsfiddle.net/monknomo/g8zt9t3m/

Command to get latest Git commit hash from a branch

you can git fetch nameofremoterepo, then git log

and personally, I alias gitlog to git log --graph --oneline --pretty --decorate --all. try out and see if it fits you

Python 2.6: Class inside a Class?

It sounds like you are talking about aggregation. Each instance of your player class can contain zero or more instances of Airplane, which, in turn, can contain zero or more instances of Flight. You can implement this in Python using the built-in list type to save you naming variables with numbers.

class Flight(object):

    def __init__(self, duration):
        self.duration = duration


class Airplane(object):

    def __init__(self):
        self.flights = []

    def add_flight(self, duration):
        self.flights.append(Flight(duration))


class Player(object):

    def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
        self.stock = stock
        self.bank = bank
        self.fuel = fuel
        self.total_pax = total_pax
        self.airplanes = []


    def add_planes(self):
        self.airplanes.append(Airplane())



if __name__ == '__main__':
    player = Player()
    player.add_planes()
    player.airplanes[0].add_flight(5)

How to disable a particular checkstyle rule for a particular line of code?

I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.

Long Press in JavaScript?

There is no 'jQuery' magic, just JavaScript timers.

var pressTimer;

$("a").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() { ... Your Code ...},1000);
  return false; 
});

Declaring a boolean in JavaScript using just var

If you want IsLoggedIn to be treated as a boolean you should initialize as follows:

var IsLoggedIn=true;

If you initialize it with var IsLoggedIn=1; then it will be treated as an integer.

However at any time the variable IsLoggedIn could refer to a different data type:

 IsLoggedIn="Hello World";

This will not cause an error.

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

If input value is blank, assign a value of "empty" with Javascript

This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

How to prevent text in a table cell from wrapping

For Use with React / Material UI

In case you're here wondering how this works for Material UI when building in React, here's how you add this to your <TableHead> Component:

<TableHead style={{ whiteSpace: 'nowrap'}}>

How do I type a TAB character in PowerShell?

If it helps you can embed a tab character in a double quoted string:

PS> "`t hello"

Firefox "ssl_error_no_cypher_overlap" error

I've had the same problem; to solve was enough to enable all the SSL schemas in "about:config". I was finding them by filtering with ssl. First I anabled all options for afret disabling the unnecessary ones.

Java array assignment (multiple values)

On declaration you can do the following.

float[] values = {0.1f, 0.2f, 0.3f};

When the field is already defined, try this.

values = new float[] {0.1f, 0.2f, 0.3f};

Be aware that also the second version creates a new array. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.

Get specific line from text file using just shell script

The standard way to do this sort of thing is to use external tools. Disallowing the use of external tools while writing a shell script is absurd. However, if you really don't want to use external tools, you can print line 5 with:

i=0; while read line; do test $((++i)) = 5 && echo "$line"; done < input-file

Note that this will print logical line 5. That is, if input-file contains line continuations, they will be counted as a single line. You can change this behavior by adding -r to the read command. (Which is probably the desired behavior.)

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

Send email by using codeigniter library via localhost

Please check my working code.

function sendMail()
{
    $config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => '[email protected]', // change it to yours
  'smtp_pass' => 'xxx', // change it to yours
  'mailtype' => 'html',
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);

        $message = '';
        $this->load->library('email', $config);
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]'); // change it to yours
      $this->email->to('[email protected]');// change it to yours
      $this->email->subject('Resume from JobsBuddy for your Job posting');
      $this->email->message($message);
      if($this->email->send())
     {
      echo 'Email sent.';
     }
     else
    {
     show_error($this->email->print_debugger());
    }

}

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

Working with TIFFs (import, export) in Python using numpy

PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images(): 
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)

You can install PyLibTiff with

pip3 install numpy libtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

How to leave space in HTML

If you want to leave blank space in HTML while editing the website just use <br /> and copy-paste it under the last one and keep going like that until you have enough space. Hope it helps.

Displaying tooltip on mouse hover of a text

You shouldn't use the control private tooltip, but the form one. This example works well:

public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;

    public Form1()
    {
        InitializeComponent();
        this.components = new System.ComponentModel.Container();
        this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);

        MyRitchTextBox myRTB = new MyRitchTextBox();
        this.Controls.Add(myRTB);

        myRTB.Location = new Point(10, 10);
        myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
        myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
    }


    void myRTB_MouseEnter(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Show("Hello!!!", rtb);
        }
    }

    void myRTB_MouseLeave(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Hide(rtb);
        }
    }


    public class MyRitchTextBox : RichTextBox
    {
    }

}

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

Microsoft.Office.Core Reference Missing

In case you are using Visual Studio 2012, for this to work and in order to make reference to Microsoft Office Core, you have to make the reference through Visual Studio by clicking on the top menu's Project, Add Reference, Extensions button and checking office which is now (14.0).

Program "make" not found in PATH

Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe, try renaming it to make.exe

How do I remove the horizontal scrollbar in a div?

Use This chunk of code..

.card::-webkit-scrollbar {
  display: none;
}

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Percentage Height HTML 5/CSS

I am trying to set a div to a certain percentage height in CSS

Percentage of what?

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html> and <body>, have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)

Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh) and viewport width (vw):

div {
    height:100vh; 
}

See here for more info.

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

REST API - why use PUT DELETE POST GET?

In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.

SQL string value spanning multiple lines in query

What's the column "BIO" datatype? What database server (sql/oracle/mysql)? You should be able to span over multiple lines all you want as long as you adhere to the character limit in the column's datatype (ie: varchar(200) ). Try using single quotes, that might make a difference. This works for me:

update table set mycolumn = 'hello world,
my name is carlos.
goodbye.'
where id = 1;

Also, you might want to put in checks for single quotes if you are concatinating the sql string together in C#. If the variable contains single quotes that could escape the code out of the sql statement, therefore, not doing all the lines you were expecting to see.

BTW, you can delimit your SQL statements with a semi colon like you do in C#, just as FYI.

Is it possible to use "return" in stored procedure?

-- IN arguments : you get them. You can modify them locally but caller won't see it
-- IN OUT arguments: initialized by caller, already have a value, you can modify them and the caller will see it
-- OUT arguments: they're reinitialized by the procedure, the caller will see the final value.
CREATE PROCEDURE f (p IN NUMBER, x IN OUT NUMBER, y OUT NUMBER)
IS
BEGIN
   x:=x * p;
   y:=4 * p;
END;
/

SET SERVEROUTPUT ON

declare
   foo number := 30;
   bar number := 0;
begin
   f(5,foo,bar);
   dbms_output.put_line(foo || ' ' || bar);
end;
/

-- Procedure output can be collected from variables x and y (ans1:= x and ans2:=y) will be: 150 and 20 respectively.

-- Answer borrowed from: https://stackoverflow.com/a/9484228/1661078

Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

How do I make a text input non-editable?

you just need to add disabled at the end

<input type="text" value="3" class="field left" disabled>

Any way to clear python's IDLE window?

"command + L" for MAC OS X.

"control + L" for Ubuntu

Clears the last line on the interactive session

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

The simplest code would be like, keep your properties files into resources folder, either in src/main/resource or in src/test/resource. Then use below code to read properties files:

public class Utilities {
    static {
        rb1 = ResourceBundle.getBundle("fileNameWithoutExtension"); 
              // do not use .properties extension
    }
    public static String getConfigProperties(String keyString) {
        return rb1.getString(keyString);
    }
}

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

Why do I need 'b' to encode a string with Base64?

If the string is Unicode the easiest way is:

import base64                                                        

a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))

# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'

b = base64.b64decode(a).decode("utf-8", "ignore")                    

print(b)
# b :complex string: ñáéíóúÑ

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

Return first N key:value pairs from dict

I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.

I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.

Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.

The answer to the OP question that worked best for me.

itr = iter(dic.items())
lst = [next(itr) for i in range(3)]

How to call Stored Procedure in Entity Framework 6 (Code-First)?

This works for me by pulling back data from a stored procedure while passing in a parameter.

var param = new SqlParameter("@datetime", combinedTime);
var result = 
        _db.Database.SqlQuery<QAList>("dbo.GetQAListByDateTime @datetime", param).ToList();

_db is the dbContext

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

change the your servlet name dispatcher to any other name .because dispatcher is predefined name for spring3,spring4 versions.

<servlet>
    <servlet-name>ahok</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>ashok</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

PowerShell script to return versions of .NET Framework on a machine?

Added v4.8 support to the script:

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
  name="Product"
  expression={
      switch -regex ($_.Release) {
        "378389" { [Version]"4.5" }
        "378675|378758" { [Version]"4.5.1" }
        "379893" { [Version]"4.5.2" }
        "393295|393297" { [Version]"4.6" }
        "394254|394271" { [Version]"4.6.1" }
        "394802|394806" { [Version]"4.6.2" }
        "460798|460805" { [Version]"4.7" }
        "461308|461310" { [Version]"4.7.1" }
        "461808|461814" { [Version]"4.7.2" }
        "528040|528049" { [Version]"4.8" }
        {$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
      }
    }
}

Installing RubyGems in Windows

To setup you Ruby development environment on Windows:

  1. Install Ruby via RubyInstaller: http://rubyinstaller.org/downloads/

  2. Check your ruby version: Start - Run - type in cmd to open a windows console

  3. Type in ruby -v
  4. You will get something like that: ruby 2.0.0p353 (2013-11-22) [i386-mingw32]

For Ruby 2.4 or later, run the extra installation at the end to install the DevelopmentKit. If you forgot to do that, run ridk install in your windows console to install it.

For earlier versions:

  1. Download and install DevelopmentKit from the same download page as Ruby Installer. Choose an ?exe file corresponding to your environment (32 bits or 64 bits and working with your version of Ruby).
  2. Follow the installation instructions for DevelopmentKit described at: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit#installation-instructions. Adapt it for Windows.
  3. After installing DevelopmentKit you can install all needed gems by just running from the command prompt (windows console or terminal): gem install {gem name}. For example, to install rails, just run gem install rails.

Hope this helps.

Running Facebook application on localhost

if you use localhost:

in Facebook-->Settings-->Basic, in field "App Domains" write "localhost", then click to "+Add Platform" choose "Web Site",

it will create two fields "Mobile Site URL" and "Site URL", in "Site URL" write again "localhost".

works for me.

why are there two different kinds of for loops in java?

Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

I have faced same issue while trying to read data from file in R. After figuring out I found out that sep value is causing this issue. Once I tried this with correct separator it was working as expected.

read.table("file_location/file_name",
    sep="." # exact separator as given in file: also "," or "\t" etc.
    col_names=c("name_1", "name_2",..))

Angular2 - Http POST request parameters

These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append() syntax to achieve multiple params in the body since we are working with an immutable object:

login(userName: string, password: string): Promise<boolean> {
    if (!userName || !password) {
      return Promise.resolve(false);
    }

    let body: HttpParams = new HttpParams();
    body = body.append('grant_type', 'password');
    body = body.append('username', userName);
    body = body.append('password', password);

    return this.http.post(this.url, body)
      .map(res => {
        if (res) {          
          return true;
        }
        return false;
      })
      .toPromise();
  }

SQL Server: the maximum number of rows in table

It's hard to give a generic answer to this. It really depends on number of factors:

  • what size your row is
  • what kind of data you store (strings, blobs, numbers)
  • what do you do with your data (just keep it as archive, query it regularly)
  • do you have indexes on your table - how many
  • what's your server specs

etc.

As answered elsewhere here, 100,000 a day and thus per table is overkill - I'd suggest monthly or weekly perhaps even quarterly. The more tables you have the bigger maintenance/query nightmare it will become.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

It does seem a little cumbersome to ignore files (and folders) in Team Foundation Server. I've found a couple ways to do this (using TFS / Team Explorer / Visual Studio 2008). These methods work with the web site ASP project type, too.

One way is to add a new or existing item to a project (e.g. right click on project, Add Existing Item or drag and drop from Windows explorer into the solution explorer), let TFS process the file(s) or folder, then undo pending changes on the item(s). TFS will unmark them as having a pending add change, and the files will sit quietly in the project and stay out of TFS.

Another way is with the Add Items to Folder command of Source Control Explorer. This launches a small wizard, and on one of the steps you can select items to exclude (although, I think you have to add at least one item to TFS with this method for the wizard to let you continue).

You can even add a forbidden patterns check-in policy (under Team -> Team Project Settings -> Source Control... -> Check-in Policy) to disallow other people on the team from mistakenly checking in certain assets.

Make a VStack fill the width of the screen in SwiftUI

 var body: some View {
      VStack {
           CarouselView().edgesIgnoringSafeArea(.all)           
           List {
                ForEach(viewModel.parents) { k in
                    VideosRowView(parent: k)
                }
           }
    }
 }

How to set fake GPS location on IOS real device

When running in debug mode you can use the little arrow button in the debug area (Shift+Cmd+Y) in Xcode to specify a location. There are some presets or you can also add a GPX file.

Specify debug location

You can generate GPX files here manually: http://www.bikehike.co.uk/mapview.php (from answer: https://stackoverflow.com/a/17478860/881197)

SmartGit Installation and Usage on Ubuntu

Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

What is the difference between user variables and system variables?

Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:

$("span").unbind("click");

Get value when selected ng-option changes

You will get selected option's value and text from list/array by using filter.
editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName

<select name="statusSelect"
      id="statusSelect"
      class="form-control"
      ng-model="editobj.Flag"
      ng-options="option.Value as option.KeyName for option in EmployeeStatus"
      ng-change="editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName">
</select>

How to make Sonar ignore some classes for codeCoverage metric?

Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:

<plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-clover2-plugin</artifactId>
    <version>${clover-version}</version>
    <configuration> 
        <excludes> 
            <exclude>**/*Dull.java</exclude> 
        </excludes> 
    </configuration>
</plugin>

Also, you can include the following Sonar configuration:

<properties>
    <sonar.exclusions>
        **/domain/*.java,
        **/transfer/*.java
    </sonar.exclusions>
</properties> 

Subversion stuck due to "previous operation has not finished"?

This can happen when you have files still open when you try to SVN switch / cleanup.

I had a branch where I had created a new file, which I had open in another application. Switching to another branch could not remove the file causing the switch to fail. This was also causing the svn cleanup to fail, however this is not displayed as the reason in the Tortoise SVN UI.

Running svn cleanup from a console window (on the root folder) clearly shows the error file\location\file.ext: The process cannot access the file because it is being used by another process

Closing any open file handles / windows and running the console svn cleanup then allows the cleanup to work correctly.

Long story short - run svn cleanup in the console to see a more detailed error.

Generating Random Number In Each Row In Oracle Query

If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

Windows command for file size only

Try forfiles:

forfiles /p C:\Temp /m file1.txt /c "cmd /c echo @fsize"

The forfiles command runs command c for each file m in directory p.

The variable @fsize is replaced with the size of each file.

If the file C:\Temp\file1.txt is 27 bytes, forfiles runs this command:

cmd /c echo 27

Which prints 27 to the screen.

As a side-effect, it clears your screen as if you had run the cls command.

Modifying Objects within stream in Java8 while iterating

Instead of creating strange things, you can just filter() and then map() your result.

This is much more readable and sure. Streams will make it in only one loop.

How to find largest objects in a SQL Server database?

If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Dive right it, make it a hobby, and have fun :)

Coming from an electronics background myself I can tell you that you should pick it up pretty quickly. And having an electronics background will give you a deeper understanding of the underlying hardware.

IMHO the root of information technology is electronics.

For example..

Think of objects as components.

The .NET framework is essentially drawers full of standard components.

For example you know what a 7400 (NAND gate) is capable of doing. You have a data sheet showing the pin outs and sample configurations. You don't typically care about the circuitry inside. Software objects are the same way. We have inputs and we have methods that do something to the inputs to produce predictable outputs. As developers we typically don't care how the object was written... just that it does what it says it will do.

You also know that you can build additional logic circuits by using two or more NAND gates. This of this as instantiation.

You also know that you can take a NAND gate and place it inside a circuit where you can modify the input signals coming in so the outputs have different behaviors. This is a crude example but you can think of this as inheritance.

I have also learned it helps to have a project to work on. It could be a hobbyist project or a work project. Start small, get something very basic working, and work up from there.

To answer your specific question on "what should I learn first".

1) Take your project you have in mind and break it into steps. For example... get a number from the user, add one to the number, display the result. Think of this as your design.

2) Learn basic C#. Write a simple console application that does something. Learn what an if statement is (this is all boolean logic so it should be somewhat familiar), learn about loops, learn about mathematical operations, learn about functions (subroutines). Play with simple file i/o (reading and writing text files). The basic C# can be thought of as your wiring and discrete components (resistors, caps, transistors, etc) to your chips (object).

3) Learn how to instantiate and use objects from the framework. You have already been doing this but now it's time to delve in further. For example... play with System.Console some more... try making the speaker beep. Also start looking for objects that you may want to use for database work.

4) Learn basic SQL. Lots of help and examples online. Pick a database you want to work with. I personally think MS Access is a great beginners database. I would not use it for multi-user or cross platform desktop applications... but it is a great single user database for Windows users... and it is a great way to learn the basics of SQL. There are other simple free databases available (Open Office has one for example) if you don't want to shell out $ for Access.

5) Expand your app to do something with a database.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my case was a mistake made by me. I added a new file as "OS X>Source>Cocoa Class", instead of "iOS>Source>Cocoa Touch Class".

Working with huge files in VIM

I had the same problem, but it was a 300GB mysql dump and I wanted to get rid of the DROP and change CREATE TABLE to CREATE TABLE IF NOT EXISTS so didn't want to run two invocations of sed. I wrote this quick Ruby script to dupe the file with those changes:

#!/usr/bin/env ruby

matchers={
    %q/^CREATE TABLE `foo`/ => %q/CREATE TABLE IF NOT EXISTS `foo`/,
    %q/^DROP TABLE IF EXISTS `foo`;.*$/ => "-- DROP TABLE IF EXISTS `foo`;"
}

matchers.each_pair { |m,r|
    STDERR.puts "%s: %s" % [ m, r ]
}

STDIN.each { |line|
    #STDERR.puts "line=#{line}"
    line.chomp!
    unless matchers.length == 0
        matchers.each_pair { |m,r|
            re=/#{m}/
            next if line[re].nil?
            line.sub!(re,r)
            STDERR.puts "Matched: #{m} -> #{r}"
            matchers.delete(m)
            break
        }
    end
    puts line
}

Invoked like

./mreplace.rb < foo.sql > foo_two.sql

UIView bottom border?

I wrote a general method that will add a border on whichever sides you wish in any UIView. You can define thickness, color, margins and zOrder for each side.

/*
 view: the view to draw border around
 thickness: thickness of the border on the given side
 color: color of the border on the given side
 margin: space between the border's outer edge and the view's frame edge on the given side.
 zOrder: defines the order to add the borders to the view.  The borders will be added by zOrder from lowest to highest, thus making the highest priority border visible when two borders overlap at the corners.
*/

    +(void) drawBorderAroundUIView:(UIView *) view thicknessLeft:(CGFloat) thicknessLeft colorLeft:(UIColor *)colorLeft marginLeft:(CGFloat) marginLeft zOrderLeft:(int) zOrderLeft thicknessRight:(CGFloat) thicknessRight colorRight:(UIColor *)colorRight marginRight:(CGFloat) marginRight zOrderRight:(int) zOrderRight thicknessTop:(CGFloat) thicknessTop colorTop:(UIColor *)colorTop marginTop:(CGFloat) marginTop zOrderTop:(int) zOrderTop thicknessBottom:(CGFloat) thicknessBottom colorBottom:(UIColor *)colorBottom marginBottom:(CGFloat) marginBottom zOrderBottom:(int) zOrderBottom{
    //make margins be the outside edge and make positive margin represent a smaller rectangle
    marginBottom = -1 * marginBottom - thicknessBottom;
    marginTop = -1 * marginTop - thicknessTop;
    marginLeft = -1 * marginLeft - thicknessLeft;
    marginRight = -1 * marginRight - thicknessRight;

    //get reference points for corners
    CGPoint upperLeftCorner = CGPointZero;
    CGPoint lowerLeftCorner = CGPointMake(upperLeftCorner.x, upperLeftCorner.y + view.frame.size.height);
    CGPoint upperRightCorner = CGPointMake(upperLeftCorner.x + view.frame.size.width, upperLeftCorner.y);

    //left
    CALayer *leftBorder = [CALayer layer];
    leftBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, thicknessLeft, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
    leftBorder.backgroundColor = colorLeft.CGColor;

    //right
    CALayer *rightBorder = [CALayer layer];
    rightBorder.frame = CGRectMake(upperRightCorner.x + marginRight, upperRightCorner.y - thicknessTop - marginTop, thicknessRight, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
    rightBorder.backgroundColor = colorRight.CGColor;

    //top
    CALayer *topBorder = [CALayer layer];
    topBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessTop);
    topBorder.backgroundColor = colorTop.CGColor;

    //bottom
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, lowerLeftCorner.y + marginBottom, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessBottom);
    bottomBorder.backgroundColor = colorBottom.CGColor;

    //define dictionary keys to be used for adding borders in order of zOrder
    NSString *borderDK = @"border";
    NSString *zOrderDK = @"zOrder";

    //storing borders in dictionaries in preparation to add them in order of zOrder
    NSDictionary *leftBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:leftBorder, borderDK, [NSNumber numberWithInt:zOrderLeft], zOrderDK, nil];
    NSDictionary *rightBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:rightBorder, borderDK, [NSNumber numberWithInt:zOrderRight], zOrderDK, nil];
    NSDictionary *topBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:topBorder, borderDK, [NSNumber numberWithInt:zOrderTop], zOrderDK, nil];
    NSDictionary *bottomBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:bottomBorder, borderDK, [NSNumber numberWithInt:zOrderBottom], zOrderDK, nil];

    NSMutableArray *borders = [NSMutableArray arrayWithObjects:leftBorderDictionary, rightBorderDictionary, topBorderDictionary, bottomBorderDictionary, nil];

    //add borders in order of zOrder (lowest -> highest).  Thus the highest zOrder will be added last so it will be on top.
    while (borders.count)
    {
        //look for the next lowest zOrder border to add
        NSDictionary *nextBorderToLayDown = [borders objectAtIndex:0];
        for (int indexOfBorder = 0; indexOfBorder < borders.count; indexOfBorder++)
        {
            NSDictionary *borderAtIndex = [borders objectAtIndex:indexOfBorder];
            if ([[borderAtIndex objectForKey:zOrderDK] intValue] < [[nextBorderToLayDown objectForKey:zOrderDK] intValue])
            {
                nextBorderToLayDown = borderAtIndex;
            }
        }
        //add the border to the view
        [view.layer addSublayer:[nextBorderToLayDown objectForKey:borderDK]];
        [borders removeObject:nextBorderToLayDown];
    }
}

How to run or debug php on Visual Studio Code (VSCode)

To debug php with vscode,you need these things:

  1. vscode with php debuge plugin(XDebug) installed;
  2. php with XDebug.so/XDebug.dll downloaded and configured;
  3. a web server,such as apache/nginx or just nothing(use the php built-in server)

you can gently walk through step 1 and 2,by following the vscode official guide.It is fully recommended to use XDebug installation wizard to verify your XDebug configuration.

If you want to debug without a standalone web server,the php built-in maybe a choice.Start the built-in server by php -S localhost:port -t path/to/your/project command,setting your project dir as document root.You can refer to this post for more details.

How to search through all Git and Mercurial commits in the repository for a certain string?

One command in git that I think it's much easier to find a string:

git log --pretty=oneline --grep "string to search"

works in Git 2.0.4

How to configure slf4j-simple

You can programatically change it by setting the system property:

public class App {

    public static void main(String[] args) {

        System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");

        final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);

        log.trace("trace");
        log.debug("debug");
        log.info("info");
        log.warn("warning");
        log.error("error");

    }
}

The log levels are ERROR > WARN > INFO > DEBUG > TRACE.

Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Always use nvarchar.

You may never need the double-byte characters for most applications. However, if you need to support double-byte languages and you only have single-byte support in your database schema it's really expensive to go back and modify throughout your application.

The cost of migrating one application from varchar to nvarchar will be much more than the little bit of extra disk space you'll use in most applications.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

For me the issue got resolved by doing the following:

Navigated to Tool --> Options --> Project and Solutions --> Web Projects

I could find the first check box "Use the 64 bit version of IIS Express of web sites and projects" was unchecked.

Selecting this check box helped me in launching the WCF Client.

VS Version : VS2019

What's the difference between `raw_input()` and `input()` in Python 3?

If You want to ensure, that your code is running with python2 and python3, use function input () in your script and add this to begin of your script:

from sys import version_info
if version_info.major == 3:
    pass
elif version_info.major == 2:
    try:
        input = raw_input
    except NameError:
        pass
else:
    print ("Unknown python version - input function not safe")

Git copy file preserving history

Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.

The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).

So in git this is not a matter of how you commit your changes but how you look at the committed changes later.

What is the maximum size of a web browser's cookie's key?

Actually, RFC 2965, the document that defines how cookies work, specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

See section 5.3, "Implementation Limits", in the RFC.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id

I would run

sp_helpconstraint sup_item

and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.

Convert row to column header for Pandas DataFrame,

It would be easier to recreate the data frame. This would also interpret the columns types from scratch.

headers = df.iloc[0]
new_df  = pd.DataFrame(df.values[1:], columns=headers)

How to create a dump with Oracle PL/SQL Developer?

There are some easy steps to make Dump file of your Tables,Users and Procedures:

Goto sqlplus or any sql*plus connect by your username or password

  1. Now type host it looks like SQL>host.
  2. Now type "exp" means export.
  3. It ask u for username and password give the username and password of that user of which you want to make a dump file.
  4. Now press Enter.
  5. Now option blinks for Export file: EXPDAT.DMP>_ (Give a path and file name to where you want to make a dump file e.g e:\FILENAME.dmp) and the press enter
  6. Select the option "Entire Database" or "Tables" or "Users" then press Enter
  7. Again press Enter 2 more times table data and compress extent
  8. Enter the name of table like i want to make dmp file of table student existing so type student and press Enter
  9. Enter to quit now your file at your given path is dump file now import that dmp file to get all the table data.

How to print multiple lines of text with Python

I wanted to answer to the following question which is a little bit different than this:

Best way to print messages on multiple lines

He wanted to show lines from repeated characters too. He wanted this output:

----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000

----------------------------------------

You can create those lines inside f-strings with a multiplication, like this:

run_mode, num_repeats, num_runs = 'short', 5, 1000

s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}

{'-'*40}
"""

print(s)

Is there a way to detect if a browser window is not currently active?

There is a neat library available on GitHub:

https://github.com/serkanyersen/ifvisible.js

Example:

// If page is visible right now
if( ifvisible.now() ){
  // Display pop-up
  openPopUp();
}

I've tested version 1.0.1 on all browsers I have and can confirm that it works with:

  • IE9, IE10
  • FF 26.0
  • Chrome 34.0

... and probably all newer versions.

Doesn't fully work with:

  • IE8 - always indicate that tab/window is currently active (.now() always returns true for me)

Count the number of occurrences of each letter in string

protected void btnSave_Click(object sender, EventArgs e)
    {           
        var FullName = "stackoverflow"

        char[] charArray = FullName.ToLower().ToCharArray();
        Dictionary<char, int> counter = new Dictionary<char, int>();
        int tempVar = 0;
        foreach (var item in charArray)
        {
            if (counter.TryGetValue(item, out tempVar))
            {
                counter[item] += 1;
            }
            else
            {
                counter.Add(item, 1);
            }
        }
        //var numberofchars = "";
        foreach (KeyValuePair<char, int> item in counter)
        {
            if (counter.Count > 0)
            {
                //Label1.Text=split(item.
            }
            Response.Write(item.Value + " " + item.Key + "<br />");
            // Label1.Text=item.Value + " " + item.Key + "<br />";
            spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
        }

    }

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

C programming in Visual Studio

Yes, you can:

You can create a C-language project by using C++ project templates. In the generated project, locate files that have a .cpp file name extension and change it to .c. Then, on the Project Properties page for the project (not for the solution), expand Configuration Properties, C/C++ and select Advanced. Change the Compile As setting to Compile as C Code (/TC).

https://docs.microsoft.com/en-us/cpp/ide/visual-cpp-project-types?view=vs-2017

How do I find the maximum of 2 numbers?

Use the builtin function max.

Example: max(2, 4) returns 4.

Just for giggles, there's a min as well...should you need it. :P

How to check if an array is empty?

Your problem is that you are NOT testing the length of the array until it is too late.

But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.

The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.

How to set placeholder value using CSS?

As @Sarfraz already mentioned CSS, I'll just add HTML5 to the mix.

You can use the HTML5 placeholder attribute:

<input type="text" placeholder="Placeholder text blah blah." />

How can I make my string property nullable?

Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; } and you'll be able to set it to null.

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

How can I find an element by CSS class with XPath?

I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago

//div[contains(concat(' ', @class, ' '), ' Test ')]

Remove HTML Tags in Javascript with Regex

The way I do it is practically a one-liner.

The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.

Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.

I realize this question is old, I just thought my solution was unique and wanted to share. :)

function getTextFromString(htmlString) {
    return document
        .createRange()
        // Creates a fragment and turns the supplied string into HTML nodes
        .createContextualFragment(htmlString)
        // Gets the text from the fragment
        .textContent
        // Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
        .replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
        // Trims off any extra space on either end of the string
        .trim();
}

var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');

alert(cleanString);

Keep CMD open after BAT file executes

In Windows add '& Pause' to the end of your command in the file.

How to create a density plot in matplotlib?

Option 1:

Use pandas dataframe plot (built on top of matplotlib):

import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()

enter image description here

Option 2:

Use distplot of seaborn:

import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)

enter image description here

Converting characters to integers in Java

From the Javadoc for Character#getNumericValue:

If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

The character + does not have a numeric value, so you're getting -1.

Update:

The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

c# datatable insert column at position 0

You can use the following code to add column to Datatable at postion 0:

    DataColumn Col   = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
    Col.SetOrdinal(0);// to put the column in position 0;

iOS Swift - Get the Current Local Time and Date Timestamp

you can even create a function to return different time stamps depending on your necessity:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    } 

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

Stop embedded youtube iframe?

You may want to review through the Youtube JavaScript API Reference docs.

When you embed your video(s) on the page, you will need to pass this parameter:

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:

player.stopVideo()

This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Does HTTP use UDP?

Maybe some change on this topic with QUIC

QUIC (Quick UDP Internet Connections, pronounced quick) is an experimental transport layer network protocol developed by Google and implemented in 2013. QUIC supports a set of multiplexed connections between two endpoints over User Datagram Protocol (UDP), and was designed to provide security protection equivalent to TLS/SSL, along with reduced connection and transport latency, and bandwidth estimation in each direction to avoid congestion. QUIC's main goal is to optimize connection-oriented web applications currently using TCP.

How to execute raw SQL in Flask-SQLAlchemy app

SQL Alchemy session objects have their own execute method:

result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})

All your application queries should be going through a session object, whether they're raw SQL or not. This ensures that the queries are properly managed by a transaction, which allows multiple queries in the same request to be committed or rolled back as a single unit. Going outside the transaction using the engine or the connection puts you at much greater risk of subtle, possibly hard to detect bugs that can leave you with corrupted data. Each request should be associated with only one transaction, and using db.session will ensure this is the case for your application.

Also take note that execute is designed for parameterized queries. Use parameters, like :val in the example, for any inputs to the query to protect yourself from SQL injection attacks. You can provide the value for these parameters by passing a dict as the second argument, where each key is the name of the parameter as it appears in the query. The exact syntax of the parameter itself may be different depending on your database, but all of the major relational databases support them in some form.

Assuming it's a SELECT query, this will return an iterable of RowProxy objects.

You can access individual columns with a variety of techniques:

for r in result:
    print(r[0]) # Access by positional index
    print(r['my_column']) # Access by column name as a string
    r_dict = dict(r.items()) # convert to dict keyed by column names

Personally, I prefer to convert the results into namedtuples:

from collections import namedtuple

Record = namedtuple('Record', result.keys())
records = [Record(*r) for r in result.fetchall()]
for r in records:
    print(r.my_column)
    print(r)

If you're not using the Flask-SQLAlchemy extension, you can still easily use a session:

import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session

engine = sqlalchemy.create_engine('my connection string')
Session = scoped_session(sessionmaker(bind=engine))

s = Session()
result = s.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})

HTML5 Email Validation

Here is the example I use for all of my form email inputs. This example is ASP.NET, but applies to any:

<asp:TextBox runat="server" class="form-control" placeholder="Contact's email" 
    name="contact_email" ID="contact_email" title="Contact's email (format: [email protected])" 
    type="email" TextMode="Email" validate="required:true"
    pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*" >
</asp:TextBox>

HTML5 still validates using the pattern when not required. Haven't found one yet that was a false positive.

This renders as the following HTML:

<input class="form-control" placeholder="Contact's email" 
    name="contact_email" id="contact_email" type="email" 
    title="Contact's email (format: [email protected])" 
    pattern="[a-zA-Z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">

MySQL: is a SELECT statement case sensitive?

You can lowercase the value and the passed parameter :

SELECT * FROM `table` WHERE LOWER(`Value`) = LOWER("IAreSavage")

Another (better) way would be to use the COLLATE operator as said in the documentation

Compare two objects' properties to find differences?

Type.GetProperties will list each of the properties of a given type. Then use PropertyInfo.GetValue to check the values.

How to convert a string of numbers to an array of numbers?

Array.from() for details go to MDN

var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);

b is an array of numbers

git: fatal: I don't handle protocol '??http'

The same issue happened with me when I have just copied the url into the clipboard and then pasted it into the terminal. Rewriting whole the line without copy-past option resolved my issue.

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

how to configuring a xampp web server for different root directory

In case, if anyone prefers a simpler solution, especially on Linux (e.g. Ubuntu), a very easy way out is to create a symbolic link to the intended folder in the htdocs folder. For example, if I want to be able to serve files from a folder called "/home/some/projects/testserver/" and my htdocs is located in "/opt/lampp/htdocs/". Just create a symbolic link like so:

ln -s /home/some/projects/testserver /opt/lampp/htdocs/testserver

The command for symbolic link works like so: ln -s target source where,

target - The existing file/directory you would like to link TO.
source - The file/folder to be created, copying the contents of the target. The LINK itself.

For more help see ln --help Source: Create Symbolic Links in Ubuntu

And that's done. just visit http://localhost/testserver/ In fact, you don't even need to restart your server.

How can I push a specific commit to a remote, and not previous commits?

The simplest way to accomplish this is to use two commands.

First, get the local directory into the state that you want. Then,

$ git push origin +HEAD^:someBranch

removes the last commit from someBranch in the remote only, not local. You can do this a few times in a row, or change +HEAD^ to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use

$ git push origin someBranch

as normal to update the remote.

How do I capture SIGINT in Python?

From Python's documentation:

import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10) # Press Ctrl+c here

Class 'ViewController' has no initializers in swift

if you lost a "!" in your code ,like this code below, you'll also get this error.

import UIKit

class MemeDetailViewController : UIViewController {

    @IBOutlet weak var memeImage: UIImageView!

    var meme:Meme! // lost"!"

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)
        self.memeImage!.image = meme.memedImage
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
    }

}

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

Add padding on view programmatically

You can set padding to your view by pro grammatically throughout below code -

view.setPadding(0,1,20,3);

And, also there are different type of padding available -

Padding

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

These, links will refer Android Developers site. Hope this helps you lot.

How do I get the last four characters from a string in C#?

assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.

Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"

In the above, I need to extract the "273" that I will use in database query

        //find the length of the string            
        int streamLen=StreamSelected.Length;

        //now remove all characters except the last 10 characters
        string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));   

        //extract the 3 characters using substring starting from index 0
        //show Result is a TextBox (txtStreamSubs) with 
        txtStreamSubs.Text = streamLessTen.Substring(0, 3);

Subtract a value from every number in a list in Python?

You can use map() function:

a = list(map(lambda x: x - 13, a))