Programs & Examples On #Forward reference

How to do what head, tail, more, less, sed do in Powershell?

$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
    #gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
    #gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"}             # cat -n
    gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script 
$ErrorActionPreference = $Push_Pop #Suppresses errors

You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Upload files from Java client to a HTTP server

It could depend on your framework. (for each of them could exist an easier solution).

But to answer your question: there are a lot of external libraries for this functionality. Look here how to use apache commons fileupload.

Default SecurityProtocol in .NET 4.5

The registry change mechanism worked for me after a struggle. Actually my application was running as 32bit. So I had to change the value under path.

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319

The value type needs to be DWORD and value above 0 .Better use 1.Registry settings to get .Net 4.0 app use TLS 1.2 provided .Net 4.5 is installed in the machine.

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

Inserting image into IPython notebook markdown

You can find your current working directory by 'pwd' command in jupyter notebook without quotes.

Is there a better jQuery solution to this.form.submit();?

In JQuery you can call

$("form:first").trigger("submit")

Don't know if that is much better. I think form.submit(); is pretty universal.

How do you count the lines of code in a Visual Studio solution?

Obviously tools are easier, but I feel cool doing this in powershell:)

This script finds all the .csproj references in the .sln file, and then within each csproj file it locates files included for compilation. For each file that is included for compilation it creates an object with properties: Solution, Project, File, Lines. It stores all these objects in a list, and then groups and projects the data as needed.

#path to the solution file e.g. "D:\Code\Test.sln"
$slnFile = "D:\Code\Test.sln"


#results
$results = @()

#iterate through .csproj references in solution file
foreach($projLines in get-item $slnFile | Get-Content | Select-String '".*csproj')
{
    $projFile = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($slnFile), [regex]::Match($projLines,'[^"]*csproj').Value)
    $projFolder = [System.IO.Path]::GetDirectoryName($projFile)

    #from csproj file: get lines for files to compile <Compile Include="..."/>
    $includeLines = get-item $projFile | Get-Content | Select-String '<Compile Include'


    #count of all files lines in project
    $linesInProject = 0;
    foreach($fileLine in $includeLines)
    {
        $includedFilePath = [System.IO.Path]::Combine($projFolder, [Regex]::Match($fileLine, '"(?<file>.*)"').Groups["file"].Value)
        $lineCountInFile = (Get-Content $includedFilePath).Count      
        $results+=New-Object PSObject -Property @{ Solution=$slnFile ;Project=$projFile; File=$includedFilePath; Lines=$lineCountInFile }
    }
}

#filter out any files we dont need
$results = $results | ?{!($_.File -match "Designer")}


#print out:

"---------------lines per solution--------------"
$results | group Solution | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
"---------------lines per peoject--------------"
$results | group Project | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}

How to connect HTML Divs with Lines?

Check my fiddle from this thread: Draw a line connecting two clicked div columns

The layout is different, but basically the idea is to create invisible divs between the boxes and add corresponding borders with jQuery (the answer is only HTML and CSS)

What is the use of static synchronized method in java?

Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.

Can I get div's background-image url?

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

How to send Basic Auth with axios

Hi you can do this in the following way

var username = '';
var password = ''

const token = `${username}:${password}`;
const encodedToken = Buffer.from(token).toString('base64');
const session_url = 'http://api_address/api/session_endpoint';

var config = {
  method: 'get',
  url: session_url,
  headers: { 'Authorization': 'Basic '+ encodedToken }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

Finishing current activity from a fragment

Very simple...

1- just grab activity by getActivity() in the fragment

2- then call finish();

So just getActivity().finish(); will finish the parent activity.

How to detect the OS from a Bash script?

For my .bashrc, I use the following code:

platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
   platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
   platform='freebsd'
fi

Then I do somethings like:

if [[ $platform == 'linux' ]]; then
   alias ls='ls --color=auto'
elif [[ $platform == 'freebsd' ]]; then
   alias ls='ls -G'
fi

It's ugly, but it works. You may use case instead of if if you prefer.

How to set the focus for a particular field in a Bootstrap modal, once it appears

I had the same problem with the bootstrap 3 and solved like this:

$('#myModal').on('shown.bs.modal', function (e) {
    $(this).find('input[type=text]:visible:first').focus();
})

$('#myModal').modal('show').trigger('shown');

How can I String.Format a TimeSpan object with a custom format in .NET?

Personally, I like this approach:

TimeSpan ts = ...;
string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);

You can make this as custom as you like with no problems:

string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);

C++ passing an array pointer as a function argument

This is another method . Passing array as a pointer to the function
void generateArray(int *array,  int size) {
    srand(time(0));
    for (int j=0;j<size;j++)
        array[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

Correct modification of state arrays in React.js

This code work for me:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
    this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
  })

Could not reliably determine the server's fully qualified domain name

I was NOT getting the ServerName wrong. Inside your VirtualHost configuration that is causing this warning message, it is the generic one near the top of your httpd.conf which is by default commented out.

Change

#ServerName www.example.com:80

to:

  ServerName 127.0.0.1:80

Printf width specifier to maintain precision of floating-point value

To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.

postgres default timezone

Note many third-party clients have own timezone settings overlapping any Postgres server and\or session settings.

E.g. if you're using 'IntelliJ IDEA 2017.3' (or DataGrips), you should define timezone as:

'DB source properties' -> 'Advanced' tab -> 'VM Options': -Duser.timezone=UTC+06:00

otherwise you will see 'UTC' despite of whatever you have set anywhere else.

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

Printing an array in C++?

C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.

"could not find stored procedure"

One more possibility to check. Listing here because it just happened to me and wasn't mentioned;-)

I had accidentally added a space character on the end of the name. Many hours of trying things before I finally noticed it. It's always something simple after you figure it out.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

I use a combined version :

strip_tags(preg_replace("/&(?!#?[a-z0-9]+;)/", "&amp;",$textorhtml))

How to configure Visual Studio to use Beyond Compare

If you are using the TFS, you can find the more information in diff/merge configuration in Team Foundation - common Command and Argument values

It shows how to configure the following tools:

  • WinDiff
  • DiffDoc (for Word files)
  • WinMerge
  • Beyond Compare
  • KDiff3
  • Araxis
  • Compare It!
  • SourceGear DiffMerge
  • Beyond Compare 3
  • TortoiseMerge
  • Visual SlickEdit

How to select records without duplicate on just one field in SQL?

Try this:

SELECT MIN(id) AS id, title
FROM tbl_countries
GROUP BY title

How to perform case-insensitive sorting in JavaScript?

You can also use the new Intl.Collator().compare, per MDN it's more efficient when sorting arrays. The downside is that it's not supported by older browsers. MDN states that it's not supported at all in Safari. Need to verify it, since it states that Intl.Collator is supported.

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property

["Foo", "bar"].sort(Intl.Collator().compare); //["bar", "Foo"]

send Content-Type: application/json post with node.js

