Programs & Examples On #Optical mark recognition

Optical Mark Recognition or Optical Mark Reading is the capturing of data through an optical device from a predefined format.

Return Result from Select Query in stored procedure to a List

I had the same question, took me ages to find a simple solution.

Using ASP.NET MVC 5 and EF 6:

When you add a stored procedure to your .edmx model, the result of the stored procedure will be delivered via an auto-generated object called yourStoredProcName_result.

This _result object contains the attributes corresponding to the columns in the database that your stored procedure selected.

The _result class can be simply converted to a list:

yourStoredProcName_result.ToList()

how to run the command mvn eclipse:eclipse

I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse which produced the same result.

java : non-static variable cannot be referenced from a static context Error

Java has two kind of Variables

a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.

Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.

b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.

Object Level: They will get initialized when you create a new object ,say by new();

C)
Your Problem : Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.

Now from that you want to call an Object varibale : Where is the object ??

You have to create a Object and then only you can access Object level varibales.

Using find to locate files that match one of multiple patterns

#! /bin/bash
filetypes="*.py *.xml"
for type in $filetypes
do
find Documents -name "$type"
done

simple but works :)

how to take user input in Array using java?

You can do the following:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

How to get an element by its href in jquery?

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

Render Partial View Using jQuery in ASP.NET MVC

@tvanfosson rocks with his answer.

However, I would suggest an improvement within js and a small controller check.

When we use @Url helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html) not the actual element (.replaceWith).

More about at: What's the difference between jQuery's replaceWith() and html()?

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').html(data);
}); 

This is specially useful in trees, where the content can be changed several times.

At the controller we can reuse the action depending on requester:

public ActionResult Details( int id )
{
    var model = GetFooModel();
    if (Request.IsAjaxRequest())
    {
        return PartialView( "UserDetails", model );
    }
    return View(model);
}

"Parse Error : There is a problem parsing the package" while installing Android application

I'm not repeating what is instructed here to input the Key store, password, etc. Try

Build -> Generate Signed APK -> [ Input ] ---Next---> select BOTH

  • V1 (Jar Signature)
  • V2 (Full APK Signature)

I don't know why, but at least it worked in my situation.

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

How to send a “multipart/form-data” POST in Android with Volley

First answer on SO.

I have encountered the same problem and found @alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse() from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:

public class MultipartRequest extends Request<String> {

private MultipartEntity entity = new MultipartEntity();

private static final String FILE_PART_NAME = "image";

private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;

public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
    super(Method.POST, url, errorListener);

    mListener = listener;
    this.file = file;
    this.params = params;
    buildMultipartEntity();
}