Mikeal's request module can do this easily:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Make a VStack fill the width of the screen in SwiftUI

You can use GeometryReader in a handy extension to fill the parent

extension View {
    func fillParent(alignment:Alignment = .center) -> some View {
        return GeometryReader { geometry in
            self
                .frame(width: geometry.size.width,
                       height: geometry.size.height,
                       alignment: alignment)
        }
    }
}

so using the requested example, you get

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Title")
                .font(.title)

            Text("Content")
                .lineLimit(nil)
                .font(.body)
        }
        .fillParent(alignment:.topLeading)
        .background(Color.red)
    }
}

(note the spacer is no longer needed)

enter image description here

Drawing an image from a data URL to a canvas

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

jQuery - Fancybox: But I don't want scrollbars!

Fancybox 2.x at least has an "overlay helper" which turned out to be the key for me. I added the following to my fancybox configuration parameters:

helpers : {
  overlay : {
    css : { 'overlay' : 'hidden' }
  }
}

I had tried setting this in the CSS, but that didn't work, and late in the game, such as on the beforeShow event, but that led to a flickering bar. This seems to work without a hitch.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

React components (both functional as well as class) must begin with a capital letter. Like

const App=(props)=><div>Hey</div>

class App extends React.Component{
   render(){
     return <div>Hey</div>
   }
}

React identifies user-defined components by following this semantic. React's JSX transpiles to React.createElement function which returns an object representation of the dom node. The type property of this object tells whether it is a user-defined component or a dom element like div. Therefore it is important to follow this semantics