private void buildMultipartEntity()
{
    entity.addPart(FILE_PART_NAME, new FileBody(file));
    try
    {
        for ( String key : params.keySet() ) {
            entity.addPart(key, new StringBody(params.get(key)));
        }
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

/**
 * copied from Android StringRequest class
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(String response)
{
    mListener.onResponse(response);
}

And you may use the class as following:

    HashMap<String, String> params = new HashMap<String, String>();

    params.put("type", "Some Param");
    params.put("location", "Some Param");
    params.put("contact",  "Some Param");


    MultipartRequest mr = new MultipartRequest(url, new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
            Log.d("response", response);
        }

    }, new Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley Request Error", error.getLocalizedMessage());
        }

    }, f, params);

    Volley.newRequestQueue(this).add(mr);

SQL Update with row_number()

Simple and easy way to update the cursor

UPDATE Cursor
SET Cursor.CODE = Cursor.New_CODE
FROM (
  SELECT CODE, ROW_NUMBER() OVER (ORDER BY [CODE]) AS New_CODE
  FROM Table Where CODE BETWEEN 1000 AND 1999
  ) Cursor

How to make PDF file downloadable in HTML link?

if you need to limit download rate, use this code !!

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
    // send the current file part to the browser
    print fread($file, round($download_rate * 1024));
    // flush the content to the browser
    flush();
    // sleep one second
    sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}

?>

For more information click here

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will not "grayout" the textbox and will still submit the value on a postback.

How to generate .json file with PHP?

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

copy

Make Vim show ALL white spaces as a character

:set list will show all whitespaces as a character. Everything but a space will look different than its normal state, which means that if you still see a plain old space, it's really a plain old space. :)

Endless loop in C/C++

Everyone seems to like while (true):

https://stackoverflow.com/a/224142/1508519

https://stackoverflow.com/a/1401169/1508519

https://stackoverflow.com/a/1401165/1508519

https://stackoverflow.com/a/1401164/1508519

https://stackoverflow.com/a/1401176/1508519

According to SLaks, they compile identically.

Ben Zotto also says it doesn't matter:

It's not faster. If you really care, compile with assembler output for your platform and look to see. It doesn't matter. This never matters. Write your infinite loops however you like.

In response to user1216838, here's my attempt to reproduce his results.

Here's my machine:

cat /etc/*-release
CentOS release 6.4 (Final)

gcc version:

Target: x86_64-unknown-linux-gnu
Thread model: posix
gcc version 4.8.2 (GCC)

And test files:

// testing.cpp
#include <iostream>

int main() {
    do { break; } while(1);
}

// testing2.cpp
#include <iostream>

int main() {
    while(1) { break; }
}

// testing3.cpp
#include <iostream>

int main() {
    while(true) { break; }
}

The commands:

gcc -S -o test1.asm testing.cpp
gcc -S -o test2.asm testing2.cpp
gcc -S -o test3.asm testing3.cpp

cmp test1.asm test2.asm

The only difference is the first line, aka the filename.

test1.asm test2.asm differ: byte 16, line 1

Output:

        .file   "testing2.cpp"
        .local  _ZStL8__ioinit
        .comm   _ZStL8__ioinit,1,1
        .text
        .globl  main
        .type   main, @function
main:
.LFB969:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        nop
        movl    $0, %eax
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE969:
        .size   main, .-main
        .type   _Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB970:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $16, %rsp
        movl    %edi, -4(%rbp)
        movl    %esi, -8(%rbp)
        cmpl    $1, -4(%rbp)
        jne     .L3
        cmpl    $65535, -8(%rbp)
        jne     .L3
        movl    $_ZStL8__ioinit, %edi
        call    _ZNSt8ios_base4InitC1Ev
        movl    $__dso_handle, %edx
        movl    $_ZStL8__ioinit, %esi
        movl    $_ZNSt8ios_base4InitD1Ev, %edi
        call    __cxa_atexit
.L3:
        leave
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE970:
        .size   _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
        .type   _GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB971:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    $65535, %esi
        movl    $1, %edi
        call    _Z41__static_initialization_and_destruction_0ii
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE971:
        .size   _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
        .section        .ctors,"aw",@progbits
        .align 8
        .quad   _GLOBAL__sub_I_main
        .hidden __dso_handle
        .ident  "GCC: (GNU) 4.8.2"
        .section        .note.GNU-stack,"",@progbits

With -O3, the output is considerably smaller of course, but still no difference.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

File permissions are restrictive on the Postgres db owned by the Mac OS. These permissions are reset after reboot, or restart of Postgres: e.g. serveradmin start postgres.

So, temporarily reset the permissions or ownership:

sudo chmod o+rwx /var/pgsql_socket/.s.PGSQL.5432
sudo chown "webUser"  /var/pgsql_socket/.s.PGSQL.5432

Permissions resetting is not secure, so install a version of the db that you own for a solution.

Find methods calls in Eclipse project

Select mymethod() and press ctrl+alt+h.

To see some detailed Information about any method you can use this by selecting that particular Object or method and right click. you can see the "OpenCallHierarchy" (Ctrl+Alt+H). Like that many tools are there to make your work Easier like "Quick Outline" (Ctrl+O) to view the Datatypes and methods declared in a particular .java file.

To know more about this, refer this eclipse Reference

Detect if a Form Control option button is selected in VBA

If you are using a Form Control, you can get the same property as ActiveX by using OLEFormat.Object property of the Shape Object. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.

Dim opt As OptionButton

With Sheets("Sheet1") ' Try to be always explicit
    Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
    Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With

But then again, you really don't need to know the value.
If you use Form Control, you associate a Macro or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.

For example you have 2 Form Control Option Buttons.

Sub CheckOptions()
    Select Case Application.Caller
    Case "Option Button 1"
    ' Action for option button 1
    Case "Option Button 2"
    ' Action for option button 2
    End Select
End Sub

In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller.
This way, no need to check whether the option button value is true or false.

How to create an Array with AngularJS's ng-model

This should work.

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope) ->
  $scope.users = ['bob', 'sean', 'rocky', 'john']
  $scope.test = ->
    console.log $scope.users

HTML:

<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />

Example plunk here

Checking if a variable is initialized

There's no reasonable way to check whether a value has been initialized.

If you care about whether something has been initialized, instead of trying to check for it, put code into the constructor(s) to ensure that they are always initialized and be done with it.

Windows 8.1 gets Error 720 on connect VPN

Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:

  • Reset TCP/IP to Original Configuration- Using the NetShell utility, type this command (in CommandLine): netsh int ip reset [file_name.txt], [file_name.txt] is the name of the file where the actions taken by NetShell are record, for example netsh hint ip reset fixtcpip.txt.

  • Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.

  • Upgrade the NIC driver – You may download the latest NIC driver and upgrade the driver.

Hope it could help.

Print PDF directly from JavaScript

Download the Print.js from http://printjs.crabbly.com/

$http({
    url: "",
    method: "GET",
    headers: {
        "Content-type": "application/pdf"
    },
    responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
    var pdfFile = new Blob([data], {
        type: "application/pdf"
    });
    var pdfUrl = URL.createObjectURL(pdfFile);
    //window.open(pdfUrl);
    printJS(pdfUrl);
    //var printwWindow = $window.open(pdfUrl);
    //printwWindow.print();
}).error(function (data, status, headers, config) {
    alert("Sorry, something went wrong")
});

How to load an ImageView by URL in Android?

A simple and clean way to do this is to use the open source library Prime.

What is the difference between dynamic and static polymorphism in Java?

In simple terms :

Static polymorphism : Same method name is overloaded with different type or number of parameters in same class (different signature). Targeted method call is resolved at compile time.

Dynamic polymorphism: Same method is overridden with same signature in different classes. Type of object on which method is being invoked is not known at compile time but will be decided at run time.

Generally overloading won't be considered as polymorphism.

From java tutorial page :

Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class

Entity framework self referencing loop detected

I had same problem and found that you can just apply the [JsonIgnore] attribute to the navigation property you don't want to be serialised. It will still serialise both the parent and child entities but just avoids the self referencing loop.

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

Error when deploying an artifact in Nexus

I had the same problem today with the addition "Return code is: 400, ReasonPhrase: Bad Request." which turned out to be the "artifact is already deployed with that version if it is a release" problem from answer above enter link description here

One solution not mentioned yet is to configure Nexus to allow redeployment into a Release repository. Maybe not a best practice, because this is set for a reason, you nevertheless could go to "Access Settings" in your Nexus repositories´ "Configuration"-Tab and set the "Deployment Policy" to "Allow Redeploy".

Regular Expression For Duplicate Words

Regex to Strip 2+ duplicate words (consecutive/non-consecutive words)

Try this regex that can catch 2 or more duplicates words and only leave behind one single word. And the duplicate words need not even be consecutive.

/\b(\w+)\b(?=.*?\b\1\b)/ig

Here, \b is used for Word Boundary, ?= is used for positive lookahead, and \1 is used for back-referencing.

Example Source

Is it safe to use Project Lombok?

Lombok is great, but...

Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.

Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.

I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.

Is there a real solution to debug cordova apps

You can also debug with chrome your html5 apps

I create a .bat to open chrome in debug mode

cd C:\Program Files (x86)\Google\Chrome\Application
chrome.exe "file:///C:\Users\***.html" --allow-file-access-from-files --disable-web-security

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

Why do access tokens expire?

A couple of scenarios might help illustrate the purpose of access and refresh tokens and the engineering trade-offs in designing an oauth2 (or any other auth) system:

Web app scenario

In the web app scenario you have a couple of options:

  1. if you have your own session management, store both the access_token and refresh_token against your session id in session state on your session state service. When a page is requested by the user that requires you to access the resource use the access_token and if the access_token has expired use the refresh_token to get the new one.

Let's imagine that someone manages to hijack your session. The only thing that is possible is to request your pages.

  1. if you don't have session management, put the access_token in a cookie and use that as a session. Then, whenever the user requests pages from your web server send up the access_token. Your app server could refresh the access_token if need be.

Comparing 1 and 2:

In 1, access_token and refresh_token only travel over the wire on the way between the authorzation server (google in your case) and your app server. This would be done on a secure channel. A hacker could hijack the session but they would only be able to interact with your web app. In 2, the hacker could take the access_token away and form their own requests to the resources that the user has granted access to. Even if the hacker gets a hold of the access_token they will only have a short window in which they can access the resources.

Either way the refresh_token and clientid/secret are only known to the server making it impossible from the web browser to obtain long term access.

Let's imagine you are implementing oauth2 and set a long timeout on the access token:

In 1) There's not much difference here between a short and long access token since it's hidden in the app server. In 2) someone could get the access_token in the browser and then use it to directly access the user's resources for a long time.

Mobile scenario

On the mobile, there are a couple of scenarios that I know of:

  1. Store clientid/secret on the device and have the device orchestrate obtaining access to the user's resources.

  2. Use a backend app server to hold the clientid/secret and have it do the orchestration. Use the access_token as a kind of session key and pass it between the client and the app server.

Comparing 1 and 2

In 1) Once you have clientid/secret on the device they aren't secret any more. Anyone can decompile and then start acting as though they are you, with the permission of the user of course. The access_token and refresh_token are also in memory and could be accessed on a compromised device which means someone could act as your app without the user giving their credentials. In this scenario the length of the access_token makes no difference to the hackability since refresh_token is in the same place as access_token. In 2) the clientid/secret nor the refresh token are compromised. Here the length of the access_token expiry determines how long a hacker could access the users resources, should they get hold of it.

Expiry lengths

Here it depends upon what you're securing with your auth system as to how long your access_token expiry should be. If it's something particularly valuable to the user it should be short. Something less valuable, it can be longer.

Some people like google don't expire the refresh_token. Some like stackflow do. The decision on the expiry is a trade-off between user ease and security. The length of the refresh token is related to the user return length, i.e. set the refresh to how often the user returns to your app. If the refresh token doesn't expire the only way they are revoked is with an explicit revoke. Normally, a log on wouldn't revoke.

Hope that rather length post is useful.

seek() function?

When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place.

So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20) to move to where you want to start reading, then continue with reading the file.

Or say you want to read every 10th byte, you could write a loop that does seek(9, 1) (moves 9 bytes forward relative to the current positions), read(1) (reads one byte), repeat.

Disabling Minimize & Maximize On WinForm?

Right Click the form you want to hide them on, choose Controls -> Properties.

In Properties, set

  • Control Box -> False
  • Minimize Box -> False
  • Maximize Box -> False

You'll do this in the designer.

What is the optimal algorithm for the game 2048?

I copy here the content of a post on my blog


The solution I propose is very simple and easy to implement. Although, it has reached the score of 131040. Several benchmarks of the algorithm performances are presented.

Score

Algorithm

Heuristic scoring algorithm

The assumption on which my algorithm is based is rather simple: if you want to achieve higher score, the board must be kept as tidy as possible. In particular, the optimal setup is given by a linear and monotonic decreasing order of the tile values. This intuition will give you also the upper bound for a tile value: s where n is the number of tile on the board.

(There's a possibility to reach the 131072 tile if the 4-tile is randomly generated instead of the 2-tile when needed)

Two possible ways of organizing the board are shown in the following images:

enter image description here

To enforce the ordination of the tiles in a monotonic decreasing order, the score si computed as the sum of the linearized values on the board multiplied by the values of a geometric sequence with common ratio r<1 .

s

s

Several linear path could be evaluated at once, the final score will be the maximum score of any path.

Decision rule

The decision rule implemented is not quite smart, the code in Python is presented here:

@staticmethod
def nextMove(board,recursion_depth=3):
    m,s = AI.nextMoveRecur(board,recursion_depth,recursion_depth)
    return m

@staticmethod
def nextMoveRecur(board,depth,maxDepth,base=0.9):
    bestScore = -1.
    bestMove = 0
    for m in range(1,5):
        if(board.validMove(m)):
            newBoard = copy.deepcopy(board)
            newBoard.move(m,add_tile=True)

            score = AI.evaluate(newBoard)
            if depth != 0:
                my_m,my_s = AI.nextMoveRecur(newBoard,depth-1,maxDepth)
                score += my_s*pow(base,maxDepth-depth+1)

            if(score > bestScore):
                bestMove = m
                bestScore = score
    return (bestMove,bestScore);

An implementation of the minmax or the Expectiminimax will surely improve the algorithm. Obviously a more sophisticated decision rule will slow down the algorithm and it will require some time to be implemented.I will try a minimax implementation in the near future. (stay tuned)

Benchmark

  • T1 - 121 tests - 8 different paths - r=0.125
  • T2 - 122 tests - 8-different paths - r=0.25
  • T3 - 132 tests - 8-different paths - r=0.5
  • T4 - 211 tests - 2-different paths - r=0.125
  • T5 - 274 tests - 2-different paths - r=0.25
  • T6 - 211 tests - 2-different paths - r=0.5

enter image description here enter image description here enter image description here enter image description here

In case of T2, four tests in ten generate the 4096 tile with an average score of s 42000

Code

The code can be found on GiHub at the following link: https://github.com/Nicola17/term2048-AI It is based on term2048 and it's written in Python. I will implement a more efficient version in C++ as soon as possible.

Turn off deprecated errors in PHP 5.3

In file wp-config.php you can find constant WP_DEBUG. Make sure it is set to false.

define('WP_DEBUG', false);

This is for WordPress 3.x.

How to turn off Wifi via ADB?

In Android tests I'm doing so: InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi enable") InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Using C# to read/write Excel files (.xls/.xlsx)

**Reading the Excel File:**

string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();  
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

Excel.Range xlRange = xlWorkSheet.UsedRange;  
int totalRows = xlRange.Rows.Count;  
int totalColumns = xlRange.Columns.Count;  

string firstValue, secondValue;   
for (int rowCount = 1; rowCount <= totalRows; rowCount++)  
{  
    firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);  
    secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);  
    Console.WriteLine(firstValue + "\t" + secondValue);  
}  
xlWorkBook.Close();  
xlApp.Quit(); 


**Writting the Excel File:**

Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;  

Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

xlWorkSheet.Cells[1, 1] = "ID";  
xlWorkSheet.Cells[1, 2] = "Name";  
xlWorkSheet.Cells[2, 1] = "100";  
xlWorkSheet.Cells[2, 2] = "John";  
xlWorkSheet.Cells[3, 1] = "101";  
xlWorkSheet.Cells[3, 2] = "Herry";  

xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,  
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  



xlWorkBook.Close();  
xlApp.Quit();  

C++: constructor initializer for arrays

Unfortunately there is no way to initialize array members till C++0x.

You could use a std::vector and push_back the Foo instances in the constructor body.

You could give Foo a default constructor (might be private and making Baz a friend).

You could use an array object that is copyable (boost or std::tr1) and initialize from a static array:

#include <boost/array.hpp>

struct Baz {

    boost::array<Foo, 3> foo;
    static boost::array<Foo, 3> initFoo;
    Baz() : foo(initFoo)
    {

    }
};

boost::array<Foo, 3> Baz::initFoo = { 4, 5, 6 };

How to get the index of an item in a list in a single step?

How about the List.FindIndex Method:

int index = myList.FindIndex(a => a.Prop == oProp);

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

If the item is not found, it will return -1

How to implement 2D vector array?

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

How to set session attribute in java?

I am try to catch your point.I hope it is helpful.....

if (session.isNew()){
     title = "Welcome to my website";
     session.setAttribute(userIDKey, userID);

Copying PostgreSQL database to another server

pg_dump the_db_name > the_backup.sql

Then copy the backup to your development server, restore with:

psql the_new_dev_db < the_backup.sql

How to subtract days from a plain Date?

If you want it all on one line instead.

5 days from today

//past
var thirtyDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var thirtyDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));

5 days from a specific date

 var pastDate = new Date('2019-12-12T00:00:00');

 //past
 var thirtyDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
 //future
 var thirtyDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));

I wrote a function you can use.

_x000D_
_x000D_
function AddOrSubractDays(startingDate, number, add) {_x000D_
  if (add) {_x000D_
    return new Date(new Date().setDate(startingDate.getDate() + number));_x000D_
  } else {_x000D_
    return new Date(new Date().setDate(startingDate.getDate() - number));_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Today : ' + new Date());_x000D_
console.log('Future : ' + AddOrSubractDays(new Date(), 5, true));_x000D_
console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
_x000D_
_x000D_
_x000D_

numpy get index where value is true

A simple and clean way: use np.argwhere to group the indices by element, rather than dimension as in np.nonzero(a) (i.e., np.argwhere returns a row for each non-zero element).

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
       [6],
       [7],
       [8],
       [9]])

np.argwhere(a) is the same as np.transpose(np.nonzero(a)).

Note: You cannot use a(np.argwhere(a>4)) to get the corresponding values in a. The recommended way is to use a[(a>4).astype(bool)] or a[(a>4) != 0] rather than a[np.nonzero(a>4)] as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)] and a[(a>4) != 0] can be simplified to a[a>4].

Another example:

>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([  5, -15,  -8,  -5,  10])
>>> a > 4
array([ True, False, False, False,  True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10,  -3,   0,  15],
       [-10, -30, -23, -20,  -5],
       [ -3, -23, -16, -13,   2],
       [  0, -20, -13, -10,   5],
       [ 15,  -5,   2,   5,  20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
       [0, 4],
       [3, 4],
       [4, 0],
       [4, 3],
       [4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4

How to upgrade Git to latest version on macOS?

I used the following to upgrade git on mac.

hansi$ brew install git 

hansi$ git --version 
git version 2.19.0


hansi$ brew install git
Warning: git 2.25.1 is already installed, it's just not linked
You can use `brew link git` to link this version.

hansi$ brew link git 
Linking /usr/local/Cellar/git/2.25.1... 
Error: Could not symlink bin/git
Target /usr/local/bin/git
already exists. You may want to remove it:
  rm '/usr/local/bin/git'

To force the link and overwrite all conflicting files:
  brew link --overwrite git

To list all files that would be deleted:
  brew link --overwrite --dry-run git

hansi$ brew link --overwrite git 
Linking /usr/local/Cellar/git/2.25.1... 205 symlinks created


hansi$ git --version
git version 2.25.1

Enabling WiFi on Android Emulator

(Repeating here my answer elsewhere.)

In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.

It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.

In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.

How do I implement JQuery.noConflict() ?

Today i have this issue because i have implemented "bootstrap menu" that uses a jQuery version along with "fancybox image gallery". Of course one plugin works and the other not due to jQuery conflict but i have overcome it as follow:

First i have added the "bootstrap menu" Js in the script footer as the menu is presented allover the website pages:

<!-- Top Menu Javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var jq171 = jQuery.noConflict(true);
</script>

And in the "fancybox" image gallery page as follow:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="fancybox/js/libs/jquery-1.7.1.min.js"><\/script>')</script>

And the good thing is both working like a charm :)

Give it a try :)

How can I install a local gem?

Yup, when you do gem install, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the gem reference, which you may find handy as well:

gem install will install the named gem. It will attempt a local installation (i.e. a .gem file in the current directory), and if that fails, it will attempt to download and install the most recent version of the gem you want.

How to change angular port from 4200 to any other

you can also write this command: ng serve -p 5000

Passing parameter using onclick or a click binding with KnockoutJS

Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click binding using function.bind like this:

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
    Click me
</button>

Error: Uncaught SyntaxError: Unexpected token <

Typically this happens when you are trying to load a non-html resource (e.g the jquery library script file as type text/javascript) and the server, instead of returning the expected JS resource, returns HTML instead - typically a 404 page.

The browser then attempts to parse the resource as JS, but since what was actually returned was an HTML page, the parsing fails with a syntax error, and since an HTML page will typically start with a < character, this is the character that is highlighted in the syntax error exception.

Can I set an unlimited length for maxJsonLength in web.config?

I followed vestigal's answer and got to this solution:

When I needed to post a large json to an action in a controller, I would get the famous "Error during deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\r\nParameter name: input value provider".

What I did is create a new ValueProviderFactory, LargeJsonValueProviderFactory, and set the MaxJsonLength = Int32.MaxValue in the GetDeserializedObject method

public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
    IDictionary<string, object> dictionary = value as IDictionary<string, object>;
    if (dictionary != null)
    {
        foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
            LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
    }
    else
    {
        IList list = value as IList;
        if (list != null)
        {
            for (int index = 0; index < list.Count; ++index)
                LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
        }
        else
            backingStore.Add(prefix, value);
    }
}

private static object GetDeserializedObject(ControllerContext controllerContext)
{
    if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        return (object) null;
    string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
    if (string.IsNullOrEmpty(end))
        return (object) null;

    var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};

    return serializer.DeserializeObject(end);
}

/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
    if (controllerContext == null)
        throw new ArgumentNullException("controllerContext");
    object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
    if (deserializedObject == null)
        return (IValueProvider) null;
    Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
    LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
    return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}

private static string MakeArrayKey(string prefix, int index)
{
    return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}

private static string MakePropertyKey(string prefix, string propertyName)
{
    if (!string.IsNullOrEmpty(prefix))
        return prefix + "." + propertyName;
    return propertyName;
}

private class EntryLimitedDictionary
{
    private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
    private readonly IDictionary<string, object> _innerDictionary;
    private int _itemCount;

    public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
    {
        this._innerDictionary = innerDictionary;
    }

    public void Add(string key, object value)
    {
        if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
            throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
        this._innerDictionary.Add(key, value);
    }

    private static int GetMaximumDepth()
    {
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            int result;
            if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
                return result;
        }
        return 1000;
     }
  }
}

Then, in the Application_Start method from Global.asax.cs, replace the ValueProviderFactory with the new one:

protected void Application_Start()
{
    ...

    //Add LargeJsonValueProviderFactory
    ValueProviderFactory jsonFactory = null;
    foreach (var factory in ValueProviderFactories.Factories)
    {
        if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
        {
            jsonFactory = factory;
            break;
        }
    }

    if (jsonFactory != null)
    {
        ValueProviderFactories.Factories.Remove(jsonFactory);
    }

    var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
    ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}

Finding the id of a parent div using Jquery

To get the id of the parent div:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:

How to check if a service is running via batch file and start it, if it is not running?

@echo off

color 1F


@sc query >%COMPUTERNAME%_START.TXT


find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul

IF ERRORLEVEL 0 EXIT

IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"

HTML5 Canvas Resize (Downscale) Image High Quality?

Maybe man you can try this, which is I always use in my project.In this way you can not only get high quality image ,but any other element on your canvas.

/* 
 * @parame canvas => canvas object
 * @parame rate => the pixel quality
 */
function setCanvasSize(canvas, rate) {
    const scaleRate = rate;
    canvas.width = window.innerWidth * scaleRate;
    canvas.height = window.innerHeight * scaleRate;
    canvas.style.width = window.innerWidth + 'px';
    canvas.style.height = window.innerHeight + 'px';
    canvas.getContext('2d').scale(scaleRate, scaleRate);
}

ImportError: No module named pandas

For me how it worked is, I have two executable versions of python so on pip install it was installing in one version but my executable path version is different so it failed, then I changed the path in sys's environment variable and installed in the executable version of python and it was able to identify the package from site-packages

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

I think this would be best explained by the following picture:

enter image description here

To initialize the above, one would type:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221)   #top left
fig.add_subplot(222)   #top right
fig.add_subplot(223)   #bottom left
fig.add_subplot(224)   #bottom right 
plt.show()

How to get the PID of a process by giving the process name in Mac OS X ?

This solution matches the process name more strictly:

ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'

This solution has the following advantages:

  • it ignores command line arguments like tail -f ~/Dropbox
  • it ignores processes inside a directory like ~/Dropbox/foo.sh
  • it ignores processes with names like ~/DropboxUID.sh

How to create a connection string in asp.net c#

Add this in your web.config file

<connectionStrings>
<add name="itmall" 
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-
02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>

How to specify a local file within html using the file: scheme?

For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc

My answer is one method specifically to windows 10.

So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)

open cmd and type hostname (example result: LAPTOP-G666P000, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)

Press Windows_key + E > right click 'This PC' > press N (It's Map Network drive, NOT add a network location)

If you are right clicking the shortcut on the desktop you need to press N then enter

Fill out U: or G: or Z: or whatever you want Example Address: \\LAPTOP-G666P000\c$\Users\username\

Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button> like in your question


related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.

related2: I have used http://localhost/c$ etc before on some WAMP/apache servers too before, you can use .htaccess for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google

How to remove old and unused Docker images

The following command will delete images older than 48 hours.

$ docker image prune --all --filter until=48h

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

Unable to compile class for JSP

<pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>       
                <version>2.2</version>
            </plugin>
        </plugins>

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

How to iterate (keys, values) in JavaScript?

You can use below script.

var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
    console.log(key,value);
}

outputs
1 a
2 b
c 3

How to printf long long

First of all, %d is for a int

So %1.16lld makes no sense, because %d is an integer

That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

What you want to use is the type double, for calculating pi and then using %f or %1.16f.

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

What's a .sh file?

I know this is an old question and I probably won't help, but many Linux distributions(e.g., ubuntu) have a "Live cd/usb" function, so if you really need to run this script, you could try booting your computer into Linux. Just burn a .iso to a flash drive (here's how http://goo.gl/U1wLYA), start your computer with the drive plugged in, and press the F key for boot menu. If you choose "...USB...", you will boot into the OS you just put on the drive.