Since useState hook can only be used inside the functional component(or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.

useState can also be used inside the custom hooks which is used for the reusability and the abstraction of logic. So according to the rules of hooks, the name of a custom hook must begin with a "use" prefix and must be in a camelCase

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I think you have put command like java -VERSION. This is in capital letters You need to put all command in lowercase letters

javac -version
java -version

All characters must be in lowercase letter

How to print_r $_POST array?

As you need to see the result for testing purpose. The simple and elegant solution is the below code.

echo "<pre>";
print_r($_POST);
echo "</pre>";

align divs to the bottom of their container

Why can't you use absolute positioning? Vertical-align does not work (except for tables). Make your container's position: relative. Then absolutely position the internal divs using bottom: 0; Should work like a charm.

EDIT By zoidberg (i will update the answer instead)

<div style="position:relative; border: 1px solid red;width: 40px; height: 40px;">
   <div style="border:1px solid green;position: absolute; bottom: 0; left: 0; width: 20px; height: 20px;"></div>
   <div style="border:1px solid blue;position: absolute; bottom: 0; left: 20px; width: 20px height: 20px;"></div>
</div>

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

Git: Remove committed file after push

You can revert only one file to a specified revision.

First you can check on which commits the file was changed.

git log path/to/file.txt

Then you can checkout the file with the revision number.

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt

After that you can commit and push it again.

how to open .mat file without using MATLAB?

You don't need to download any new software. You can use Octave Online to open .m files.

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

How to merge 2 JSON objects from 2 files using jq?

This can be used to merge any number of files specified on the command:

jq -rs 'reduce .[] as $item ({}; . * $item)' file1.json file2.json file3.json ... file10.json

or this for any number of files

jq -rs 'reduce .[] as $item ({}; . * $item)' ./*.json

How can I change the color of AlertDialog title and the color of the line under it

Instead of using divider in dialog, use the view in the custom layout and set the layout as custom layout in dialog.

custom_popup.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <com.divago.view.TextViewMedium
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:text="AlertDialog"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <View
        android:id="@+id/border"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/txtTitle"
        android:background="@color/txt_dark_grey" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/border"
        android:scrollbars="vertical">

        <com.divago.view.TextViewRegular
            android:id="@+id/txtPopup"
            android:layout_margin="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</RelativeLayout>

activity.java:

public void showPopUp(String title, String text) {

    LayoutInflater inflater = getLayoutInflater();
    View alertLayout = inflater.inflate(R.layout.custom_popup, null);

    TextView txtContent = alertLayout.findViewById(R.id.txtPopup);
    txtContent.setText(text);

    TextView txtTitle = alertLayout.findViewById(R.id.txtTitle);
    txtTitle.setText(title);

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setView(alertLayout);
    alert.setCancelable(true);

    alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    AlertDialog dialog = alert.create();
    dialog.show();
}

Shuffle an array with python, randomize array item order with python

Alternative way to do this using sklearn

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

Output:

[2, 1, 3]
['two', 'one', 'three']

Advantage: You can random multiple arrays simultaneously without disrupting the mapping. And 'random_state' can control the shuffling for reproducible behavior.

File inside jar is not visible for spring

I had the same issue, ended up using the much more convenient Guava Resources:

Resources.getResource("my.file")

Git Remote: Error: fatal: protocol error: bad line length character: Unab

This error message is a bit obtuse, but what it's actually trying to tell you is that the remote server didn't reply with a proper git response. Ultimately, there was a problem on the server running the git-receive-pack process.

In the Git protocol, the first four bytes should be the line length. Instead, they were the characters Unab... which is probably the beginning an error message of some kind. (ie, it's probably "Unable to..." do something).

What happens when you run ssh <host> git-receive-pack <path-to-git-repository>? You should see the error message that your git client is barfing on and you may be able to correct it.

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

Retrieve last 100 lines logs

Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):

$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p

$ sed -nf sed.cmd logfilename

For me it is way more difficult than your script so

tail -n 100 logfilename

is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910

How can I return to a parent activity correctly?

Updated Answer: Up Navigation Design

You have to declare which activity is the appropriate parent for each activity. Doing so allows the system to facilitate navigation patterns such as Up because the system can determine the logical parent activity from the manifest file.

So for that you have to declare your parent Activity in tag Activity with attribute

android:parentActivityName

Like,

<!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.app_name.A" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name=".B"
        android:label="B"
        android:parentActivityName="com.example.app_name.A" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.app_name.A" />
    </activity>

With the parent activity declared this way, you can navigate Up to the appropriate parent like below,

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

So When you call NavUtils.navigateUpFromSameTask(this); this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward as defined by FLAG_ACTIVITY_CLEAR_TOP.

And to display Up button you have to declare setDisplayHomeAsUpEnabled():

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Old Answer: (Without Up Navigation, default Back Navigation)

It happen only if you are starting Activity A again from Activity B.

Using startActivity().

Instead of this from Activity A start Activity B using startActivityForResult() and override onActivtyResult() in Activity A.

Now in Activity B just call finish() on button Up. So now you directed to Activity A's onActivityResult() without creating of Activity A again..

Eclipse Intellisense?

If it's not working even when you already have Code Assist enabled, Eclipse's configuration files are probably corrupt. A solution that worked for me (on Eclipse 3.5.2) was to:

  1. Close Eclipse.
  2. Rename the workspace directory.
  3. Start Eclipse. (This creates a new workspace directory.)
  4. Import (with copy) the Java projects from the old workspace.

"elseif" syntax in JavaScript

You are missing a space between else and if

It should be else if instead of elseif

if(condition)
{

} 
else if(condition)
{

}
else
{

}

How to fix: "HAX is not working and emulator runs in emulation mode"

Either increase the ram size allocated while doing HAX installation , so as to fit exactly or a bit more higher space than the ram size of the emulator which you want to launch in "Intel x86 Emulator Accelerator (HAXM) " mode,

Once you succeed with that, you can now able to view this in the console /log

enter image description here

Java Replace Character At Specific Position Of String?

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}

How to detect Esc Key Press in React and how to handle it

For a reusable React hook solution

import React, { useEffect } from 'react';

const useEscape = (onEscape) => {
    useEffect(() => {
        const handleEsc = (event) => {
            if (event.keyCode === 27) 
                onEscape();
        };
        window.addEventListener('keydown', handleEsc);

        return () => {
            window.removeEventListener('keydown', handleEsc);
        };
    }, []);
}

export default useEscape

Usage:

const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))

SQL order string as number

The column I'm sorting with has any combination of alpha and numeric, so I used the suggestions in this post as a starting point and came up with this.

DECLARE @tmp TABLE (ID VARCHAR(50));
INSERT INTO @tmp VALUES ('XYZ300');
INSERT INTO @tmp VALUES ('XYZ1002');
INSERT INTO @tmp VALUES ('106');
INSERT INTO @tmp VALUES ('206');
INSERT INTO @tmp VALUES ('1002');
INSERT INTO @tmp VALUES ('J206');
INSERT INTO @tmp VALUES ('J1002');

SELECT ID, (CASE WHEN ISNUMERIC(ID) = 1 THEN 0 ELSE 1 END) IsNum
FROM @tmp
ORDER BY IsNum, LEN(ID), ID;

Results

ID
------------------------
106
206
1002
J206
J1002
XYZ300
XYZ1002

Hope this helps

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

Oracle SQL Developer spool output?

You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export

using Sql Developer 3.0

See SQL Developer downloads for latest versions

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Use Fail module.

  1. Use ignore_errors with every task that you need to ignore in case of errors.
  2. Set a flag (say, result = false) whenever there is a failure in any task execution
  3. At the end of the playbook, check if flag is set, and depending on that, fail the execution
- fail: msg="The execution has failed because of errors."
  when: flag == "failed"

Update:

Use register to store the result of a task like you have shown in your example. Then, use a task like this:

- name: Set flag
  set_fact: flag = failed
  when: "'FAILED' in command_result.stderr"

Google Chrome display JSON AJAX response as tree and not as a plain text

I'm not sure if Chrome has added this feature since the last answer, but I was able to view the json response by...

  • opening developer tools in the browser while on the page with the request
  • submitting the request
  • in developer tools - "Console" tab - click on the "Object" tree under the resource to expand

...I was able to view the response as a readable hierarchy that showed what to ask for and what is returned. (Neither Network or Resources tab had anything helpful that I was able to find.)

Happy requesting!

Generate a sequence of numbers in Python

In python 3.1 you can produce a list in a way

     lst=list(range(100))
     for i in range(100)
        print (lst[i],',',end='')

In python 2.7 you can do it as

     lst=range(100)
     for i in range(100)
        print lst[i]+',' 

How to add icon inside EditText view in Android ?

Use a relative layout and set the button the be align left of the edit text view, and set the left padding of your text view to the size of your button. I can't think of a good way to do it without hard coding the padding :/

You can also use apk tool to sorta unzip the facebook apk and take a look at its layout files.

SelectSingleNode returning null for known good xml node path using XPath

just use //id instead of /id. It works fine in my code

php convert datetime to UTC

As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone). So I propose this (I complicated by changing the HMTL format in plain/text...):

<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");

// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";

// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";

// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n"; 
?>

How to check all versions of python installed on osx and centos

As someone mentioned in a comment, you can use which python if it is supported by CentOS. Another command that could work is whereis python. In the event neither of these work, you can start the Python interpreter, and it will show you the version, or you could look in /usr/bin for the Python files (python, python3 etc).

svn over HTTP proxy

If you can get SSH to it you can an SSH Port-forwarded SVN server.

Use SSHs -L ( or -R , I forget, it always confuses me ) to make an ssh tunnel so that

127.0.0.1:3690 is really connecting to remote:3690 over the ssh tunnel, and then you can use it via

svn co svn://127.0.0.1/....

Windows equivalent to UNIX pwd

You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.

Hope it helps.

git: Switch branch and ignore any changes without committing

If you want to discard the changes,

git checkout -- <file>
git checkout branch

If you want to keep the changes,

git stash save
git checkout branch
git stash pop

How to include a class in PHP

I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

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

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.


Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":

GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed

How to change the default encoding to UTF-8 for Apache?

In httpd.conf add (or change if it's already there):

AddDefaultCharset utf-8

Showing an image from console in Python

Or simply execute the image through the shell, as in

import subprocess
subprocess.call([ fname ], shell=True)

and whatever program is installed to handle images will be launched.

how to get request path with express req object

To supplement, here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

Based on: https://expressjs.com/en/api.html#req.originalUrl

Conclusion: As c1moore's answer states, use:

var fullPath = req.baseUrl + req.path;

List all environment variables from the command line

To list all environment variables in PowerShell:

Get-ChildItem Env:

Or as suggested by user797717 to avoid output truncation:

Get-ChildItem Env: | Format-Table -Wrap -AutoSize

Source: Creating and Modifying Environment Variables (Windows PowerShell Tip of the Week)

Which MySQL data type to use for storing boolean values

You can use BOOL, BOOLEAN data type for storing boolean values.

These types are synonyms for TINYINT(1)

However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.

MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).

Further, read documentation

What does `ValueError: cannot reindex from a duplicate axis` mean?

I came across this error today when I wanted to add a new column like this

df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

I wanted to process the REMARK column of df_temp to return 1 or 0. However I typed wrong variable with df. And it returned error like this:

----> 1 df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2417         else:
   2418             # set column
-> 2419             self._set_item(key, value)
   2420 
   2421     def _setitem_slice(self, key, value):

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
   2483 
   2484         self._ensure_valid_index(value)
-> 2485         value = self._sanitize_column(key, value)
   2486         NDFrame._set_item(self, key, value)
   2487 

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
   2633 
   2634         if isinstance(value, Series):
-> 2635             value = reindexer(value)
   2636 
   2637         elif isinstance(value, DataFrame):

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in reindexer(value)
   2625                     # duplicate axis
   2626                     if not value.index.is_unique:
-> 2627                         raise e
   2628 
   2629                     # other

ValueError: cannot reindex from a duplicate axis

As you can see it, the right code should be

df_temp['REMARK_TYPE'] = df_temp.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

Because df and df_temp have a different number of rows. So it returned ValueError: cannot reindex from a duplicate axis.

Hope you can understand it and my answer can help other people to debug their code.

How to automatically reload a page after a given period of inactivity

var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();

bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
    time = new Date().getTime();
    window.location.reload(true);
    }else{
        time = new Date().getTime();
    }
}

Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.

'namespace' but is used like a 'type'

I suspect you've got the same problem at least twice.

Here:

namespace TimeTest
{
    class TimeTest
    {
}

... you're declaring a type with the same name as the namespace it's in. Don't do that.

Now you apparently have the same problem with Time2. I suspect if you add:

using Time2;

to your list of using directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)

(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

How to solve the memory error in Python

Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError.

Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).

If that's not enough, consider converting to a sqlite3 database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.

How to run mysql command on bash?

This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.

mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'

What exactly is \r in C language?

'\r' is the carriage return character. The main times it would be useful are:

  1. When reading text in binary mode, or which may come from a foreign OS, you'll find (and probably want to discard) it due to CR/LF line-endings from Windows-format text files.

  2. When writing to an interactive terminal on stdout or stderr, '\r' can be used to move the cursor back to the beginning of the line, to overwrite it with new contents. This makes a nice primitive progress indicator.

The example code in your post is definitely a wrong way to use '\r'. It assumes a carriage return will precede the newline character at the end of a line entered, which is non-portable and only true on Windows. Instead the code should look for '\n' (newline), and discard any carriage return it finds before the newline. Or, it could use text mode and have the C library handle the translation (but text mode is ugly and probably should not be used).

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

Netbeans how to set command line arguments in Java

IF you are using MyEclipse and want to add args before run the program, Then do as follows: 1.0) Run -> Run Config 2.1) Click "Arguments" on the right panel 2.2)add your args in the "Program Args" box, separated by blank

How can I export a GridView.DataSource to a datatable or dataset?

Ambu,

I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

    DataTable dt = new DataTable();

    // add the columns to the datatable            
    if (GridView1.HeaderRow != null)
    {

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
        }
    }

    //  add each of the data rows to the table
    foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

    //  add the footer row to the table
    if (GridView1.FooterRow != null)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
        {
            dr[i] = GridView1.FooterRow.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

Correct way to set Bearer token with CURL

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "your api goes here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJ0eciOiJSUzI1NiJ9.eyJMiIsInNjb3BlcyI6W119.K3lW1STQhMdxfAxn00E4WWFA3uN3iIA"
  ),
 ));

$response = curl_exec($curl);
$data = json_decode($response, true);

echo $data;

?>

Disable Proximity Sensor during call

If you have LineageOS 7.1.2 (and have root), try this solution from XDA.


After having tried all the solutions proposed here, none of which worked for my Nexus 4 (mako), I found one on XDA that solves the problem with the Android dialer (but not with other apps). Basically I downloaded a recompiled version of the Dialer.apk file, which simply ignores the proximity sensor and behaves in the same way as the stock dialer app does.

Rename /system/priv-app/Dialer/Dialer.apk to something, then place the downloaded file to that folder. After reboot, I had to install the new dialer manually (simply by clicking on it). So now the original app is replaced, and the calls should be handled by this new one.

[Downside: the new way to answer a call is by pulling down the status bar and clicking 'Answer' (or 'Dismiss'), the usual slider is missing. Also, you'll need to repeat this every time your Android updates to a newer version.]

Invalid shorthand property initializer

Because it's an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'
 }

In-memory size of a Python structure

When you use the dir([object]) built-in function, you can get the __sizeof__ of the built-in function.

>>> a = -1
>>> a.__sizeof__()
24

Implementing multiple interfaces with Java - is there a way to delegate?

There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

Call static methods from regular ES6 class methods

Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

class Super {
  static whoami() {
    return "Super";
  }
  lognameA() {
    console.log(Super.whoami());
  }
  lognameB() {
    console.log(this.constructor.whoami());
  }
}
class Sub extends Super {
  static whoami() {
    return "Sub";
  }
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub

Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.

This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self.

If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.

How to use regex in String.contains() method in Java

matcher.find() does what you needed. Example:

Pattern.compile("stores.*store.*product").matcher(someString).find();

How to place and center text in an SVG rectangle

The previous answers gave poor results when using rounded corners or stroke-width that's >1 . For example, you would expect the following code to produce a rounded rectangle, but the corners are clipped by the parent svg component:

_x000D_
_x000D_
<svg width="200" height="100">_x000D_
  <!--this rect should have rounded corners-->_x000D_
  <rect x="0" y="0" rx="5" ry="5" width="200" height="100" stroke="red" stroke-width="10px" fill="white"/>_x000D_
  <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CLIPPED BORDER</text>    _x000D_
</svg>
_x000D_
_x000D_
_x000D_

Instead, I recommend wrapping the text in a svg and then nesting that new svg and the rect together inside a g element, as in the following example:

_x000D_
_x000D_
<!--the outer svg here-->_x000D_
<svg width="400px" height="300px">_x000D_
_x000D_
  <!--the rect/text group-->_x000D_
  <g transform="translate(50,50)">_x000D_
    <rect rx="5" ry="5" width="200" height="100" stroke="green" fill="none" stroke-width="10"/>_x000D_
    <svg width="200px" height="100px">_x000D_
      <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CORRECT BORDER</text>      _x000D_
    </svg>_x000D_
  </g>_x000D_
_x000D_
  <!--rest of the image's code-->_x000D_
</svg>
_x000D_
_x000D_
_x000D_

This fixes the clipping problem that occurs in the answers above. I also translated the rect/text group using the transform="translate(x,y)" attribute to demonstrate that this provides a more intuitive approach to positioning the rect/text on-screen.

ZIP file content type for HTTP request

[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];

Pass element ID to Javascript function

The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.

This worked:

validateSelectizeDropdown('#PartCondition')

This did not:

validateSelectizeDropdown("#PartCondition")

And the function:

    function validateSelectizeDropdown(name) {
    if ($(name).val() === "") {
         //do something
    }
}

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

I think the problem is with the user having deny privileges. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want.

GRANT the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database.

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

Plotting with C#

NPlot is a pretty good simple open source 2D plotting API. Unfortunately, the web site is down. I don't know if this is just temporary or not. I haven't heard of any bad news. It may come back up.

http://www.nplot.com

Here is an article describing it:

http://aspnet.4guysfromrolla.com/articles/072507-1.aspx

The previous article uses VB.NET, but obviously this will work with C#.

Again, not sure why nplot's site is not currently working but it is a somewhat popular plotting API that I've used in the past. I post it for your information and in case of the likely event nplot will be back up soon. :)

Edit:

Thanks to a Hosam Aly, it looks like the SourceForge project can still be accessed here:

http://sourceforge.net/projects/nplot

Unable to read repository at http://download.eclipse.org/releases/indigo

My issue was the Eclipse Marketplace client needed updating.

After trying Fredriks solution of

Go to Window -> Preferences -> Install/update: Available Software sites. Then remove and add the indigo site. Just remember to copy the adress so you can add it again.

The Marketplace client wouldn't load. But I could access it via a browser. So, I went to the Help -> Eclipse Marketplace it loaded fine

Clicked on Installed and found the Eclipse Marketplace Client and it had so i clicked it it updated and then when I did the standard update everything worked.

How to change ProgressBar's progress indicator color in Android

For anyone looking for how to do it programmatically:

    Drawable bckgrndDr = new ColorDrawable(Color.RED);
    Drawable secProgressDr = new ColorDrawable(Color.GRAY);
    Drawable progressDr = new ScaleDrawable(new ColorDrawable(Color.BLUE), Gravity.LEFT, 1, -1);
    LayerDrawable resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, secProgressDr, progressDr });
    //setting ids is important
    resultDr.setId(0, android.R.id.background);
    resultDr.setId(1, android.R.id.secondaryProgress);
    resultDr.setId(2, android.R.id.progress);

Setting ids to drawables is crucial, and takes care of preserving bounds and actual state of progress bar

Decode UTF-8 with Javascript

This is a solution with extensive error reporting.

It would take an UTF-8 encoded byte array (where byte array is represented as array of numbers and each number is an integer between 0 and 255 inclusive) and will produce a JavaScript string of Unicode characters.

function getNextByte(value, startByteIndex, startBitsStr, 
                     additional, index) 
{
    if (index >= value.length) {
        var startByte = value[startByteIndex];
        throw new Error("Invalid UTF-8 sequence. Byte " + startByteIndex 
            + " with value " + startByte + " (" + String.fromCharCode(startByte) 
            + "; binary: " + toBinary(startByte)
            + ") starts with " + startBitsStr + " in binary and thus requires " 
            + additional + " bytes after it, but we only have " 
            + (value.length - startByteIndex) + ".");
    }
    var byteValue = value[index];
    checkNextByteFormat(value, startByteIndex, startBitsStr, additional, index);
    return byteValue;
}

function checkNextByteFormat(value, startByteIndex, startBitsStr, 
                             additional, index) 
{
    if ((value[index] & 0xC0) != 0x80) {
        var startByte = value[startByteIndex];
        var wrongByte = value[index];
        throw new Error("Invalid UTF-8 byte sequence. Byte " + startByteIndex 
             + " with value " + startByte + " (" +String.fromCharCode(startByte) 
             + "; binary: " + toBinary(startByte) + ") starts with " 
             + startBitsStr + " in binary and thus requires " + additional 
             + " additional bytes, each of which shouls start with 10 in binary."
             + " However byte " + (index - startByteIndex) 
             + " after it with value " + wrongByte + " (" 
             + String.fromCharCode(wrongByte) + "; binary: " + toBinary(wrongByte)
             +") does not start with 10 in binary.");
    }
}

function fromUtf8 (str) {
        var value = [];
        var destIndex = 0;
        for (var index = 0; index < str.length; index++) {
            var code = str.charCodeAt(index);
            if (code <= 0x7F) {
                value[destIndex++] = code;
            } else if (code <= 0x7FF) {
                value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0xFFFF) {
                value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x1FFFFF) {
                value[destIndex++] = ((code >> 18) & 0x07) | 0xF0;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x03FFFFFF) {
                value[destIndex++] = ((code >> 24) & 0x03) | 0xF0;
                value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else if (code <= 0x7FFFFFFF) {
                value[destIndex++] = ((code >> 30) & 0x01) | 0xFC;
                value[destIndex++] = ((code >> 24) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
                value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
            } else {
                throw new Error("Unsupported Unicode character \"" 
                    + str.charAt(index) + "\" with code " + code + " (binary: " 
                    + toBinary(code) + ") at index " + index
                    + ". Cannot represent it as UTF-8 byte sequence.");
            }
        }
        return value;
    }

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Console.Write((int)response.StatusCode);

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

Condition within JOIN or WHERE

For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).

However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:

SELECT *
FROM dbo.Customers AS CUS 
LEFT JOIN dbo.Orders AS ORD 
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'

SELECT *
FROM dbo.Customers AS CUS 
LEFT JOIN dbo.Orders AS ORD 
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'

The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.

The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)

The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.

SELECT *
FROM dbo.Customers AS CUS 
LEFT JOIN dbo.Orders AS ORD 
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null

Calling stored procedure with return value

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

@Result int OUTPUT

And C#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

            r

Result.Direction = ParameterDirection.InputOutput;

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

How to know/change current directory in Python shell?

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

How to get and set the current web page scroll position?

The currently accepted answer is incorrect - document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

To get the current position, you want:

document.documentElement.scrollTop || document.body.scrollTop

You can set the current position to 1000px down the page like so:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

Or, using jQuery (animate it while you're at it!):

$("html, body").animate({ scrollTop: "1000px" });

Tensorflow: how to save/restore a model?

You can also check out examples in TensorFlow/skflow, which offers save and restore methods that can help you easily manage your models. It has parameters that you can also control how frequently you want to back up your model.

jQuery: Slide left and slide right

You can do this with the additional effects in jQuery UI: See here for details

Quick example:

$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);

How can I set the focus (and display the keyboard) on my EditText programmatically

First way:

    etPassword.post(() -> {
        etPassword.requestFocus();
        InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
    });

Second way:

In Manifest:

    <activity
        android:name=".activities.LoginActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateVisible"/>

In code:

etPassword.requestFocus();

Validating Phone Numbers Using Javascript

To validate Phone number using regular expression in java script.

In india phone is 10 digit and starting digits are 6,7,8 and 9.

Javascript and HTML code:

_x000D_
_x000D_
function validate()
{
  var text = document.getElementById("pno").value;
  var regx = /^[6-9]\d{9}$/ ;
  if(regx.test(text))
    alert("valid");
  else
    alert("invalid");
}
_x000D_
<html>
    <head>
        <title>JS compiler - knox97</title>
  </head>
  <body>
  <input id="pno" placeholder="phonenumber" type="tel" maxlength="10" > 
    </br></br>
    <button onclick="validate()" type="button">submit</button>
  </body>
</html>
_x000D_
_x000D_
_x000D_

How to get the list of all printers in computer

Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.

It is a list of the names of all installed printers on the system.

How can I check if a string contains ANY letters from the alphabet?

I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.

~250 ns for

import re

~3 µs for

re.search('[a-zA-Z]', string)

~6 µs for

any(c.isalpha() for c in string)

~850 ns for

string.upper().isupper()


Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.

But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

SQL Server SELECT INTO @variable?

It looks like your syntax is slightly out. This has some good examples

DECLARE @TempCustomer TABLE
(
   CustomerId uniqueidentifier,
   FirstName nvarchar(100),
   LastName nvarchar(100),
   Email nvarchar(100)
);
INSERT @TempCustomer 
SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

Then later

SELECT CustomerId FROM @TempCustomer

.setAttribute("disabled", false); changes editable attribute to false

just replace 'myselect' with your id

to disable->

document.getElementById("mySelect").disabled = true;  

to enable->

document.getElementById("mySelect").disabled = false; 

How to format a DateTime in PowerShell

A very convenient -- but probably not all too efficient -- solution is to use the member function GetDateTimeFormats(),

$d = Get-Date
$d.GetDateTimeFormats()

This outputs a large string-array of formatting styles for the date-value. You can then pick one of the elements of the array via the []-operator, e.g.,

PS C:\> $d.GetDateTimeFormats()[12]
Dienstag, 29. November 2016 19.14

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

Can I invoke an instance method on a Ruby module without including it?

If you want to call these methods without including module in another class then you need to define them as module methods:

module UsefulThings
  def self.get_file; ...
  def self.delete_file; ...

  def self.format_text(x); ...
end

and then you can call them with

UsefulThings.format_text("xxx")

or

UsefulThings::format_text("xxx")

But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.

Logical operators for boolean indexing in Pandas

When you say

(a['x']==1) and (a['y']==10)

You are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to boolean values.

NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.

Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.

Instead, you must be explicit, by calling the empty(), all() or any() method to indicate which behavior you desire.

In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the & binary operator performs:

(a['x']==1) & (a['y']==10)

returns a boolean array.


By the way, as alexpmil notes, the parentheses are mandatory since & has a higher operator precedence than ==. Without the parentheses, a['x']==1 & a['y']==10 would be evaluated as a['x'] == (1 & a['y']) == 10 which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10). That is an expression of the form Series and Series. The use of and with two Series would again trigger the same ValueError as above. That's why the parentheses are mandatory.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

SQL Server: how to select records with specific date from datetime column

SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';

This will select all the data between the 2 dates

How do you check "if not null" with Eloquent?

in laravel 5.4 this code Model::whereNotNull('column') was not working you need to add get() like this one Model::whereNotNull('column')->get(); this one works fine for me.

What is the difference between Serialization and Marshaling?

Both do one thing in common - that is serializing an Object. Serialization is used to transfer objects or to store them. But:

  • Serialization: When you serialize an object, only the member data within that object is written to the byte stream; not the code that actually implements the object.
  • Marshalling: Term Marshalling is used when we talk about passing Object to remote objects(RMI). In Marshalling Object is serialized(member data is serialized) + Codebase is attached.

So Serialization is part of Marshalling.

CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

Open existing file, append a single line

//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>

Add a column to a table, if it does not already exist

You can use a similar construct by using the sys.columns table io sys.objects.

IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[Person]') 
         AND name = 'ColumnName'
)

How do I create a right click context menu in Java Swing?

You are probably manually calling setVisible(true) on the menu. That can cause some nasty buggy behavior in the menu.

The show(Component, int x, int x) method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true) just shows the menu without adding any additional behavior.

To make a right click popup menu simply create a JPopupMenu.

class PopUpDemo extends JPopupMenu {
    JMenuItem anItem;
    public PopUpDemo() {
        anItem = new JMenuItem("Click Me!");
        add(anItem);
    }
}

Then, all you need to do is add a custom MouseListener to the components you would like the menu to popup for.

class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    private void doPop(MouseEvent e) {
        PopUpDemo menu = new PopUpDemo();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
}

// Then on your component(s)
component.addMouseListener(new PopClickListener());

Of course, the tutorials have a slightly more in-depth explanation.

Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen() and e.getYOnScreen() methods for the x and y coordinates.

IE9 jQuery AJAX with CORS returns "Access is denied"

I just made all requests JSONP because it was the only solution for all of our supported browsers (IE7+ and the regulars). Mind you, your answer technically works for IE9 so you have the correct answer.

Setting up an MS-Access DB for multi-user access

The correct way of building client/server Microsoft Access applications where the data is stored in a RDBMS is to use the Linked Table method. This ensures Data Isolation and Concurrency is maintained between the Microsoft Access client application and the RDBMS data with no additional and unnecessary programming logic and code which makes maintenance more difficult, and adds to development time.

see: http://claysql.blogspot.com/2014/08/normal-0-false-false-false-en-us-x-none.html

Select data between a date/time range

In a simple way it can be queried as

select * from hockey_stats 
where game_date between '2018-01-01' and '2018-01-31';

This works if time is not a concern.

Considering time also follow in the following way:

select * from hockey_stats where (game_date between '2018-02-05 01:20:00' and '2018-02-05 03:50:00');

Note this is for MySQL server.

NumPy array is not JSON serializable

You can use Pandas:

import pandas as pd
pd.Series(your_array).to_json(orient='values')

Math operations from string

Warning: this way is not a safe way, but is very easy to use. Use it wisely.

Use the eval function.

print eval('2 + 4')

Output:

6

You can even use variables or regular python code.

a = 5
print eval('a + 4')

Output:

9

You also can get return values:

d = eval('4 + 5')
print d

Output:

9

Or call functions:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a = 20
b = 10    
print eval('add(a, b)')
print eval('subtract(a, b)')

Output:

30
10

In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.

Why eval is unsafe?

Since you can put literally anything in the eval, e.g. if the input argument is:

os.system(‘rm -rf /’)

It will remove all files on your system (at least on Linux/Unix). So only use eval when you trust the input.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

OrderBy pipe issue

As we know filter and order by are removed from ANGULAR 2 and we need to write our own, here is a good example on plunker and detailed article

It used both filter as well as orderby, here is the code for order pipe

import { Pipe, PipeTransform } from '@angular/core';    
@Pipe({  name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {       
    return records.sort(function(a, b){
          if(a[args.property] < b[args.property]){
            return -1 * args.direction;
          }
          else if( a[args.property] > b[args.property]){
            return 1 * args.direction;
          }
          else{
            return 0;
          }
        });
    };
 }

How to show all shared libraries used by executables in Linux?

I found this post very helpful as I needed to investigate dependencies from a 3rd party supplied library (32 vs 64 bit execution path(s)).

I put together a Q&D recursing bash script based on the 'readelf -d' suggestion on a RHEL 6 distro.

It is very basic and will test every dependency every time even if it might have been tested before (i.e very verbose). Output is very basic too.

#! /bin/bash

recurse ()
# Param 1 is the nuumber of spaces that the output will be prepended with
# Param 2 full path to library
{
#Use 'readelf -d' to find dependencies
dependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')
for d in $dependencies; do
   echo "${1}${d}"
   nm=${d##*/}
   #libstdc++ hack for the '+'-s
   nm1=${nm//"+"/"\+"}
   # /lib /lib64 /usr/lib and /usr/lib are searched
   children=$(locate ${d} | grep -E "(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})")
   rc=$?
   #at least locate... didn't fail
   if [ ${rc} == "0" ] ; then
      #we have at least one dependency
      if [ ${#children[@]} -gt 0 ]; then
         #check the dependeny's dependencies
         for c in $children; do
          recurse "  ${1}" ${c}
         done
      else
         echo "${1}no children found"
      fi
   else
      echo "${1}locate failed for ${d}"
   fi
done
}
# Q&D -- recurse needs 2 params could/should be supplied from cmdline
recurse "" !!full path to library you want to investigate!!

redirect the output to a file and grep for 'found' or 'failed'

Use and modify, at your own risk of course, as you wish.

When to use window.opener / window.parent / window.top

top, parent, opener (as well as window, self, and iframe) are all window objects.

  1. window.opener -> returns the window that opens or launches the current popup window.
  2. window.top -> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.
  3. window.parent -> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or self

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

What are .a and .so files?

They are used in the linking stage. .a files are statically linked, and .so files are sort-of linked, so that the library is needed whenever you run the exe.

You can find where they are stored by looking at any of the lib directories... /usr/lib and /lib have most of them, and there is also the LIBRARY_PATH environment variable.

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

Mongoose query where value is not null

I ended up here and my issue was that I was querying for

{$not: {email: /@domain.com/}}

instead of

{email: {$not: /@domain.com/}}

Wait .5 seconds before continuing code VB.net

In web application a timer will be the best approach.

Just fyi, in desktop application I use this instead, inside an async method.

... 
Await Task.Run(Sub()
    System.Threading.Thread.Sleep(5000)
End Sub)
...

It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.

Set Background cell color in PHPExcel

  $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');

It's in the documentation, located here: https://github.com/PHPOffice/PHPExcel/wiki/User-Documentation-Overview-and-Quickstart-Guide

C# string replace

Make sure you properly escape the quotes.

  string line = "\"Text\",\"Text\",\"Text\",";

  string result = line.Replace("\",\"", ";");

How to pass anonymous types as parameters?

You can use generics with the following trick (casting to anonymous type):

public void LogEmployees<T>(IEnumerable<T> list)
{
    foreach (T item in list)
    {
        var typedItem = Cast(item, new { Name = "", Id = 0 });
        // now you can use typedItem.Name, etc.
    }
}

static T Cast<T>(object obj, T type)
{
    return (T)obj;
}

Docker command can't connect to Docker daemon

I was able to fix that by running the following command:

sudo mv /var/lib/dpkg/info/docker-ce* /tmp

Is it possible to animate scrollTop with jQuery?

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Variable name as a string in Javascript

No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

How to properly add 1 month from now to current date in moment.js

_x000D_
_x000D_
startdate = "20.03.2020";_x000D_
    var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');_x000D_
_x000D_
     alert(new_date)
_x000D_
_x000D_
_x000D_

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

Java equivalent to Explode and Implode(PHP)

Good alternatives are the String.split and StringUtils.join methods.

Explode :

String[] exploded="Hello World".split(" ");

Implode :

String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");

Keep in mind though that StringUtils is in an external library.

Determine if string is in list in JavaScript

Most of the answers suggest the Array.prototype.indexOf method, the only problem is that it will not work on any IE version before IE9.

As an alternative I leave you two more options that will work on all browsers:

if (/Foo|Bar|Baz/.test(str)) {
  // ...
}


if (str.match("Foo|Bar|Baz")) {
  // ...
}

Angular - ng: command not found

>> npm uninstall -g angular-cli
>> npm uninstall -g @angular/cli

>> npm cache clean

Restart you machine

then >> npm install -g @angular/cli@latest

set Path : C:\Users\admin\AppData\Roaming\npm\node_modules@angular\cli

Hope you never get 'ng' not found

How can I store HashMap<String, ArrayList<String>> inside a list?

Try the following:

List<Map<String, ArrayList<String>>> mapList = 
    new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);

If your list must be of type List<HashMap<String, ArrayList<String>>>, then declare your map variable as a HashMap and not a Map.

How to convert a string to utf-8 in Python

Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use:

def make_unicode(input):
    if type(input) != unicode:
        input =  input.decode('utf-8')
    return input

Are the shift operators (<<, >>) arithmetic or logical in C?

Well, I looked it up on wikipedia, and they have this to say:

C, however, has only one right shift operator, >>. Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.

So it sounds like it depends on your compiler. Also in that article, note that left shift is the same for arithmetic and logical. I would recommend doing a simple test with some signed and unsigned numbers on the border case (high bit set of course) and see what the result is on your compiler. I would also recommend avoiding depending on it being one or the other since it seems C has no standard, at least if it is reasonable and possible to avoid such dependence.

What is the difference between XAMPP or WAMP Server & IIS?

XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.

XWAMPP/WAMP - Windows,Apache,Mysql,PHP

IIS - Apache,SQL Server, ASP.NET

If you like to read more about XWAMPP vs WAMP

Identify duplicates in a List

This also works:

public static Set<Integer> findDuplicates(List<Integer> input) {
    List<Integer> copy = new ArrayList<Integer>(input);
    for (Integer value : new HashSet<Integer>(input)) {
        copy.remove(value);
    }
    return new HashSet<Integer>(copy);
}

What is the correct way to do a CSS Wrapper?

The easiest way is to have a "wrapper" div element with a width set, and a left and right margin of auto.

Sample markup:

<!doctype html>
<html>
<head>
    <title></title>
    <style type="text/css">
        .wrapper { width: 960px; margin: 0 auto; background-color: #cccccc; }
        body { margin: 0; padding: 0 }
    </style>
</head>
<body>
    <div class="wrapper">
        your content...
    </div>
</body>
</html>

How do I filter ForeignKey choices in a Django ModelForm?

If you haven't created the form and want to change the queryset you can do:

formmodel.base_fields['myfield'].queryset = MyModel.objects.filter(...)

This is pretty useful when you are using generic views!

How to return XML in ASP.NET?

XmlDocument xd = new XmlDocument();
xd.LoadXml(xmlContent);

context.Response.Clear();
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
xd.Save(context.Response.Output);
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();

BAT file to open CMD in current directory

you can try:

shift + right click

then, click on Open command prompt here

Detecting Back Button/Hash Change in URL

Another great implementation is balupton's jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

What's the most appropriate HTTP status code for an "item not found" error page

A 404 return code actually means 'resource not found', and applies to any entity for which a request was made but not satisfied. So it works equally-well for pages, subsections of pages, and any item that exists on the page which has a specific request to be rendered.

So 404 is the right code to use in this scenario. Note that it doesn't apply to 'server not found', which is a different situation in which a request was issued but not answered at all, as opposed to answered but without the resource requested.

Android: ListView elements with multiple clickable buttons

Probably you've found how to do it, but you can call

ListView.setItemsCanFocus(true)

and now your buttons will catch focus

Pass values of checkBox to controller action in asp.net mvc4

<form action="Save" method="post">
 IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive"  />

 </form>

 public ActionResult Save(Director director)
        {
                   // IsValid is my Director prop same name give    
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

AngularJS HTTP post to PHP and undefined

Because PHP does not natively accept JSON 'application/json' One approach is to update your headers and parameters from angular so that your api can use the data directly.

First, Parameterize your data:

data: $.param({ "foo": $scope.fooValue })

Then, add the following to your $http

 headers: {
     'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
 }, 

If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

myApp.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Pointer vs. Reference

This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.

While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.

Sort a two dimensional array based on one column

If you are looking for easy one liners to sort 2d array, then here you go.


Sort String[][] arr in ascending order by first column

Arrays.sort(arr, (a, b) -> a[0].compareTo(b[0]);

Sort String[][] arr in descending order by first column

Arrays.sort(arr, (a, b) -> b[0].compareTo(a[0]);

Sort String[][] arr in ascending order by second column

Arrays.sort(arr, (a, b) -> a[1].compareTo(b[1]);

Sort String[][] arr in descending order by second column

Arrays.sort(arr, (a, b) -> b[1].compareTo(a[1]);

Sort int[][] arr in ascending order by first column

Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));

or

Arrays.sort(arr, (a, b) -> a[0] - b[0]);

Sort int[][] arr in descending order by first column

Arrays.sort(arr, (a, b) -> Integer.compare(b[0], a[0]));

or

Arrays.sort(arr, (a, b) -> b[0] - a[0]);

Sort int[][] arr in ascending order by second column

Arrays.sort(arr, (a, b) -> Integer.compare(a[1], b[1]));

or

Arrays.sort(arr, (a, b) -> a[1] - b[1]);

Sort int[][] arr in descending order by second column

Arrays.sort(arr, (a, b) -> Integer.compare(b[1], a[1]));

or

Arrays.sort(arr, (a, b) -> b[1] - a[1]);

Inserting values to SQLite table in Android

public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SQLiteDatabase db;
    db = openOrCreateDatabase(
        "TestingData.db"
        , SQLiteDatabase.CREATE_IF_NECESSARY
        , null
        );
 }

}

then see this link link

Custom exception type

In short:

Option 1: use babel-plugin-transform-builtin-extend

Option 2: do it yourself (inspired from that same library)

    function CustomError(...args) {
      const instance = Reflect.construct(Error, args);
      Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Reflect.setPrototypeOf(CustomError, Error);
  • If you are using pure ES5:

    function CustomError(message, fileName, lineNumber) {
      const instance = new Error(message, fileName, lineNumber);
      Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    if (Object.setPrototypeOf){
        Object.setPrototypeOf(CustomError, Error);
    } else {
        CustomError.__proto__ = Error;
    }
    
  • Alternative: use Classtrophobic framework

Explanation:

Why extending the Error class using ES6 and Babel is a problem?

Because an instance of CustomError is not anymore recognized as such.

class CustomError extends Error {}
console.log(new CustomError('test') instanceof Error);// true
console.log(new CustomError('test') instanceof CustomError);// false

In fact, from the official documentation of Babel, you cannot extend any built-in JavaScript classes such as Date, Array, DOM or Error.

The issue is described here:

What about the other SO answers?

All the given answers fix the instanceof issue but you lose the regular error console.log:

console.log(new CustomError('test'));
// output:
// CustomError {name: "MyError", message: "test", stack: "Error?    at CustomError (<anonymous>:4:19)?    at <anonymous>:1:5"}

Whereas using the method mentioned above, not only you fix the instanceof issue but you also keep the regular error console.log:

console.log(new CustomError('test'));
// output:
// Error: test
//     at CustomError (<anonymous>:2:32)
//     at <anonymous>:1:5

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

Default port for SQL Server

The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.

Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine.

For more information see SQL Server Browser Service on MSDN.

How do I print an IFrame from javascript in Safari/Chrome

Use firefox window.frames but also add the name property because that uses the iframe in firefox

IE:

window.frames[id]

Firefox:

window.frames[name]

<img src="print.gif"  onClick="javascript: window.frames['factura'].focus(); parent['factura'].print();">
<iframe src="factura.html" width="100%" height="400" id="factura" name="factura"></iframe>

remove script tag from HTML content

Shorter:

$html = preg_replace("/<script.*?\/script>/s", "", $html);

When doing regex things might go wrong, so it's safer to do like this:

$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;

So that when the "accident" happen, we get the original $html instead of empty string.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Why is my JavaScript function sometimes "not defined"?

I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself.

In this case some browsers might prevent you from creating such reference loops and fire "function not defined" error.

Inline code would be better solution in such case.

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

Count the number of occurrences of each letter in string

#include<stdio.h>
#include<string.h>

#define filename "somefile.txt"

int main()
{
    FILE *fp;
    int count[26] = {0}, i, c;  
    char ch;
    char alpha[27] = "abcdefghijklmnopqrstuwxyz";
    fp = fopen(filename,"r");
    if(fp == NULL)
        printf("file not found\n");
    while( (ch = fgetc(fp)) != EOF) {
        c = 0;
        while(alpha[c] != '\0') {

            if(alpha[c] == ch) {
                count[c]++; 
            }
            c++;
        }
    }
    for(i = 0; i<26;i++) {
        printf("character %c occured %d number of times\n",alpha[i], count[i]);
    }
    return 0;
}

Linux command: How to 'find' only text files?

Why is it unhandy? If you need to use it often, and don't want to type it every time just define a bash function for it:

function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text
}

put it in your .bashrc and then just run:

findTextInAsciiFiles your_folder "needle text"

whenever you want.


EDIT to reflect OP's edit:

if you want to cut out mime informations you could just add a further stage to the pipeline that filters out mime informations. This should do the trick, by taking only what comes before :: cut -d':' -f1:

function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text | cut -d ':' -f1
}

Column calculated from another column?

You can use generated columns from MYSQL 5.7.

Example Usage:

ALTER TABLE tbl_test
ADD COLUMN calc_val INT 
GENERATED ALWAYS AS (((`column1` - 1) * 16) + `column2`) STORED;

VIRTUAL / STORED

  • Virtual: calculated on the fly when a record is read from a table (default)
  • Stored: calculated when a new record is inserted/updated within the table

How to get your Netbeans project into Eclipse

You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just

  1. Go to File -> Import
  2. Open Maven tree node
  3. Select Existing Maven Project
  4. Browse to find your project from NetBeans
  5. Check Add project to Working Set
  6. Click finish.

As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.

Retrieve CPU usage and memory usage of a single process on Linux?

A variant of caf's answer: top -p <pid>

This auto-refreshes the CPU usage so it's good for monitoring.

How to paste yanked text into the Vim command line

It's worth noting also that the yank registers are the same as the macro buffers. In other words, you can simply write out your whole command in your document (including your pasted snippet), then "by to yank it to the b register, and then run it with @b.

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

GZIPInputStream reading line by line

The basic setup of decorators is like this:

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.

For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.

Most network protocols use a header or other metadata to explicitly note the character encoding.

In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.

Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!