OperationalError: database is locked

If you get this error while using manage.py shell, one possible reason is that you have a development server running (manage.py runserver) which is locking the database. Stoping the server while using the shell has always fixed the problem for me.

Clear the form field after successful submission of php form

The POST data which holds the submitted form data is being echoed in the form, eg:

<input name="firstname" type="text" placeholder="First Name" required="required" 
value="<?php echo $_POST['firstname'];?>"  

Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.

header('Location: thanks.php');
exit();

This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get

The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.

package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Layout
            RelativeLayout atulsLayout = new RelativeLayout(this);
            atulsLayout.setBackgroundColor(Color.GREEN);

            //Button
            Button redButton = new Button(this);
            redButton.setText("Log In");
            redButton.setBackgroundColor(Color.RED);

            //Username input
            EditText username =  new EditText(this);

            redButton.setId(1);
            username.setId(2);

            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            //give rules to position widgets
            usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
            usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            usernameDetails.setMargins(0,0,0,50);

            buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
            username.setWidth(px);

            //Add widget to layout(button is now a child of layout)
            atulsLayout.addView(redButton,buttonDetails);
            atulsLayout.addView(username,usernameDetails);

            //Set these activities content/display to this view
            setContentView(atulsLayout);
        }
    }

Php header location redirect not working

Try this, Add @ob_start() function in top of the page,

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    exit();
}

Tomcat is web server or application server?

Tomcat is a web server and a Servlet/JavaServer Pages container. It is often used as an application server for strictly web-based applications but does not include the entire suite of capabilities that a Java EE application server would supply.

Links:

How do I restore a dump file from mysqldump?

You cannot use the Restore menu in MySQL Admin if the backup / dump wasn't created from there. It's worth a shot though. If you choose to "ignore errors" with the checkbox for that, it will say it completed successfully, although it clearly exits with only a fraction of rows imported...this is with a dump, mind you.

What's the difference between 'r+' and 'a+' when open file in python?

One difference is for r+ if the files does not exist, it'll not be created and open fails. But in case of a+ the file will be created if it does not exist.

css overflow - only 1 line of text

I was able to achieve this by using the webkit-line-clamp and the following css:

div {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

Aligning two divs side-by-side

If you wrapped your divs, like this:

<div id="main">
  <div id="sidebar"></div>
  <div id="page-wrap"></div>
</div>

You could use this styling:

#main { 
    width: 800px;
    margin: 0 auto;
}
#sidebar    {
    width: 200px;
    height: 400px;
    background: red;
    float: left;
}

#page-wrap  {
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin-left: 200px;
}

This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px as a unit, not the 600px centered with the 200px on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap has the width of your sidebar as it's left margin to move that far over.

Update based on comments: For this off-centered look, you can do this:

<div id="page-wrap">
  <div id="sidebar"></div>
</div>

With this styling:

#sidebar    {
    position: absolute;
    left: -200px;
    width: 200px;
    height: 400px;
    background: red;    
}

#page-wrap  {
    position: relative;
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin: 0 auto;
}

How to send email via Django?

You need to use smtp as backend in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

If you use backend as console, you will receive output in console

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

And also below settings in addition

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'

If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.

How to include layout inside layout?

Use <include /> tag.

          <include 
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>

Also, read Creating Reusable UI Components and Merging Layouts articles.

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

How to run an awk commands in Windows?

Actually, I do like mark instruction but little differently. I've added C:\Program Files (x86)\GnuWin32\bin\ to the Path variable, and try to run it with type awk using cmd.

Hope it works.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

You are missing the python mysqldb library. Use this command (for Debian/Ubuntu) to install it: sudo apt-get install python-mysqldb

Full-screen iframe with a height of 100%

Only this worked for me (but for "same-domain"):

function MakeIframeFullHeight(iframeElement){
    iframeElement.style.width   = "100%";
    var ifrD = iframeElement.contentDocument || iframeElement.contentWindow.document;
    var mHeight = parseInt( window.getComputedStyle( ifrD.documentElement).height );  // Math.max( ifrD.body.scrollHeight, .. offsetHeight, ....clientHeight,
    var margins = ifrD.body.style.margin + ifrD.body.style.padding + ifrD.documentElement.style.margin + ifrD.documentElement.style.padding;
    if(margins=="") { margins=0;  ifrD.body.style.margin="0px"; }
    (function(){
       var interval = setInterval(function(){
        if(ifrD.readyState  == 'complete' ){
            iframeElement.style.height  = (parseInt(window.getComputedStyle( ifrD.documentElement).height) + margins+1) +"px";
            setTimeout( function(){ clearInterval(interval); }, 1000 );
        } 
       },1000)
    })();
}

you can use either:

MakeIframeFullHeight(document.getElementById("iframe_id"));

or

<iframe .... onload="MakeIframeFullHeight(this);" ....

Remove scrollbar from iframe

Add scrolling="no" attribute to the iframe.

IIS Config Error - This configuration section cannot be used at this path

When I tried these steps I kept getting error:

  1. Search for "Turn windows features on or off"
  2. Check "Internet Information Services"
  3. Check "World Wide Web Services"
  4. Check "Application Development Features"
  5. Enable all items under this

Then i looked at event viewer and saw this error:Unable to install counter strings because the SYSTEM\CurrentControlSet\Services\ASP.NET_64\Performance key could not be opened or accessed. The first DWORD in the Data section contains the Win32 error code.

To fix the issue i manually created following entry in registry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ASP.NET_64\Performance

and followed these steps:

  1. Search for "Turn windows features on or off"
  2. Check "Internet Information Services"
  3. Check "World Wide Web Services"
  4. Check "Application Development Features"
  5. Enable all items under this

If list index exists, do X

If you want to iterate the inserted actors data:

for i in range(n):
    if len(nams[i]) > 3:
        do_something
    if len(nams[i]) > 4:
        do_something_else

Program to find largest and second largest number in array

Try this:

public static void main(String[] args) throws IndexOutOfBoundsException {

    int[] a = { 12, 19, 10, 3, 9, 8 };
    int n = a.length;
    int larg = a[0];
    int larg2 = a[0];

    for (int i = 0; i < n; i++) {
        if (larg < a[i]) {
            larg = a[i];

        }
        if (a[i] > larg2 && larg < a[i]) {
            larg2 = a[i];

        }
    }

    System.out.println("largest " + larg);
    System.out.println("largest2 " + larg2);

}

How do I clear all variables in the middle of a Python script?

Isn't the easiest way to create a class contining all the needed variables? Then you have one object with all curretn variables, and if you need you can overwrite this variable?

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Checking if an object is null in C#

With c#9 (2020) you can now check a parameter is null with this code:

if (name is null) { }

if (name is not null) { }

You can have more information here

How to pass extra variables in URL with WordPress

to add parameter to post urls (to perma-links), i use this:

add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post ) 
{
    return add_query_arg('my_pid',$post->ID, $url);
}

output:

http://yoursite.com/pagename?my_pid=12345678

How to implement a SQL like 'LIKE' operator in java?

http://josql.sourceforge.net/ has what you need. Look for org.josql.expressions.LikeExpression.

In angular $http service, How can I catch the "status" of error?

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

What is the difference between UTF-8 and Unicode?

The existing answers already explain a lot of details, but here's a very short answer with the most direct explanation and example.

Unicode is the standard that maps characters to codepoints.
Each character has a unique codepoint (identification number), which is a number like 9731.

UTF-8 is an the encoding of the codepoints.
In order to store all characters on disk (in a file), UTF-8 splits characters into up to 4 octets (8-bit sequences) - bytes. UTF-8 is one of several encodings (methods of representing data). For example, in Unicode, the (decimal) codepoint 9731 represents a snowman (?), which consists of 3 bytes in UTF-8: E2 98 83

Here's a sorted list with some random examples.

Replace given value in vector

Another simpler option is to do:

 > x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
 > x[x==1] <- 0
 > x
 [1] 0 0 2 4 5 2 0 3 2

What is “assert” in JavaScript?

It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):

http://chaijs.com/guide/styles/#assert

Why does 'git commit' not save my changes?

if you have more files in my case i have 7000 image files when i try to add them from project's route folder it hasn't added them but when i go to the image folder everything is ok. Go through the target folder and command like abows

git add .
git commit -am "image uploading"
git push origin master

git push origin master Enumerating objects: 6574, done. Counting objects: 100% (6574/6574), done. Delta compression using up to 4 threads Compressing objects: 100% (6347/6347), done. Writing objects: 28% (1850/6569), 142.17 MiB | 414.00 KiB/s

How to recover a dropped stash in Git?

To get the list of stashes that are still in your repository, but not reachable any more:

git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP

If you gave a title to your stash, replace "WIP" in -grep=WIP at the end of the command with a part of your message, e.g. -grep=Tesselation.

The command is grepping for "WIP" because the default commit message for a stash is in the form WIP on mybranch: [previous-commit-hash] Message of the previous commit.

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

What is the "hasClass" function with plain JavaScript?

I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'

This method is great because does not require polyfills and if you use them for classList it's much better in terms of performance. At least for me.

Update: I made a tiny polyfill that's an all round solution I use now:

function hasClass(element,testClass){
  if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better

//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
  return false;
}

For the other class manipulation, see the complete file here.

How do I copy a folder from remote to local using scp?

I don't know why but I was had to use local folder before source server directive . to make it work

scp -r . [email protected]:/usr/share/nginx/www/example.org/

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

Java, How to implement a Shift Cipher (Caesar Cipher)

The warning is due to you attempting to add an integer (int shift = 3) to a character value. You can change the data type to char if you want to avoid that.

A char is 16 bits, an int is 32.

char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;

As an aside, you can simplify the following:

char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'}; 

To:

char[] message = "onceuponatime".toCharArray();

Message 'src refspec master does not match any' when pushing commits in Git

  1. Try git show-ref to see what refs you have. Is there a refs/heads/master?

Due to the recent "Replacing master with main in GitHub" action, you may notice that there is a refs/heads/main. As a result, the following command may change from git push origin HEAD:master to git push origin HEAD:main

  1. You can try git push origin HEAD:master as a more local-reference-independent solution. This explicitly states that you want to push the local ref HEAD to the remote ref master (see the git-push refspec documentation).

displayname attribute vs display attribute

Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)

//using statements
using System;
using System.ComponentModel.DataAnnotations;  //needed for Display annotation
using System.ComponentModel;  //needed for DisplayName annotation

public class Whatever
{
    //Property
    [Display(Name ="Release Date")]
    public DateTime ReleaseDate { get; set; }
}


//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)

How to increase timeout for a single test case in mocha

For test navegation on Express:

const request = require('supertest');
const server = require('../bin/www');

describe('navegation', () => {
    it('login page', function(done) {
        this.timeout(4000);
        const timeOut = setTimeout(done, 3500);

        request(server)
            .get('/login')
            .expect(200)
            .then(res => {
                res.text.should.include('Login');
                clearTimeout(timeOut);
                done();
            })
            .catch(err => {
                console.log(this.test.fullTitle(), err);
                clearTimeout(timeOut);
                done(err);
            });
    });
});

In the example the test time is 4000 (4s).

Note: setTimeout(done, 3500) is minor for than done is called within the time of the test but clearTimeout(timeOut) it avoid than used all these time.

Git and nasty "error: cannot lock existing info/refs fatal"

Check that you (git process actually) have access to file .git/info/refs and this file isn't locked by another process.

PowerShell: how to grep command output?

For a more flexible and lazy solution, you could match all properties of the objects. Most of the time, this should get you the behavior you want, and you can always be more specific when it doesn't. Here's a grep function that works based on this principle:

Function Select-ObjectPropertyValues {
    param(
    [Parameter(Mandatory=$true,Position=0)]
    [String]
    $Pattern,
    [Parameter(ValueFromPipeline)]
    $input)

    $input | Where-Object {($_.PSObject.Properties | Where-Object {$_.Value -match $Pattern} | Measure-Object).count -gt 0} | Write-Output
}

Receive JSON POST with PHP

It is worth pointing out that if you use json_decode(file_get_contents("php://input")) (as others have mentioned), this will fail if the string is not valid JSON.

This can be simply resolved by first checking if the JSON is valid. i.e.

function isValidJSON($str) {
   json_decode($str);
   return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");

if (strlen($json_params) > 0 && isValidJSON($json_params))
  $decoded_params = json_decode($json_params);

Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);

How to download the latest artifact from Artifactory repository?

For me the easiest way was to read the last versions of the project with a combination of curl, grep, sort and tail.

My format: service-(version: 1.9.23)-(buildnumber)156.tar.gz

versionToDownload=$(curl -u$user:$password 'https://$artifactory/artifactory/$project/' | grep -o 'service-[^"]*.tar.gz' | sort | tail -1)

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

installation app blocked by play protect

I found the solution: Go to the link below and submit your application.

Play Protect Appeals Submission Form

After a few days, the problem will be fixed

Can jQuery read/write cookies to a browser?

The default JavaScript "API" for setting a cookie is as easy as:

document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'

Use the jQuery cookie plugin like:

$.cookie('mycookie', 'valueOfCookie')

What does git push -u mean?

When you push a new branch the first time use: >git push -u origin

After that, you can just type a shorter command: >git push

The first-time -u option created a persistent upstream tracking branch with your local branch.

Better way to find index of item in ArrayList?

The best way to find the position of item in the list is by using Collections interface,

Eg,

List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);

Output : 2

How to increase buffer size in Oracle SQL Developer to view all records?

after you retrieve the first 50 rows in the query windows, simply click a column to get focus on the query window, then once selected do ctrl + pagedown

This will load the full result set (all rows)

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

JUnit 5: How to assert an exception is thrown?

They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:

@Test
public void wrongInput() {
    Throwable exception = assertThrows(InvalidArgumentException.class,
            ()->{objectName.yourMethod("WRONG");} );
}

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Hudson can be configured to ignore changes to certain paths and files so that it does not prompt a new build.

On the job configuration page, under Source Code Management, click the Advanced button. In the Excluded Regions box you enter one or more regular expression to match exclusions.

For example to ignore changes to the version.properties file you can use:

/MyProject/trunk/version.properties

This will work for languages other than C# and allows you to store your version info within subversion.

java.lang.IllegalArgumentException: contains a path separator

You cannot use path with directory separators directly, but you will have to make a file object for every directory.

NOTE: This code makes directories, yours may not need that...

File file= context.getFilesDir();
file.mkdir();

String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
    file=new File(file,array[t]);
    file.mkdir();
}

File f=new File(file,array[array.length-1]);

RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);

How to access parameters in a Parameterized Build?

As per Pipeline plugin tutorial:

If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.

So try to access the variable directly, e.g.:

node()
{
     print "DEBUG: parameter foo = " + foo
     print "DEBUG: parameter bar = ${bar}"
}

Writing data into CSV file in C#

You can use AppendAllText instead:

File.AppendAllText(filePath, csv);

As the documentation of WriteAllText says:

If the target file already exists, it is overwritten

Also, note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:

string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);

Convert XmlDocument to String

As an extension method:

public static class Extensions
{
    public static string AsString(this XmlDocument xmlDoc)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter tx = new XmlTextWriter(sw))
            {
                xmlDoc.WriteTo(tx);
                string strXmlText = sw.ToString();
                return strXmlText;
            }
        }
    }
}

Now to use simply:

yourXmlDoc.AsString()

How to remove a package in sublime text 2

There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...

Ctrl+Shift+P

Package Control: Remove Package

If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.

First navigate to

C:\users\[Name]\AppData\Roaming\Sublime Text [version]\

There will be 4 directories:

  1. Installed Packages (Holds the Package Control config file, ignore)
  2. Packages (Holds Package source)
  3. Pristine Packages (Holds the versioning info, ignore)
  4. Settings (Sublime Setting Info, ignore)

First open ..\Packages folder and locate the folder named the same as your package; Delete it.

Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user

Third, locate the line where the package name you want to "uninstall"

{
    "installed_packages":
    [
        "Alignment",
        "All Autocomplete",
        "AngularJS",
        "AutoFileName",
        "BracketHighlighter",
        "Browser Support",
        "Case Conversion",
        "ColorPicker",
        "Emmet",
        "FileDiffs",
        "Format SQL",
        "Git",
        "Github Tools",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLBeautify",
        "jQuery",
        "JsFormat",
        "JSHint",
        "JsMinifier",
        "LiveReload",
        "LoremIpsum",
        "LoremPixel",
        "Oracle PL SQL",
        "Package Control",
        "Placehold.it Image Tag Generator",
        "Placeholders",
        "Prefixr",
        "Search Stack Overflow",
        "SublimeAStyleFormatter",
        "SublimeCodeIntel",
        "Tag",
        "Theme - Centurion",
        "TortoiseSVN",
        "Zen Tabs"
    ]
}

NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.

Thus concludes the easiest way to remove or Install a Sublime Text Package.

Html code as IFRAME source rather than a URL

use html5's new attribute srcdoc (srcdoc-polyfill) Docs

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Browser support - Tested in the following browsers:

Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I had to modify some bits for this to work for me. I am using Bootstrap 3 and jQuery 2

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "!";
if (hash) {
    hash = hash.replace(prefix,'');
    var hashPieces = hash.split('?');
    activeTab = $('[role="tablist"] a[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
}

// Change hash for page-reload
$('[role="tablist"] a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

How to convert all tables in database to one collation?

Better option to change also collation of varchar columns inside table also

SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') AS    mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "myschema"
AND TABLE_TYPE="BASE TABLE"

Additionnaly if you have data with forein key on non utf8 column before launch the bunch script use

SET foreign_key_checks = 0;

It means global SQL will be for mySQL :

SET foreign_key_checks = 0;
ALTER TABLE `table1` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `table2` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `tableXXX` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
SET foreign_key_checks = 1;

But take care if according mysql documentation http://dev.mysql.com/doc/refman/5.1/en/charset-column.html,

If you use ALTER TABLE to convert a column from one character set to another, MySQL attempts to map the data values, but if the character sets are incompatible, there may be data loss. "

EDIT: Specially with column type enum, it just crash completly enums set (even if there is no special caracters) https://bugs.mysql.com/bug.php?id=26731

How can I submit a POST form using the <a href="..."> tag?

You need to use javascript for this.

<form id="form1" action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

How to make links in a TextView clickable?

As the databinding is out I'd like to share my solution for databinding TextViews supporting html tags with clickable links.

To avoid retrieving every textview and giving them html support using From.html we extend the TextView and put the logic in setText()

public class HtmlTextView extends TextView {

    public HtmlTextView(Context context) {
        super(context);
    }

    public HtmlTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(Html.fromHtml(text.toString()), type);
        this.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

I've made a gist which also shows example entity and view for using this.

How to compare dates in datetime fields in Postgresql?

Use Date convert to compare with date: Try This:

select * from table 
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

virtualenvwrapper and Python 3

I find that running

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3

and

export VIRTUALENVWRAPPER_VIRTUALENV=/usr/bin/virtualenv-3.4

in the command line on Ubuntu forces mkvirtualenv to use python3 and virtualenv-3.4. One still has to do

mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

to create the environment. This is assuming that you have python3 in /usr/bin/python3 and virtualenv-3.4 in /usr/local/bin/virtualenv-3.4.

Align div right in Bootstrap 3

Do you mean something like this:

HTML

<div class="row">
  <div class="container">

    <div class="col-md-4">
      left content
    </div>

    <div class="col-md-4 col-md-offset-4">

      <div class="yellow-background">
        text
        <div class="pull-right">right content</div>  
      </div>

    </div>
  </div>
</div>

CSS

.yellow-background {
  background: blue;
}

.pull-right {
  background: yellow;
}

A full example can be found on Codepen.

What is the difference between parseInt() and Number()?

parseInt converts to a integer number, that is, it strips decimals. Number does not convert to integer.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

I too had this issue in PyCharm. This issue is because you don't have tkinter module in your machine.

To install follow the steps given below (select your appropriate os)

For ubuntu users

 sudo apt-get install python-tk

or

 sudo apt-get install python3-tk

For Centos users

 sudo yum install python-tkinter

or

 sudo yum install python3-tkinter

For Windows, use pip to install tk

After installing tkinter restart your Pycharm and run your code, it will work

Java 6 Unsupported major.minor version 51.0

According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.

How can I initialize an array without knowing it size?

Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)

 static int isLeft(ArrayList<String> left, ArrayList<String> right)

    {
        int f = 0;
        for (int i = 0; i < left.size(); i++) {
            for (int j = 0; j < right.size(); j++)

            {
                if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
                    System.out.println("Grammar is left recursive");
                    f = 1;
                }

            }
        }
        return f;

    }

    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<String> left = new ArrayList<String>();
        ArrayList<String> right = new ArrayList<String>();


        Scanner sc = new Scanner(System.in);
        System.out.println("enter no of prod");
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println("enter left prod");
            String leftText = sc.next();
            left.add(leftText);
            System.out.println("enter right prod");
            String rightText = sc.next();
            right.add(rightText);
        }

        System.out.println("the productions are");
        for (int i = 0; i < n; i++) {
            System.out.println(left.get(i) + "->" + right.get(i));
        }
        int flag;
        flag = isLeft(left, right);
        if (flag == 1) {
            System.out.println("Removing left recursion");
        } else {
            System.out.println("No left recursion");
        }

    }

Vertical align in bootstrap table

Based on what you have provided your CSS selector is not specific enough to override the CSS rules defined by Bootstrap.

Try this:

.table > tbody > tr > td {
     vertical-align: middle;
}

In Boostrap 4, this can be achieved with the .align-middle Vertical Alignment utility class.

<td class="align-middle">Text</td>

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

For Swift I've created a global function, nothing special, using the dispatch_after method. I like this more as it's readable and easy to use:

func performBlock(block:() -> Void, afterDelay delay:NSTimeInterval){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
}

Which you can use as followed:

performBlock({ () -> Void in
    // Perform actions
}, afterDelay: 0.3)

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You can also use Url.Action for the path instead like so:

$.ajax({
        url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",                
        type: "GET",           
        success: function (partialViewResult) {            
            $("#refTable").html(partialViewResult);
        }
    });

What's the bad magic number error?

I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Differences between Ant and Maven

Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

"Stack overflow in line 0" on Internet Explorer

Aha!

I had an OnError() event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...

For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

How do I remove trailing whitespace using a regular expression?

Try just removing trailing spaces and tabs:

[ \t]+$

Removing all non-numeric characters from string in Python

Fastest approach, if you need to perform more than just one or two such removal operations (or even just one, but on a very long string!-), is to rely on the translate method of strings, even though it does need some prep:

>>> import string
>>> allchars = ''.join(chr(i) for i in xrange(256))
>>> identity = string.maketrans('', '')
>>> nondigits = allchars.translate(identity, string.digits)
>>> s = 'abc123def456'
>>> s.translate(identity, nondigits)
'123456'

The translate method is different, and maybe a tad simpler simpler to use, on Unicode strings than it is on byte strings, btw:

>>> unondig = dict.fromkeys(xrange(65536))
>>> for x in string.digits: del unondig[ord(x)]
... 
>>> s = u'abc123def456'
>>> s.translate(unondig)
u'123456'

You might want to use a mapping class rather than an actual dict, especially if your Unicode string may potentially contain characters with very high ord values (that would make the dict excessively large;-). For example:

>>> class keeponly(object):
...   def __init__(self, keep): 
...     self.keep = set(ord(c) for c in keep)
...   def __getitem__(self, key):
...     if key in self.keep:
...       return key
...     return None
... 
>>> s.translate(keeponly(string.digits))
u'123456'
>>> 

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

Program does not contain a static 'Main' method suitable for an entry point

Just in case someone is still getting the same error, even with all the help above: I had this problem, I tried all the solutions given here, and I just found out that my problem was actually another error from my error list (which was about a missing image set to be my splash screen. i just changed its path to the right one and then all started to work)

Make footer stick to bottom of page correctly

the easiest hack is to set a min-height to your page container at 400px assuming your footer come at the end. you dont even have to put css for the footer or just a width:100% assuming your footer is direct child of your <body>

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;
}

Here you are using a div with id body, as:

<body>
  <div id="body>
    all the text would go here!
  </div>
</body>

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;
}

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

How to remove new line characters from a string?

just do that

s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);

How to convert TimeStamp to Date in Java?

I feel obliged to respond since other answers seem to be time zone agnostic which a real world application cannot afford to be. To make timestamp-to-date conversion correct when the timestamp and the JVM are using different time zones you can use Joda Time's LocalDateTime (or LocalDateTime in Java8) like this:

Timestamp timestamp = resultSet.getTimestamp("time_column");
LocalDateTime localDateTime = new LocalDateTime(timestamp);
Date trueDate = localDateTime.toDate(DateTimeZone.UTC.toTimeZone());

The example below assumes that the timestamp is UTC (as is usually the case with databases). In case your timestamps are in different timezone, change the timezone parameter of the toDatestatement.

How to set max and min value for Y axis

Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):

statsData.push(0);

[...]

var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        datasets: [{
            data: statsData,
[...]

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

Android Recyclerview GridLayoutManager column spacing

Here is my modification of SpacesItemDecoration which can take numOfColums and space equally on top, bottom, left and right.

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    private int mNumCol;

    public SpacesItemDecoration(int space, int numCol) {
        this.space = space;
        this.mNumCol=numCol;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {

        //outRect.right = space;
        outRect.bottom = space;
        //outRect.left = space;

        //Log.d("ttt", "item position" + parent.getChildLayoutPosition(view));
        int position=parent.getChildLayoutPosition(view);

        if(mNumCol<=2) {
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) != 0) {
                    outRect.left = space / 2;
                    outRect.right = space;
                } else {
                    outRect.left = space;
                    outRect.right = space / 2;
                }
            }
        }else{
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) == 0) {
                    outRect.left = space;
                    outRect.right = space/2;
                } else if((position % mNumCol) == (mNumCol-1)){
                    outRect.left = space/2;
                    outRect.right = space;
                }else{
                    outRect.left=space/2;
                    outRect.right=space/2;
                }
            }

        }

        if(position<mNumCol){
            outRect.top=space;
        }else{
            outRect.top=0;
        }
        // Add top margin only for the first item to avoid double space between items
        /*
        if (parent.getChildLayoutPosition(view) == 0 ) {

        } else {
            outRect.top = 0;
        }*/
    }
}

and use below code on your logic.

recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels, numCol));

How to fix "Attempted relative import in non-package" even with __init__.py

This approach worked for me and is less cluttered than some solutions:

try:
  from ..components.core import GameLoopEvents
except ValueError:
  from components.core import GameLoopEvents

The parent directory is in my PYTHONPATH, and there are __init__.py files in the parent directory and this directory.

The above always worked in python 2, but python 3 sometimes hit an ImportError or ModuleNotFoundError (the latter is new in python 3.6 and a subclass of ImportError), so the following tweak works for me in both python 2 and 3:

try:
  from ..components.core import GameLoopEvents
except ( ValueError, ImportError):
  from components.core import GameLoopEvents

Datatables: Cannot read property 'mData' of undefined

in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.

_x000D_
_x000D_
<table id="tabel_data">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>heading 1</th>_x000D_
            <th>heading 2</th>_x000D_
            <th>heading 3</th>_x000D_
            <th>heading 4</th>_x000D_
            <th>heading 5</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>data-1</td>_x000D_
            <td>data-2</td>_x000D_
            <td>data-3</td>_x000D_
            <td>data-4</td>_x000D_
            <td>data-5</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>_x000D_
_x000D_
<table id="tabel_data">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>heading 1</th>_x000D_
            <th>heading 2</th>_x000D_
            <th>heading 3</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>data-1</td>_x000D_
            <td>data-2</td>_x000D_
            <td>data-3</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

I got this error until I realized that I hadn't intialized a Git repository in that folder, on a mounted vagrant machine.

So I typed git init and then git worked.

Get source jar files attached to Eclipse for Maven-managed dependencies

There is also a similiar question that answers this and includes example pom settings.

What exactly are DLL files, and how do they work?

What is a DLL?

DLL files are binary files that can contain executable code and resources like images, etc. Unlike applications, these cannot be directly executed, but an application will load them as and when they are required (or all at once during startup).

Are they important?

Most applications will load the DLL files they require at startup. If any of these are not found the system will not be able to start the process at all.

DLL files might require other DLL files

In the same way that an application requires a DLL file, a DLL file might be dependent on other DLL files itself. If one of these DLL files in the chain of dependency is not found, the application will not load. This is debugged easily using any dependency walker tools, like Dependency Walker.

There are so many of them in the system folders

Most of the system functionality is exposed to a user program in the form of DLL files as they are a standard form of sharing code / resources. Each functionality is kept separately in different DLL files so that only the required DLL files will be loaded and thus reduce the memory constraints on the system.

Installed applications also use DLL files

DLL files also becomes a form of separating functionalities physically as explained above. Good applications also try to not load the DLL files until they are absolutely required, which reduces the memory requirements. This too causes applications to ship with a lot of DLL files.

DLL Hell

However, at times system upgrades often breaks other programs when there is a version mismatch between the shared DLL files and the program that requires them. System checkpoints and DLL cache, etc. have been the initiatives from M$ to solve this problem. The .NET platform might not face this issue at all.

How do we know what's inside a DLL file?

You have to use an external tool like DUMPBIN or Dependency Walker which will not only show what publicly visible functions (known as exports) are contained inside the DLL files and also what other DLL files it requires and which exports from those DLL files this DLL file is dependent upon.

How do we create / use them?

Refer the programming documentation from your vendor. For C++, refer to LoadLibrary in MSDN.

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

Get Filename Without Extension in Python

No need for regex. os.path.splitext is your friend:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')

How do I check if a given string is a legal/valid file name under Windows?

From MSDN's "Naming a File or Directory," here are the general conventions for what a legal file name is under Windows:

You may use any character in the current code page (Unicode/ANSI above 127), except:

  • < > : " / \ | ? *
  • Characters whose integer representations are 0-31 (less than ASCII space)
  • Any other character that the target file system does not allow (say, trailing periods or spaces)
  • Any of the DOS names: CON, PRN, AUX, NUL, COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 (and avoid AUX.txt, etc)
  • The file name is all periods

Some optional things to check:

  • File paths (including the file name) may not have more than 260 characters (that don't use the \?\ prefix)
  • Unicode file paths (including the file name) with more than 32,000 characters when using \?\ (note that prefix may expand directory components and cause it to overflow the 32,000 limit)

What's the simplest way to list conflicted files in Git?

My 2 cents here (even when there are a lot of cool/working responses)

I created this alias in my .gitconfig

[alias]
 ...
 conflicts = !git diff --name-only --diff-filter=U | grep -oE '[^/ ]+$'

which is going to show me just the names of the files with conflicts... not their whole path :)

How to Remove the last char of String in C#?

var input = "12342";
var output = input.Substring(0, input.Length - 1); 

or

var output = input.Remove(input.Length - 1);

How to list active / open connections in Oracle?

select s.sid as "Sid", s.serial# as "Serial#", nvl(s.username, ' ') as "Username", s.machine as "Machine", s.schemaname as "Schema name", s.logon_time as "Login time", s.program as "Program", s.osuser as "Os user", s.status as "Status", nvl(s.process, ' ') as "OS Process id"
from v$session s
where nvl(s.username, 'a') not like 'a' and status like 'ACTIVE'
order by 1,2

This query attempts to filter out all background processes.

How to make tesseract to recognize only numbers, when they are mixed with letters?

You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/

Cookies vs. sessions

Actually, session and cookies are not always separate things. Often, but not always, session uses cookies.

There are some good answers to your question in these other questions here. Since your question is specifically about saving the user's IDU (or ID), I don't think it is quite a duplicate of those other questions, but their answers should help you.

cookies vs session

Cache VS Session VS cookies?

What is the difference between a Session and a Cookie?

What is Scala's yield?

The keyword yield in Scala is simply syntactic sugar which can be easily replaced by a map, as Daniel Sobral already explained in detail.

On the other hand, yield is absolutely misleading if you are looking for generators (or continuations) similar to those in Python. See this SO thread for more information: What is the preferred way to implement 'yield' in Scala?

How to clone all remote branches in Git?

#!/bin/bash
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
   git branch --track ${branch#remotes/origin/} $branch
done

These code will pull all remote branches code to local repo.

Java Error opening registry key

On Windows 10 I had just installed the JDK, and got these errors when checking the version. I had to delete all executable files starting with java (i.e. java.exe, javaw.exe and javaws.exe) from C:\ProgramData\Oracle\Java\javapath. And then, once deleted, re-run the JDK installer, restart my terminal program and java -v works.

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

Add a prefix string to beginning of each line

If you need to prepend a text at the beginning of each line that has a certain string, try following. In the following example, I am adding # at the beginning of each line that has the word "rock" in it.

sed -i -e 's/^.*rock.*/#&/' file_name

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

Something went wrong with your GCC installation. Try reinstalling the it like this:

sudo apt-get install --reinstall g++-5

In Ubuntu the g++ is a dependency package that installs the default version of g++ for your OS version. So simply removing and installing the package again won't work, cause it will install the default version. That's why you need to reinstall.

Note: You can replace the g++-5 with your desired g++ version. To find your current g++ version run this:

g++ --version

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

Extend contigency table with proportions (percentages)

I made this for when doing aggregate functions and similar

per.fun <- function(x) {
    if(length(x)>1){
        denom <- length(x);
        num <- sum(x);
        percentage <- num/denom;
        percentage*100
        }
        else NA
    }

Loading PictureBox Image from resource file with path (Part 3)

Ok...so first you need to import the image into your project.

1) Select the PictureBox in the Form Design View

2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)

3) Click on "Choose image..."

4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)

5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)

6) Click on "OK"

Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:

pictureBox1.Image = Properties.Resources.MyImage;

Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

How to style the menu items on an Android action bar

I think the code below

<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item> 

must be in MyAppTheme section.

Reading NFC Tags with iPhone 6 / iOS 8

The only information currently available is that Apple Pay will be available in ios8, but that doesn't shed any light on whether RFID tags or rather NFC tags specifically will be able to be detected/read.

IMO it would be a shortsighted move not to allow that possibility, but really the money is in Apple Pay, not necessarily in allowing developers access to those features - we've seen it before with tethering, Bluetooth SPP, and diminished access to certain functions.

...but then again, it's been about 5 hours since the first announcement.

equals vs Arrays.equals in Java

import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {
   // initializing three object arrays
   Object[] array1 = new Object[] { 1, 123 };
   Object[] array2 = new Object[] { 1, 123, 22, 4 };
   Object[] array3 = new Object[] { 1, 123 };

   // comparing array1 and array2
   boolean retval=Arrays.equals(array1, array2);
   System.out.println("array1 and array2 equal: " + retval);
   System.out.println("array1 and array2 equal: " + array1.equals(array2));

   // comparing array1 and array3
   boolean retval2=Arrays.equals(array1, array3);
   System.out.println("array1 and array3 equal: " + retval2);
   System.out.println("array1 and array3 equal: " + array1.equals(array3));

   }
}

Here is the output:

    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false

Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted need to close the "System Integrity Protection".

first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable, now you can reboot and try again.

Program "make" not found in PATH

In MinGW, I had to install the following things:

Basic Setup -> mingw32-base  
Basic Setup -> mingw32-gcc-g++  
Basic Setup -> msys-base 

And in Eclipse, go to

Windows -> Preferences -> C/C++ -> Build -> Environment

And set the following environment variables (with "Append variables to native environment" option set):

MINGW_HOME   C:\MinGW
PATH   C:\MinGW\bin;C:\MinGW\msys\1.0\bin

Click "Apply" and then "OK".

This worked for me, as far as I can tell.

Is it possible to break a long line to multiple lines in Python?

As far as I know, it can be done. Python has implicit line continuation (inside parentheses, brackets, and strings) for triple-quoted strings ("""like this""")and the indentation of continuation lines is not important. For more info, you may want to read this article on lexical analysis, from python.org.

How do I get PHP errors to display?

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().