Programs & Examples On #Mp3

MPEG-1 or MPEG-2 Audio Layer III, more commonly referred to as MP3, is a patented digital audio encoding format using a form of lossy data compression. It is a common audio format for consumer audio storage, as well as a de facto standard of digital audio compression for the transfer and playback of music on digital audio players.

Which mime type should I use for mp3

Your best bet would be using the RFC defined mime-type audio/mpeg.

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

Accessing MP3 metadata with Python

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

Playing a MP3 file in a WinForm application

1) The most simple way would be using WMPLib

WMPLib.WindowsMediaPlayer Player;

private void PlayFile(String url)
{
    Player = new WMPLib.WindowsMediaPlayer();
    Player.PlayStateChange += Player_PlayStateChange;
    Player.URL = url;
    Player.controls.play();
}

private void Player_PlayStateChange(int NewState)
{
    if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
    {
        //Actions on stop
    }
}

2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.

This is as simple as

using NAudio;
using NAudio.Wave;

IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");

waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();

Don't forget to dispose after the stop

waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();

Playing mp3 song on python

import os
os.system('file_path/filename.mp3')

View/edit ID3 data for MP3 files

TagLib Sharp is pretty popular.

As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.

class MusicID3Tag

{

    public byte[] TAGID = new byte[3];      //  3
    public byte[] Title = new byte[30];     //  30
    public byte[] Artist = new byte[30];    //  30 
    public byte[] Album = new byte[30];     //  30 
    public byte[] Year = new byte[4];       //  4 
    public byte[] Comment = new byte[30];   //  30 
    public byte[] Genre = new byte[1];      //  1

}

string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";

        using (FileStream fs = File.OpenRead(filePath))
        {
            if (fs.Length >= 128)
            {
                MusicID3Tag tag = new MusicID3Tag();
                fs.Seek(-128, SeekOrigin.End);
                fs.Read(tag.TAGID, 0, tag.TAGID.Length);
                fs.Read(tag.Title, 0, tag.Title.Length);
                fs.Read(tag.Artist, 0, tag.Artist.Length);
                fs.Read(tag.Album, 0, tag.Album.Length);
                fs.Read(tag.Year, 0, tag.Year.Length);
                fs.Read(tag.Comment, 0, tag.Comment.Length);
                fs.Read(tag.Genre, 0, tag.Genre.Length);
                string theTAGID = Encoding.Default.GetString(tag.TAGID);

                if (theTAGID.Equals("TAG"))
                {
                    string Title = Encoding.Default.GetString(tag.Title);
                    string Artist = Encoding.Default.GetString(tag.Artist);
                    string Album = Encoding.Default.GetString(tag.Album);
                    string Year = Encoding.Default.GetString(tag.Year);
                    string Comment = Encoding.Default.GetString(tag.Comment);
                    string Genre = Encoding.Default.GetString(tag.Genre);

                    Console.WriteLine(Title);
                    Console.WriteLine(Artist);
                    Console.WriteLine(Album);
                    Console.WriteLine(Year);
                    Console.WriteLine(Comment);
                    Console.WriteLine(Genre);
                    Console.WriteLine();
                }
            }
        }

Playing .mp3 and .wav in Java?

I have other methods for that, the first is :

public static void playAudio(String filePath){

    try{
        InputStream mus = new FileInputStream(new File(filePath));
        AudioStream aud = new AudioStream(mus);
    }catch(Exception e){
        JOptionPane.showMessageDialig(null, "You have an Error");
    }

And the second is :

try{
    JFXPanel x = JFXPanel();
    String u = new File("021.mp3").toURI().toString();
    new MediaPlayer(new Media(u)).play();
} catch(Exception e){
    JOPtionPane.showMessageDialog(null, e);
}

And if we want to make loop to this audio we use this method.

try{
    AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
    ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
    AudioPlayer.player.start(s);
} catch(Exception ex){
    JOPtionPane.showMessageDialog(null, ex);
}

if we want to stop this loop we add this libreries in the try:

AudioPlayer.player.stop(s);

for this third method we add the folowing imports :

import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

Autoplay an audio with HTML5 embed tag while the player is invisible

Sometimes autoplay is needed. Someone once pointed out that the famous Les Paul Google Doodle (2011) required autoplay, even though the sound didn't play until you moused over the guitar strings. If it's done with class and great design it can be beautiful (especially movie websites with immersive design)

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

Streaming Audio from A URL in Android using MediaPlayer?

I guess that you are trying to play an .pls directly or something similar.

try this out:

1: the code

mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

2: the .pls file

This URL is from BBC just as an example. It was an .pls file that on linux i downloaded with

wget http://foo.bar/file.pls

and then i opened with vim (use your favorite editor ;) and i've seen the real URLs inside this file. Unfortunately not all of the .pls are plain text like that.

I've read that 1.6 would not support streaming mp3 over http, but, i've just tested the obove code with android 1.6 and 2.2 and didn't have any issue.

good luck!

What is the difference between smoke testing and sanity testing?

Smoke Testing

  1. Smoke testing is a wide approach where all areas of the software application are tested without getting into too deep

  2. The test cases for smoke testing of the software can be either manual or automated

  3. Smoke testing is done to ensure whether the main functions of the software application are working or not. During smoke testing of the software, we do not go into finer details.

  4. Smoke testing of the software application is done to check whether the build can be accepted for through software testing

  5. This testing is performed by the developers or testers

  6. Smoke testing exercises the entire system from end to end

  7. Smoke testing is like General Health Check Up

  8. Smoke testing is usually documented or scripted

Santy Testing

  1. Sanity software testing is a narrow regression testing with a focus on one or a small set of areas of functionality of the software application.

  2. Sanity test is generally without test scripts or test cases.

  3. Sanity testing is a cursory software testing type. It is done whenever a quick round of software testing can prove that the software application is functioning according to business / functional requirements.

  4. Sanity testing of the software is to ensure whether the requirements are met or not.

  5. Sanity testing is usually performed by testers

  6. Sanity testing exercises only the particular component of the entire system

  7. Sanity Testing is like specialized health check up

  8. Sanity testing is usually not documented and is unscripted

For more visit Link

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

Simple DateTime sql query

You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:

 SELECT *
   FROM TABLENAME
  WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'

See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:

Sql Server string to date conversion

How can I force component to re-render with hooks in React?

Simple code

const forceUpdate = React.useReducer(bool => !bool)[1];

Use:

forceUpdate();

CSS transition fade in

CSS Keyframes support is pretty good these days:

_x000D_
_x000D_
.fade-in {_x000D_
 opacity: 1;_x000D_
 animation-name: fadeInOpacity;_x000D_
 animation-iteration-count: 1;_x000D_
 animation-timing-function: ease-in;_x000D_
 animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
 0% {_x000D_
  opacity: 0;_x000D_
 }_x000D_
 100% {_x000D_
  opacity: 1;_x000D_
 }_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
_x000D_
_x000D_

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

VirtualBox error "Failed to open a session for the virtual machine"

Updating VirtualBox to newest version fixed my issue.

How to compare binary files to check if they are the same?

Diff with the following options would do a binary comparison to check just if the files are different at all and it'd output if the files are the same as well:

diff -qs {file1} {file2}

If you are comparing two files with the same name in different directories, you can use this form instead:

diff -qs {file1} --to-file={dir2}

OS X El Capitan

How to vertically align into the center of the content of a div with defined width/height?

I have researched this a little and from what I have found you have four options:

Version 1: Parent div with display as table-cell

If you do not mind using the display:table-cell on your parent div, you can use of the following options:

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:table-cell;
    vertical-align:middle;
}?

Live DEMO


Version 2: Parent div with display block and content display table-cell

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:block;
}

.content {
    height: 100px;
    width: 100px;
    display:table-cell;
    vertical-align:middle;    
}?

Live DEMO


Version 3: Parent div floating and content div as display table-cell

.area{
    background: red;
    margin:10px;
    text-align: center;
    display:block;
    float: left;
}

.content {
    display:table-cell;
    vertical-align:middle;
    height: 100px;
    width: 100px;
}?

Live DEMO


Version 4: Parent div position relative with content position absolute

The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.

.area{
    position:relative; 
    display:block;
    height:100px;
    width:100px;
    border:1px solid black;
    background:red;
    margin:10px;
}

.content { 
    position:absolute;
    top:50%; 
    height:50%; 
    width:100px;
    margin-top:-25%;
    text-align:center;
}?

Live DEMO

Getting or changing CSS class property with Javascript using DOM style

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

Beautiful way to remove GET-variables with PHP?

Another solution... I find this function more elegant, it will also remove the trailing '?' if the key to remove is the only one in the query string.

/**
 * Remove a query string parameter from an URL.
 *
 * @param string $url
 * @param string $varname
 *
 * @return string
 */
function removeQueryStringParameter($url, $varname)
{
    $parsedUrl = parse_url($url);
    $query = array();

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $query);
        unset($query[$varname]);
    }

    $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
    $query = !empty($query) ? '?'. http_build_query($query) : '';

    return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}

Tests:

$urls = array(
    'http://www.example.com?test=test',
    'http://www.example.com?bar=foo&test=test2&foo2=dooh',
    'http://www.example.com',
    'http://www.example.com?foo=bar',
    'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
    'https://www.example.com/test/test.test?test=test6',
);

foreach ($urls as $url) {
    echo $url. '<br/>';
    echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}

Will output:

http://www.example.com?test=test
http://www.example.com

http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh

http://www.example.com
http://www.example.com

http://www.example.com?foo=bar
http://www.example.com?foo=bar

http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar

https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test

» Run these tests on 3v4l

What's the best way to add a full screen background image in React Native

To handle this use case, you can use the <ImageBackground> component, which has the same props as <Image>, and add whatever children to it you would like to layer on top of it.

Example:

return (
  <ImageBackground source={...} style={{width: '100%', height: '100%'}}>
    <Text>Inside</Text>
  </ImageBackground>
);

For more: ImageBackground | React Native

Note that you must specify some width and height style attributes.

How to add a footer in ListView?

I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.

Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment

Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":

<RelativeLayout>

<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/> 
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->

</RelativeLayout>

How to show progress dialog in Android?

To use ProgressDialog use the below code

ProgressDialog progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please Wait....");

To start the ProgressDialog use

progressdialog.show();

progressdialog.setCancelable(false); is used so that ProgressDialog cannot be cancelled until the work is done.

To stop the ProgressDialog use this code (when your work is finished):

progressdialog.dismiss();`

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size

Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)

# c3p0.properties
c3p0.testConnectionOnCheckout=true

With this configuration each connection is tested before being used. It however might affect the performance of the site.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Try this,

string FilePath=@"C:\mydir\myfile.ext";
string Result=Path.GetFileName(FilePath);//With Extension
string Result=Path.GetFileNameWithoutExtension(FilePath);//Without Extension

Add / remove input field dynamically with jQuery

You need to create the element.

input = jQuery('<input name="myname">');

and then append it to the form.

jQuery('#formID').append(input);

to remove an input you use the remove functionality.

jQuery('#inputid').remove();

This is the basic idea, you may have feildsets that you append it too instead, or maybe append it after a specific element, but this is how to build anything dynamically really.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I also encountered this problem. I found after changing the table storage engine from MyISAM to Innodb, problem solved .

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Convert xlsx file to csv using batch

Try in2csv!

Usage:

in2csv file.xlsx > file.csv

Get first date of current month in java

In order to get a Date (that can be used in JPA later on), I did

Date startOfMonth = Date.from(LocalDate.now().withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.UTC));
  • I take current date LocalDate.now()
  • Move it to first day of the month withDayOfMonth(1)
  • Move it to the sart of the day atStartOfDay() to get rid of hours and minutes
  • and deal with the TimeZone issues by changing it into an Instant with the "right" ZoneOffset.

Steps to upload an iPhone application to the AppStore

Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.

Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC

Creating a "Hello World" WebSocket example

WebSockets are implemented with a protocol that involves handshake between client and server. I don't imagine they work very much like normal sockets. Read up on the protocol, and get your application to talk it. Alternatively, use an existing WebSocket library, or .Net4.5beta which has a WebSocket API.

std::cin input with spaces?

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

THE C++ WAY

gets is removed in c++11.

[Recommended]:You can use getline(cin,name) which is in string.h or cin.getline(name,256) which is in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}

urlencoded Forward slash is breaking URL

You can use %2F if using it this way:
?param1=value1&param2=value%2Fvalue

but if you use /param1=value1/param2=value%2Fvalue it will throw an error.

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Count the number of occurrences of each letter in string

for (int i=0;i<word.length();i++){
         int counter=0;
         for (int j=0;j<word.length();j++){
             if(word.charAt(i)==word.charAt(j))
             counter++;
             }// inner for
             JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
         }// outer for

pip install - locale.Error: unsupported locale setting

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I had a similar issue which i solved by making two changes

  1. added below entry in application.yaml file

    spring: jackson: serialization.write_dates_as_timestamps: false

  2. add below two annotations in pojo

    1. @JsonDeserialize(using = LocalDateDeserializer.class)
    2. @JsonSerialize(using = LocalDateSerializer.class)

    sample example

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Customer { //your fields ... @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) protected LocalDate birthdate; }

then the following json requests worked for me

  1. sample request format as string

{ "birthdate": "2019-11-28" }

  1. sample request format as array

{ "birthdate":[2019,11,18] }

Hope it helps!!

Run a Command Prompt command from Desktop Shortcut

Using the Drag and Drop method

  1. From the windows search bar type in cmd to pull up the windows bar operation.
  2. When the command line option is shown, right click it and select Open File Location.
  3. The file explorer opens and the shortcut link is highlighted in the folder. If it is not highlighted, then select it.
  4. Hold down the Control key and using the mouse drag the shortcut to the desktop. If you don't see Copy to Desktop while dragging and before dropping, then push down and hold the Control key until you see the message.
  5. Drop the link on the desktop.
  6. Change properties as needed.

What are the rules about using an underscore in a C++ identifier?

From MSDN:

Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.

This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.

This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.

See also this question.

How do I generate random numbers in Dart?

Not able to comment because I just created this account, but I wanted to make sure to point out that @eggrobot78's solution works, but it is exclusive in dart so it doesn't include the last number. If you change the last line to "r = min + rnd.nextInt(max - min + 1);", then it should include the last number as well.

Explanation:

max = 5;
min = 3;
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//max - min is 2
//nextInt is exclusive so nextInt will return 0 through 1
//3 is added so the line will give a number between 3 and 4
//if you add the "+ 1" then it will return a number between 3 and 5

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

How do I change the default application icon in Java?

Try This write after

initcomponents();

setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));

React Native Change Default iOS Simulator Device

1) Rename your simulator, If simulator with same name but different iOS version

Xcode -> Window -> Devices and Simulators -> Simulators.

enter image description here

2) Open your react native project folder

3) Edit package.json

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest",
    "flow": "node_modules/.bin/flow",
    "start-iphone6": "react-native run-ios --simulator \"iPhone 6 11.3\""
}

4) npm run start-iphone6

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

What do you want to do with this unique ID? Maybe you can do what you want without this ID.

The MAC address maybe is one option but this is not an trusted unique ID because the user can change the MAC address of a computer.

To get the motherboard or processor ID check on this link.

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Difference between Console.Read() and Console.ReadLine()?

The difference of Read(),ReadLine() and Readkey() method are given below:

Read():This is static method in Console class:

int i = Console.Read();//it always return int value.
Console.WriteLine(i);

paste above code and give input '1', and the output will be 49. That is Console.Read give int value but that value will be the ASCII value of that.

ReadLine():

string s= Console.ReadLine();//it always return string value.
Console.WriteLine(s);

It gives the string as it is given in the input stream.

ReadKey(): this method is used to hold the output screen.when any key is press. Read() and ReadLine() is used the enter key for exit.

How to get the new value of an HTML input after a keypress has modified it?

<html>
    <head>
        <script>
        function callme(field) {
            alert("field:" + field.value);
        }
        </script>
    </head>
    <body>
        <form name="f1">
            <input type="text" onkeyup="callme(this);" name="text1">
        </form>
    </body>
</html>

It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.

Refresh/reload the content in Div using jquery/ajax

$("#mydiv").load(location.href + " #mydiv");

Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.

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

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

What does the "assert" keyword do?

assert is a debugging tool that will cause the program to throw an AssertionFailed exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false. Generally speaking, assert should not be used in production code

Convert string to JSON Object

Quick answer, this eval work:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

Ruby: How to post a file via HTTP as multipart/form-data?

Fast forward to 2017, ruby stdlib net/http has this built-in since 1.9.3

Net::HTTPRequest#set_form): Added to support both application/x-www-form-urlencoded and multipart/form-data.

https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form

We can even use IO which does not support :size to stream the form data.

Hoping that this answer can really help someone :)

P.S. I only tested this in ruby 2.3.1

Android: how do I check if activity is running?

If you are interested in the lifecycle state of the specific instance of the activity, siliconeagle's solution looks correct except that the new "active" variable should be an instance variable, rather than static.

Encode URL in JavaScript?

Nothing worked for me. All I was seeing was the HTML of the login page, coming back to the client side with code 200. (302 at first but the same Ajax request loading login page inside another Ajax request, which was supposed to be a redirect rather than loading plain text of the login page).

In the login controller, I added this line:

Response.Headers["land"] = "login";

And in the global Ajax handler, I did this:

$(function () {
    var $document = $(document);
    $document.ajaxSuccess(function (e, response, request) {
        var land = response.getResponseHeader('land');
        var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
        if(land) {
            if (land.toString() === 'login') {
                window.location = redrUrl;
            }
        }
    });
});

Now I don't have any issue, and it works like a charm.

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

How to use 'hover' in CSS

I was working on a nice defect last time and was wondering more about how to use properly hover property for A tag link and for IE browser. A strange thing for me was that IE was not able to capture A tag link element based on a simple A selector. So, I found out how to even force capturing A tag element and I spotted that we must use more specifc CSS selector. Here is an example below - It works perfect:

li a[href]:hover {...}

How to get a dependency tree for an artifact?

I know this post is quite old, but still, if anyone using IntelliJ any want to see dependency tree directly in IDE then they can install Maven Helper Plugin plugin.

Once installed open pom.xml and you would able to see Dependency Analyze tab like below. It also provides option to see dependency that is conflicted only and also as a tree structure.

enter image description here

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

How are people unit testing with Entity Framework 6, should you bother?

This is a topic I'm very interested in. There are many purists who say that you shouldn't test technologies such as EF and NHibernate. They are right, they're already very stringently tested and as a previous answer stated it's often pointless to spend vast amounts of time testing what you don't own.

However, you do own the database underneath! This is where this approach in my opinion breaks down, you don't need to test that EF/NH are doing their jobs correctly. You need to test that your mappings/implementations are working with your database. In my opinion this is one of the most important parts of a system you can test.

Strictly speaking however we're moving out of the domain of unit testing and into integration testing but the principles remain the same.

The first thing you need to do is to be able to mock your DAL so your BLL can be tested independently of EF and SQL. These are your unit tests. Next you need to design your Integration Tests to prove your DAL, in my opinion these are every bit as important.

There are a couple of things to consider:

  1. Your database needs to be in a known state with each test. Most systems use either a backup or create scripts for this.
  2. Each test must be repeatable
  3. Each test must be atomic

There are two main approaches to setting up your database, the first is to run a UnitTest create DB script. This ensures that your unit test database will always be in the same state at the beginning of each test (you may either reset this or run each test in a transaction to ensure this).

Your other option is what I do, run specific setups for each individual test. I believe this is the best approach for two main reasons:

  • Your database is simpler, you don't need an entire schema for each test
  • Each test is safer, if you change one value in your create script it doesn't invalidate dozens of other tests.

Unfortunately your compromise here is speed. It takes time to run all these tests, to run all these setup/tear down scripts.

One final point, it can be very hard work to write such a large amount of SQL to test your ORM. This is where I take a very nasty approach (the purists here will disagree with me). I use my ORM to create my test! Rather than having a separate script for every DAL test in my system I have a test setup phase which creates the objects, attaches them to the context and saves them. I then run my test.

This is far from the ideal solution however in practice I find it's a LOT easier to manage (especially when you have several thousand tests), otherwise you're creating massive numbers of scripts. Practicality over purity.

I will no doubt look back at this answer in a few years (months/days) and disagree with myself as my approaches have changed - however this is my current approach.

To try and sum up everything I've said above this is my typical DB integration test:

[Test]
public void LoadUser()
{
  this.RunTest(session => // the NH/EF session to attach the objects to
  {
    var user = new UserAccount("Mr", "Joe", "Bloggs");
    session.Save(user);
    return user.UserID;
  }, id => // the ID of the entity we need to load
  {
     var user = LoadMyUser(id); // load the entity
     Assert.AreEqual("Mr", user.Title); // test your properties
     Assert.AreEqual("Joe", user.Firstname);
     Assert.AreEqual("Bloggs", user.Lastname);
  }
}

The key thing to notice here is that the sessions of the two loops are completely independent. In your implementation of RunTest you must ensure that the context is committed and destroyed and your data can only come from your database for the second part.

Edit 13/10/2014

I did say that I'd probably revise this model over the upcoming months. While I largely stand by the approach I advocated above I've updated my testing mechanism slightly. I now tend to create the entities in in the TestSetup and TestTearDown.

[SetUp]
public void Setup()
{
  this.SetupTest(session => // the NH/EF session to attach the objects to
  {
    var user = new UserAccount("Mr", "Joe", "Bloggs");
    session.Save(user);
    this.UserID =  user.UserID;
  });
}

[TearDown]
public void TearDown()
{
   this.TearDownDatabase();
}

Then test each property individually

[Test]
public void TestTitle()
{
     var user = LoadMyUser(this.UserID); // load the entity
     Assert.AreEqual("Mr", user.Title);
}

[Test]
public void TestFirstname()
{
     var user = LoadMyUser(this.UserID);
     Assert.AreEqual("Joe", user.Firstname);
}

[Test]
public void TestLastname()
{
     var user = LoadMyUser(this.UserID);
     Assert.AreEqual("Bloggs", user.Lastname);
}

There are several reasons for this approach:

  • There are no additional database calls (one setup, one teardown)
  • The tests are far more granular, each test verifies one property
  • Setup/TearDown logic is removed from the Test methods themselves

I feel this makes the test class simpler and the tests more granular (single asserts are good)

Edit 5/3/2015

Another revision on this approach. While class level setups are very helpful for tests such as loading properties they are less useful where the different setups are required. In this case setting up a new class for each case is overkill.

To help with this I now tend to have two base classes SetupPerTest and SingleSetup. These two classes expose the framework as required.

In the SingleSetup we have a very similar mechanism as described in my first edit. An example would be

public TestProperties : SingleSetup
{
  public int UserID {get;set;}

  public override DoSetup(ISession session)
  {
    var user = new User("Joe", "Bloggs");
    session.Save(user);
    this.UserID = user.UserID;
  }

  [Test]
  public void TestLastname()
  {
     var user = LoadMyUser(this.UserID); // load the entity
     Assert.AreEqual("Bloggs", user.Lastname);
  }

  [Test]
  public void TestFirstname()
  {
       var user = LoadMyUser(this.UserID);
       Assert.AreEqual("Joe", user.Firstname);
  }
}

However references which ensure that only the correct entites are loaded may use a SetupPerTest approach

public TestProperties : SetupPerTest
{
   [Test]
   public void EnsureCorrectReferenceIsLoaded()
   {
      int friendID = 0;
      this.RunTest(session =>
      {
         var user = CreateUserWithFriend();
         session.Save(user);
         friendID = user.Friends.Single().FriendID;
      } () =>
      {
         var user = GetUser();
         Assert.AreEqual(friendID, user.Friends.Single().FriendID);
      });
   }
   [Test]
   public void EnsureOnlyCorrectFriendsAreLoaded()
   {
      int userID = 0;
      this.RunTest(session =>
      {
         var user = CreateUserWithFriends(2);
         var user2 = CreateUserWithFriends(5);
         session.Save(user);
         session.Save(user2);
         userID = user.UserID;
      } () =>
      {
         var user = GetUser(userID);
         Assert.AreEqual(2, user.Friends.Count());
      });
   }
}

In summary both approaches work depending on what you are trying to test.

Disabled href tag

I see there are already a ton of answers posted here, but I don’t think there’s any clear one yet that combines the already mentioned approaches into the one I’ve found to work. This is to make the link both appear disabled, and also not redirect the user to another page.

This answer assumes you’re using jquery and bootstrap, and uses another property to temporarily store the href property while disabled.

//situation where link enable/disable should be toggled
function toggle_links(enable) {
    if (enable) {
        $('.toggle-link')
        .removeClass('disabled')
        .prop('href', $(this).attr('data-href'))
    }
    else {
        $('.toggle-link')
        .addClass('disabled')
        .prop('data-href', $(this).prop('href'))
        .prop('href','#')
    }
a.disabled {
  cursor: default;
}

Defined Edges With CSS3 Filter Blur

You can try adding the border on an other element:

DOM:

<div><img src="#" /></div>

CSS:

div {
   border: 1px solid black;
}
img {
    filter: blur(5px);
}

How to get IntPtr from byte[] in C#

Here's a twist on @user65157's answer (+1 for that, BTW):

I created an IDisposable wrapper for the pinned object:

class AutoPinner : IDisposable
{
   GCHandle _pinnedArray;
   public AutoPinner(Object obj)
   {
      _pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
   }
   public static implicit operator IntPtr(AutoPinner ap)
   {
      return ap._pinnedArray.AddrOfPinnedObject(); 
   }
   public void Dispose()
   {
      _pinnedArray.Free();
   }
}

then use it like thusly:

using (AutoPinner ap = new AutoPinner(MyManagedObject))
{
   UnmanagedIntPtr = ap;  // Use the operator to retrieve the IntPtr
   //do your stuff
}

I found this to be a nice way of not forgetting to call Free() :)

Can we rely on String.isEmpty for checking null condition on a String in Java?

No, the String.isEmpty() method looks as following:

public boolean isEmpty() {
    return this.value.length == 0;
}

as you can see it checks the length of the string so you definitely have to check if the string is null before.

How to disable GCC warnings for a few lines of code

I know the question is about GCC, but for people looking for how to do this in other and/or multiple compilers…

TL;DR

You might want to take a look at Hedley, which is a public-domain single C/C++ header I wrote which does a lot of this stuff for you. I'll put a quick section about how to use Hedley for all this at the end of this post.

Disabling the warning

#pragma warning (disable: …) has equivalents in most compilers:

  • MSVC: #pragma warning(disable:4996)
  • GCC: #pragma GCC diagnostic ignored "-W…" where the ellipsis is the name of the warning; e.g., #pragma GCC diagnostic ignored "-Wdeprecated-declarations.
  • clang: #pragma clang diagnostic ignored "-W…". The syntax is basically the same as GCC's, and many of the warning names are the same (though many aren't).
  • Intel C Compiler: Use the MSVC syntax, but keep in mind that warning numbers are totally different. Example: #pragma warning(disable:1478 1786).
  • PGI/NVidia: There is a diag_suppress pragma: #pragma diag_suppress 1215,1444. Note that all warning numbers increased by one in 20.7 (the first NV HPC release).
  • TI: There is a diag_suppress pragma with the same syntax (but different warning numbers!) as PGI: pragma diag_suppress 1291,1718
  • Oracle Developer Studio (suncc): there is an error_messages pragma. Annoyingly, the warnings are different for the C and C++ compilers. Both of these disable basically the same warnings:
    • C: #pragma error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)
    • C++: #pragma error_messages(off,symdeprecated,symdeprecated2)
  • IAR: also uses diag_suppress like PGI and TI, but the syntax is different. Some of the warning numbers are the same, but I others have diverged: #pragma diag_suppress=Pe1444,Pe1215
  • Pelles C: similar to MSVC, though again the numbers are different #pragma warn(disable:2241)

For most compilers it is often a good idea to check the compiler version before trying to disable it, otherwise you'll just end up triggering another warning. For example, GCC 7 added support for the -Wimplicit-fallthrough warning, so if you care about GCC before 7 you should do something like

#if defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

For clang and compilers based on clang such as newer versions of XL C/C++ and armclang, you can check to see if the compiler knows about a particular warning using the __has_warning() macro.

#if __has_warning("-Wimplicit-fallthrough")
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#endif

Of course you also have to check to see if the __has_warning() macro exists:

#if defined(__has_warning)
#  if __has_warning("-Wimplicit-fallthrough")
#    pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#  endif
#endif

You may be tempted to do something like

#if !defined(__has_warning)
#  define __has_warning(warning)
#endif

So you can use __has_warning a bit more easily. Clang even suggests something similar for the __has_builtin() macro in their manual. Do not do this. Other code may check for __has_warning and fall back on checking compiler versions if it doesn't exist, and if you define __has_warning you'll break their code. The right way to do this is to create a macro in your namespace. For example:

#if defined(__has_warning)
#  define MY_HAS_WARNING(warning) __has_warning(warning)
#else
#  define MY_HAS_WARNING(warning) (0)
#endif

Then you can do stuff like

#if MY_HAS_WARNING(warning)
#  pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#elif defined(__GNUC__) && (__GNUC__ >= 7)
#  pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif

Pushing and popping

Many compilers also support a way to push and pop warnings onto a stack. For example, this will disable a warning on GCC for one line of code, then return it to its previous state:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
call_deprecated_function();
#pragma GCC diagnostic pop

Of course there isn't a lot of agreement across compilers about the syntax:

  • GCC 4.6+: #pragma GCC diagnostic push / #pragma GCC diagnostic pop
  • clang: #pragma clang diagnostic push / #pragma diagnostic pop
  • Intel 13+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)
  • MSVC 15+ (VS 9.0 / 2008): #pragma warning(push) / #pragma warning(pop)
  • ARM 5.6+: #pragma push / #pragma pop
  • TI 8.1+: #pragma diag_push / #pragma diag_pop
  • Pelles C 2.90+ (and probably earlier): #pragma warning(push) / #pragma warning(pop)

If memory serves, for some very old versions of GCC (like 3.x, IIRC) the push/pop pragmas had to be outside of the function.

Hiding the gory details

For most compilers it's possible to hide the logic behind macros using _Pragma, which was introduced in C99. Even in non-C99 mode, most compilers support _Pragma; the big exception is MSVC, which has its own __pragma keyword with a different syntax. The standard _Pragma takes a string, Microsoft's version doesn't:

#if defined(_MSC_VER)
#  define PRAGMA_FOO __pragma(foo)
#else
#  define PRAGMA_FOO _Pragma("foo")
#endif
PRAGMA_FOO

Is roughly equivalent, once preprocessed, to

#pragma foo

This lets us create macros so we can write code like

MY_DIAGNOSTIC_PUSH
MY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated_function();
MY_DIAGNOSTIC_POP

And hide away all the ugly version checks in the macro definitions.

The easy way: Hedley

Now that you understand the mechanics of how to do stuff like this portably while keeping your code clean, you understand what one of my projects, Hedley does. Instead of digging through tons of documentation and/or installing as many versions of as many compilers as you can to test with, you can just include Hedley (it is a single public domain C/C++ header) and be done with it. For example:

#include "hedley.h"

HEDLEY_DIAGNOSTIC_PUSH
HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated();
HEDLEY_DIAGNOSTIC_POP

Will disable the warning about calling a deprecated function on GCC, clang, ICC, PGI, MSVC, TI, IAR, ODS, Pelles, and possibly others (I probably won't bother updating this answer as I update Hedley). And, on compilers which aren't known to work, the macros will be preprocessed away to nothing, so your code will continue to work with any compiler. Of course HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED isn't the only warning Hedley knows about, nor is disabling warnings all Hedley can do, but hopefully you get the idea.

MySQL config file location - redhat linux server

From the header of '/etc/mysql/my.cnf':

MariaDB programs look for option files in a set of
locations which depend on the deployment platform.
[...] For information about these locations, do:
'my_print_defaults --help' and see what is printed under
"Default options are read from the following files in the given order:"
More information at: http://dev.mysql.com/doc/mysql/en/option-files.html

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

MySQL Update Column +1?

update post set count = count + 1 where id = 101

Check if a radio button is checked jquery

if($("input:radio[name=test]").is(":checked")){
  //Code to append goes here
}

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

PHP Warning: Unknown: failed to open stream

In my case the group _www that apache uses was missing in the folder's access list, so first I had to add the missing group, like so:

sudo chown -R _www ~/path-to-folder

Change _www to whatever user or group that apache is running as.

Find out apache's user/group using apachectl -S

The output is huge, but look at the very end something like:

User: name="_www"
Group: name="_www"

Is it possible to access an SQLite database from JavaScript?

IMHO, the best way is to call Python using POST via AJAX and do everything you need to do with the DB within Python, then return the result to the javascript. json and sqlite support in Python is awesome and it's 100% built-in within even slightly recent versions of Python, so there is no "install this, install that" pain. In Python:

import sqlite3
import json

...that's all you need. It's part of every Python distribution.

@Sedrick Jefferson asked for examples, so (somewhat tardily) I have written up a stand-alone back-and-forth between Javascript and Python here.

Chrome: console.log, console.debug are not working

Make sure the filter box is empty

How to convert int to NSString?

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

display Java.util.Date in a specific format

It makes no sense, but:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String

Regular expression to extract text between square brackets

(?<=\[).*?(?=\]) works good as per explanation given above. Here's a Python example:

import re 
str = "Pagination.go('formPagination_bottom',2,'Page',true,'1',null,'2013')"
re.search('(?<=\[).*?(?=\])', str).group()
"'formPagination_bottom',2,'Page',true,'1',null,'2013'"

Get first day of week in PHP?

You can use Carbon library as well

$dateString = '02-21-2015'; // example in format MM-dd-yyyy
$date = Carbon::createFromFormat('m-d-Y', $dateString);
$date->hour(0)->minute(0)->second(0)->startOfWeek();
$dateString = $date->Format('m-d-Y'); // and you have got a string value "02-16-2015"

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

jQuery checkbox event handling

I have try the code from first answer, it not working but I have play around and this work for me

$('#vip').change(function(){
    if ($(this).is(':checked')) {
        alert('checked');
    } else {
        alert('uncheck');
    }
});

Basic HTTP and Bearer Token Authentication

With nginx you can send both tokens like this (even though it's against the standard):

Authorization: Basic basic-token,Bearer bearer-token

This works as long as the basic token is first - nginx successfully forwards it to the application server.

And then you need to make sure your application can properly extract the Bearer from the above string.

Forcing to download a file using PHP

.htaccess Solution

To brute force all CSV files on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

ojdbc14.jar vs. ojdbc6.jar

Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

In my context, just developed a class abstraction. When my application is launched, i check if localStorage is working by calling getStorage(). This function also return :

  • either localStorage if localStorage is working
  • or an implementation of a custom class LocalStorageAlternative

In my code i never call localStorage directly. I call cusStoglobal var, i had initialised by calling getStorage().

This way, it works with private browsing or specific Safari versions

function getStorage() {

    var storageImpl;

     try { 
        localStorage.setItem("storage", ""); 
        localStorage.removeItem("storage");
        storageImpl = localStorage;
     }
     catch (err) { 
         storageImpl = new LocalStorageAlternative();
     }

    return storageImpl;

}

function LocalStorageAlternative() {

    var structureLocalStorage = {};

    this.setItem = function (key, value) {
        structureLocalStorage[key] = value;
    }

    this.getItem = function (key) {
        if(typeof structureLocalStorage[key] != 'undefined' ) {
            return structureLocalStorage[key];
        }
        else {
            return null;
        }
    }

    this.removeItem = function (key) {
        structureLocalStorage[key] = undefined;
    }
}

cusSto = getStorage();

Create a variable name with "paste" in R?

In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.

lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))

Remove quotes from String in Python

To add to @Christian's comment:

Replace all single or double quotes in a string:

s = "'asdfa sdfa'"

import re
re.sub("[\"\']", "", s)

Why is synchronized block better than synchronized method?

It's not a matter of better, just different.

When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:

public synchronized int getCount() {
    // ...
}

This is just like you wrote this.

public int getCount() {
    synchronized (this) {
        // ...
    }
}

If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.

How to get a div to resize its height to fit container?

You probably are going to want to use the following declaration:

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

Finding the length of an integer in C

int returnIntLength(int value){
    int counter = 0;
    if(value < 0)
    {
        counter++;
        value = -value;
    }
    else if(value == 0)
        return 1;

    while(value > 0){
        value /= 10;
        counter++;
    }

    return counter;
}

I think this method is well suited for this task:

value and answers:

  • -50 -> 3 //it will count - as one character as well if you dont want to count minus then remove counter++ from 5th line.

  • 566666 -> 6

  • 0 -> 1

  • 505 -> 3

Ruby on Rails: Clear a cached page

More esoteric ways:

Rails.cache.delete_matched("*")

For Redis:

Redis.new.keys.each{ |key| Rails.cache.delete(key) }

Java Command line arguments

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}

Create session factory in Hibernate 4

Configuration hibConfiguration = new Configuration()
            .addResource("wp4core/hibernate/config/table.hbm.xml")
            .configure();       

serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(hibConfiguration.getProperties())
            .buildServiceRegistry();

sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
session = sessionFactory.withOptions().openSession();

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

Concatenate multiple files but include filename as section headers

  • AIX 7.1 ksh

... glomming onto those who've already mentioned head works for some of us:

$ r head
head file*.txt
==> file1.txt <==
xxx
111

==> file2.txt <==
yyy
222
nyuk nyuk nyuk

==> file3.txt <==
zzz
$

My need is to read the first line; as noted, if you want more than 10 lines, you'll have to add options (head -9999, etc).

Sorry for posting a derivative comment; I don't have sufficient street cred to comment/add to someone's comment.

Generating a drop down list of timezones with PHP

I did this:

php -r "echo json_encode(array_combine(DateTimeZone::listIdentifiers(DateTimeZone::ALL), DateTimeZone::listIdentifiers(DateTimeZone::ALL)));" > list-of-timezones.json

Transpose a data frame

df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

How to access a preexisting collection with Mongoose?

Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .

var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {

conn.db.collection(" collection ", function(err, collection){

    collection.find({}).toArray(function(err, data){
        console.log(data); // data printed in console
    })
});

});

Happy to Help. by RTTSS.

Spring Data: "delete by" is supported?

here follows my 2 cents. You can also use native queries, like:

@Modifying
@Query(value="delete from rreo r where r.cod_ibge = ?1 and r.exercicio= ?2", nativeQuery = true)
void deleteByParameters(Integer codIbge, Integer exercicio);

JQuery - Get select value

val() returns the value of the <select> element, i.e. the value attribute of the selected <option> element.

Since you actually want the inner text of the selected <option> element, you should match that element and use text() instead:

var nationality = $("#dancerCountry option:selected").text();

How can I declare and use Boolean variables in a shell script?

This is a speed test about different ways to test "Boolean" values in Bash:

#!/bin/bash
rounds=100000

b=true # For true; b=false for false
type -a true
time for i in $(seq $rounds); do command $b; done
time for i in $(seq $rounds); do $b; done
time for i in $(seq $rounds); do [ "$b" == true ]; done
time for i in $(seq $rounds); do test "$b" == true; done
time for i in $(seq $rounds); do [[ $b == true ]]; done

b=x; # Or any non-null string for true; b='' for false
time for i in $(seq $rounds); do [ "$b" ]; done
time for i in $(seq $rounds); do [[ $b ]]; done

b=1 # Or any non-zero integer for true; b=0 for false
time for i in $(seq $rounds); do ((b)); done

It would print something like

true is a shell builtin
true is /bin/true

real    0m0,815s
user    0m0,767s
sys     0m0,029s

real    0m0,562s
user    0m0,509s
sys     0m0,022s

real    0m0,829s
user    0m0,782s
sys     0m0,008s

real    0m0,782s
user    0m0,730s
sys     0m0,015s

real    0m0,402s
user    0m0,391s
sys     0m0,006s

real    0m0,668s
user    0m0,633s
sys     0m0,008s

real    0m0,344s
user    0m0,311s
sys     0m0,016s

real    0m0,367s
user    0m0,347s
sys     0m0,017s

Is it possible to Turn page programmatically in UIPageViewController?

This code worked nicely for me, thanks.

This is what i did with it. Some methods for stepping forward or backwards and one for going directly to a particular page. Its for a 6 page document in portrait view. It will work ok if you paste it into the implementation of the RootController of the pageViewController template.

-(IBAction)pageGoto:(id)sender {

    //get page to go to
    NSUInteger pageToGoTo = 4;

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers   objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //get the page(s) to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo - 1) storyboard:self.storyboard];

    DataViewController *secondPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, secondPageViewController, nil];


    //check which direction to animate page turn then turn page accordingly
    if (retreivedIndex < (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
    }

    if (retreivedIndex > (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
    }

}


-(IBAction)pageFoward:(id)sender {

    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex < 5){

        //get the page to go to
        DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex + 1) storyboard:self.storyboard];

        //put it(or them if in landscape view) in an array
        NSArray *theViewControllers = nil;    
        theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

        //add page view
        [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    }

}


-(IBAction)pageBack:(id)sender {


    //get current index of current page
    DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];

    //check that current page isn't first page
    if (retreivedIndex > 0){

    //get the page to go to
    DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex - 1) storyboard:self.storyboard];

    //put it(or them if in landscape view) in an array
    NSArray *theViewControllers = nil;    
    theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];

    //add page view
    [self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];

    }

}

print arraylist element?

First make sure that Dog class implements the method public String toString() then use

System.out.println(list.get(index))

where index is the position inside the list. Of course since you provide your implementation you can decide how dog prints itself.

How to redirect to a 404 in Rails?

I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:

class AdminController < ApplicationController
  before_action :blackhole_admin

  private

  def blackhole_admin
    return if current_user.admin?

    raise ActionController::RoutingError, 'Not Found'
  rescue ActionController::RoutingError
    render file: "#{Rails.root}/public/404", layout: false, status: :not_found
  end
end

Error:java: invalid source release: 8 in Intellij. What does it mean?

Check your pom.xml first (if you have one)
Check your module's JDK dependancy. Make sure that it is 1.8
To do this,go to Project Structure -> SDK's
Add the path to where you have stored 1.8 (jdk1.8.0_45.jdk in my case)
Apply the changes
Now, go to Project Structure ->Modules
Change the Module SDK to 1.8
Apply the changes

Voila! You're done

C++ String array sorting

As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful

bool cmp(string a, string b)
{
if(a.compare(b) > 0)
    return true;
else
    return false;
}

int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);

for(int i = 0; i < length; i++)
    cout << words[i] << " ";
cout << endl;
    // output will be: this test is a 

}

If you want to reverse the order of sorting just modify the sign in the cmp function.

Hope this is helpful :)

Cheers!!!

TCPDF output without saving file

      $filename= time()."pdf"; 
    //$filelocation = "C://xampp/htdocs/Nilesh/Projects/mkGroup/admin/PDF";

     $filelocation = "/pdf uplaod path/";
     $fileNL = $filelocation."/".$filename;

       $pdf->Output($fileNL,'F');
       $pdf->Output($filename, 'S');

Parse String date in (yyyy-MM-dd) format

I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .

 String date ="2016-05-01";
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 Date parsed = format.parse(date);
 java.sql.Date sql = new java.sql.Date(parsed.getTime());

sql it's my output in date format

How does Java handle integer underflows and overflows and how would you check for it?

It wraps around.

e.g:

public class Test {

    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        int j = Integer.MIN_VALUE;

        System.out.println(i+1);
        System.out.println(j-1);
    }
}

prints

-2147483648
2147483647

How do you easily create empty matrices javascript?

better. that exactly will work.

let mx = Matrix(9, 9);

function Matrix(w, h){
    let mx = Array(w);
    for(let i of mx.keys())
        mx[i] = Array(h);
    return mx;
}


what was shown

Array(9).fill(Array(9)); // Not correctly working

It does not work, because all cells are fill with one array

Execute a shell script in current shell with sudo permission

I'm not sure if this breaks any rules but

sudo bash script.sh

seems to work for me.

No line-break after a hyphen

IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.

As I could not use the CSS answer specified by Deb I instead opted to use no break tags.

<nobr>e-mail</nobr>

In addition I found a specific scenario that caused IE8/9 to break on a hyphen.

  • A string contains words separated by non-breaking spaces - &nbsp;
  • Width is limited
  • Contains a dash

IE renders it like this.

Example of hyphen breaking in IE8/9

The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta charset="utf-8"/>
        <style>
            body { padding: 20px; }
            div { width: 300px; border: 1px solid gray; }
        </style>
    </head>
    <body>
        <div>      
            <p>If&nbsp;there&nbsp;is&nbsp;a&nbsp;-&nbsp;and&nbsp;words&nbsp;are&nbsp;separated&nbsp;by&nbsp;the&nbsp;whitespace&nbsp;code&nbsp;&amp;nbsp;&nbsp;then&nbsp;IE&nbsp;will&nbsp;wrap&nbsp;on&nbsp;the&nbsp;dash.</p>
        </div>
    </body>
</html>

How do I prevent people from doing XSS in Spring MVC?

Instead of relying only on <c:out />, an antixss library should also be used, which will not only encode but also sanitize malicious script in input. One of the best library available is OWASP Antisamy, it's highly flexible and can be configured(using xml policy files) as per requirement.

For e.g. if an application supports only text input then most generic policy file provided by OWASP can be used which sanitizes and removes most of the html tags. Similarly if application support html editors(such as tinymce) which need all kind of html tags, a more flexible policy can be use such as ebay policy file

HTML Drag And Drop On Mobile Devices

Jquery Touch Punch is great but what it also does is disable all the controls on the draggable div so to prevent this you have to alter the lines... (at the time of writing - line 75)

change

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])){

to read

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0]) || event.originalEvent.target.localName === 'textarea'
        || event.originalEvent.target.localName === 'input' || event.originalEvent.target.localName === 'button' || event.originalEvent.target.localName === 'li'
        || event.originalEvent.target.localName === 'a'
        || event.originalEvent.target.localName === 'select' || event.originalEvent.target.localName === 'img') {

add as many ors as you want for each of the elements you want to 'unlock'

Hope that helps someone

Google Chrome form autofill and its yellow background

The final solution:

$(document).ready(function(){
    var contadorInterval = 0;
    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0)
    {
        var _interval = window.setInterval(function ()
        {
            var autofills = $('input:-webkit-autofill');
            if (autofills.length > 0)
            {
                window.clearInterval(_interval); // stop polling
                autofills.each(function()
                {
                    var clone = $(this).clone(true, true);
                    $(this).after(clone).remove();
                    setTimeout(function(){
//                        $("#User").val('');
                        $("#Password").val('');
                    },10);
                });
            }
            contadorInterval++;
            if(contadorInterval > 50) window.clearInterval(_interval); // stop polling
        }, 20);
    }else{
        setTimeout(function(){
//            $("#User").val('');
            $("#Password").val('');
        },100);
    }
});

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

You have to add the android:screenOrientation="portrait" directive in your AndroidManifest.xml. This is to be done in your <activity> tag.

In addition, the Android Developers guide states that :

[...] you should also explicitly declare that your application requires either portrait or landscape orientation with the element. For example, <uses-feature android:name="android.hardware.screen.portrait" />.

how to remove json object key and value.?

delete operator is used to remove an object property.

delete operator does not returns the new object, only returns a boolean: true or false.

In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean value.

How to remove Json object specific key and its value ?

You just need to know the property name in order to delete it from the object's properties.

delete myjsonobj['otherIndustry'];

_x000D_
_x000D_
let myjsonobj = {
  "employeeid": "160915848",
  "firstName": "tet",
  "lastName": "test",
  "email": "[email protected]",
  "country": "Brasil",
  "currentIndustry": "aaaaaaaaaaaaa",
  "otherIndustry": "aaaaaaaaaaaaa",
  "currentOrganization": "test",
  "salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
_x000D_
_x000D_
_x000D_

If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.

_x000D_
_x000D_
let value="test";
let myjsonobj = {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "[email protected]",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
  if (myjsonobj[key] === value) {
    delete myjsonobj[key];
  }
});
console.log(myjsonobj);
_x000D_
_x000D_
_x000D_

Batch file: Find if substring is in string (not in a file)

You can pipe the source string to findstr and check the value of ERRORLEVEL to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:

::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off

echo.%2 | findstr /C:"%1" 1>nul

if errorlevel 1 (
  echo. got one - pattern not found
) ELSE (
  echo. got zero - found pattern
)

When this is run in CMD.EXE, we get:

C:\DemoDev>y pqrs "abc def pqr 123"
 got one - pattern not found

C:\DemoDev>y pqr "abc def pqr 123" 
 got zero - found pattern

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

What is Vim recording and how can it be disabled?

You start recording by q<letter> and you can end it by typing q again.

Recording is a really useful feature of Vim.

It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...

One of the best feature of Vim IMHO.

How can I get the values of data attributes in JavaScript code?

You need to access the dataset property:

document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

Getting unique items from a list

Use a HashSet<T>. For example:

var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
    Console.WriteLine(s);

prints

A
B
D
C

Local variable referenced before assignment?

In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

test1 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()

However, if you only need to read the global variable you can print it without using the keyword global, like so:

test1 = 0
def testFunc():
     print test1 
testFunc()

But whenever you need to modify a global variable you must use the keyword global.

Best way to convert text files between character sets?

Use this Python script: https://github.com/goerz/convert_encoding.py Works on any platform. Requires Python 2.7.

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Rounding float in Ruby

When displaying, you can use (for example)

>> '%.2f' % 2.3465
=> "2.35"

If you want to store it rounded, you can use

>> (2.3465*100).round / 100.0
=> 2.35

Remove non-utf8 characters from string

Slightly different to the question, but what I am doing is to use HtmlEncode(string),

pseudo code here

var encoded = HtmlEncode(string);
encoded = Regex.Replace(encoded, "&#\d+?;", "");
var result = HtmlDecode(encoded);

input and output

"Headlight\x007E Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"
"Headlight~ Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"

I know it's not perfect, but does the job for me.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Overview

As reported by Tim Anderson

Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.

Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.

Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.

Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.

edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)

Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:

We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)

This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.

Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.

PhoneGap

The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.

To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.

PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.

  • Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.

  • Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.

  • Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).

  • Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.

by Karl Waclawek

Appcelerator Titanium

The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.

So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.

Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO

Xamarin (+ MVVMCross)

AZDevelop.net

Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.

In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.

From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.

In my opinion there are several HUGE advantages including

  • native performance
  • easier to read code (IMO)
  • testability
  • shared code between client and server
  • support (although Xam could do better on bugzilla)

Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.

Conclusion

My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.

I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.

References and links

Switch statement equivalent in Windows batch file

Compact form for short commands (no 'echo'):

IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...

After ^ must be an immediate line end, no spaces.

Inputting a default image in case the src attribute of an html <img> is not valid?

angular2:

<img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later

SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]

XAMPP on Windows - Apache not starting

I spent over 3 hours to find out solution. Actually port 80 was being used by "system" service so I tried to change port from 80 to 8080 in "httpd" file but same problem raised "port 80 is used by system". It had driven me mad for 3 hours as every thing was changed like port , localhost server etc pointing to 8080.

At last I found mistake that was server root. Basically "Server Root" in "httpd" should be pointing to apache foler of xampp. In my case that's was

ServerRoot "xampp/apache"

I just changed it as follows:

ServerRoot "C:/xampp/apache" 

It has worked successfully and now everything is running with OK status.

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How do you Sort a DataTable given column and direction?

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;
    dt.DefaultView.Sort = colName + " " + direction;
    dtOut = dt.DefaultView.ToTable();
    return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
    dt.DefaultView.Sort = colName + " " + direction;
    dt = dt.DefaultView.ToTable();
    return dt;
}

End-line characters from lines read from text file, using Python

The idiomatic way to do this in Python is to use rstrip('\n'):

for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'
    line = line.rstrip('\n')
    process(line)

Each of the other alternatives has a gotcha:

  • file('...').read().splitlines() has to load the whole file in memory at once.
  • line = line[:-1] will fail if the last line has no EOL.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

This might happen when you attempt to grant all privileges on all tables to another user, because the mysql.users table is considered off-limits for a user other than root.

The following however, should work:

GRANT ALL PRIVILEGES ON `%`.* TO '[user]'@'[hostname]' IDENTIFIED BY '[password]' WITH GRANT OPTION;

Note that we use `%`.* instead of *.*

Monitor network activity in Android Phones

TCPDUMP is one of my favourite tools for analyzing network, but if you find difficult to cross-compile tcpdump for android, I'd recomend you to use some applications from the market.

These are the applications I was talking about:

  • Shark: Is small version of wireshark for Android phones). This program will create a *.pcap and you can read the file on PC with wireshark.
  • Shark Reader : This program allows you to read the *.pcap directly in your Android phone.

Shark app works with rooted devices, so if you want to install it, be sure that you have your device already rooted.

Good luck ;)

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

The source was not found, but some or all event logs could not be searched

If you are performing a new install of the SenseNet TaskManagement website on IIS (from source code, not WebPI), you will get this message, usually related to SignalR communication. As @nicole-caliniou points out, it is due to a key search in the Registry that fails.

To solve this for SenseNet TaskManagement v1.1.0, first find the registry key name in the web.config file. By default it is "SnTaskWeb".

 <appSettings>
   <add key="LogSourceName" value="SnTaskWeb" />

Open the registry editor, regedit.exe, and navigate to HKLM\SYSTEM\CurrentControlSet\Services\EventLog\SnTask. Right-click on SnTask and select New Key, and name the key SnTaskWeb for the configuration shown above. Then right-click on the SnTaskWeb element and select New Expandable String Value. The name should be EventMessageFile and the value data should be C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll.

Keywords: signalr, sensenet, regedit, permissions

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

How to redraw DataTable with new data

The accepted answer calls the draw function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:

datatable.clear().rows.add(newData).draw();

Change fill color on vector asset in Android Studio

For those not using an ImageView, the following worked for me on a plain View (and hence the behaviour should replicate on any kind of view)

<View
    android:background="@drawable/ic_reset"
    android:backgroundTint="@color/colorLightText" />

Auto-click button element on page load using jQuery

We should rather use Javascript.

    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


    <script>

        $(document).ready(function(){
            document.getElementById("myButton").click();
        });

    </script>

How do I change a tab background color when using TabLayout?

As I found best and suitable option for me and it will work with animation too.

You can use indicator it self as a background.

You can set app:tabIndicatorGravity="stretch" attribute to use as background.

Example:

   <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorGravity="stretch"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/colorAccent">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chef" />


        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User" />

    </android.support.design.widget.TabLayout>

Hope it will helps you.

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How can I use Google's Roboto font on a website?

Did you read the How_To_Use_Webfonts.html that's in that zip file?

After reading that, it seems that each font subfolder has an already created .css in there that you can use by including this:

<link rel="stylesheet" href="stylesheet.css" type="text/css" charset="utf-8" />

Multiple commands in an alias for bash

This would run the 2 commands one after another:

alias lock='gnome-screensaver ; gnome-screensaver-command --lock'

Return char[]/string from a function

you can use a static array in your method, to avoid lose of your array when your function ends :

char * createStr() 
{
    char char1= 'm';
    char char2= 'y';

    static char str[3];  
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;
}

Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)

How do I rotate a picture in WinForms

You can easily do it by calling this method :

public static Bitmap RotateImage(Image image, float angle)
{
    if (image == null)
        throw new ArgumentNullException("image");

    PointF offset = new PointF((float)image.Width / 2, (float)image.Height / 2);

    //create a new empty bitmap to hold rotated image
    Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
    rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(rotatedBmp);

    //Put the rotation point in the center of the image
    g.TranslateTransform(offset.X, offset.Y);

    //rotate the image
    g.RotateTransform(angle);

    //move the image back
    g.TranslateTransform(-offset.X, -offset.Y);

    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0, 0));

    return rotatedBmp;
}

don't forget to add a reference to System.Drawing.dll on your project

Example of this method call :

Image image = new Bitmap("waves.png");
Image newImage = RotateImage(image, 360);
newImage.Save("newWaves.png");

Generating random strings with T-SQL

I use this procedure that I developed simply stipluate the charaters you want to be able to display in the input variables, you can define the length too. Hope this formats well, I am new to stack overflow.

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'GenerateARandomString'))
DROP PROCEDURE GenerateARandomString
GO

CREATE PROCEDURE GenerateARandomString
(
     @DESIREDLENGTH         INTEGER = 100,                  
     @NUMBERS               VARCHAR(50) 
        = '0123456789',     
     @ALPHABET              VARCHAR(100) 
        ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
     @SPECIALS              VARCHAR(50) 
        = '_=+-$£%^&*()"!@~#:', 
     @RANDOMSTRING          VARCHAR(8000)   OUT 

)

AS

BEGIN
    -- Author David Riley
    -- Version 1.0 
    -- You could alter to one big string .e.e numebrs , alpha special etc
    -- added for more felxibility in case I want to extend i.e put logic  in for 3 numbers, 2 pecials 3 numbers etc
    -- for now just randomly pick one of them

    DECLARE @SWAP                   VARCHAR(8000);      -- Will be used as a tempoary buffer 
    DECLARE @SELECTOR               INTEGER = 0;

    DECLARE @CURRENTLENGHT          INTEGER = 0;
    WHILE @CURRENTLENGHT < @DESIREDLENGTH
    BEGIN

        -- Do we want a number, special character or Alphabet Randonly decide?
        SET @SELECTOR  = CAST(ABS(CHECKSUM(NEWID())) % 3 AS INTEGER);   -- Always three 1 number , 2 alphaBET , 3 special;
        IF @SELECTOR = 0
        BEGIN
            SET @SELECTOR = 3
        END;

        -- SET SWAP VARIABLE AS DESIRED
        SELECT @SWAP = CASE WHEN @SELECTOR = 1 THEN @NUMBERS WHEN @SELECTOR = 2 THEN @ALPHABET ELSE @SPECIALS END;

        -- MAKE THE SELECTION
        SET @SELECTOR  = CAST(ABS(CHECKSUM(NEWID())) % LEN(@SWAP) AS INTEGER);
        IF @SELECTOR = 0
        BEGIN
            SET @SELECTOR = LEN(@SWAP)
        END;

        SET @RANDOMSTRING = ISNULL(@RANDOMSTRING,'') + SUBSTRING(@SWAP,@SELECTOR,1);
        SET @CURRENTLENGHT = LEN(@RANDOMSTRING);
    END;

END;

GO

DECLARE @RANDOMSTRING VARCHAR(8000)

EXEC GenerateARandomString @RANDOMSTRING = @RANDOMSTRING OUT

SELECT @RANDOMSTRING

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

Illegal string offset Warning PHP

As from PHP 5.4 we need to pass the same datatype value that a function expects. For example:

function testimonial($id); // This function expects $id as an integer

When invoking this function, if a string value is provided like this:

$id = $array['id']; // $id is of string type
testimonial($id); // illegal offset warning

This will generate an illegal offset warning because of datatype mismatch. In order to solve this, you can use settype:

$id = settype($array['id'],"integer"); // $id now contains an integer instead of a string
testimonial($id); // now running smoothly

Exit from app when click button in android phonegap?

I used a combination of the above because my app works in the browser as well as on device. The problem with browser is it won't let you close the window from a script unless your app was opened by a script (like browsersync).

        if (typeof cordova !== 'undefined') {
            if (navigator.app) {
                navigator.app.exitApp();
            }
            else if (navigator.device) {
                navigator.device.exitApp();
            }
        } else {
            window.close();
            $timeout(function () {
                self.showCloseMessage = true;  //since the browser can't be closed (otherwise this line would never run), ask the user to close the window
            });
        }

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

Update and left outer join statements

In mysql the SET clause needs to come after the JOIN. Example:

UPDATE e
    LEFT JOIN a ON a.id = e.aid
    SET e.id = 2
    WHERE  
        e.type = 'user' AND
        a.country = 'US';

Tkinter scrollbar for frame

We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.

f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)           
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

Which sort algorithm works best on mostly sorted data?

Bubble-sort (or, safer yet, bi-directional bubble sort) is likely ideal for mostly sorted lists, though I bet a tweaked comb-sort (with a much lower initial gap size) would be a little faster when the list wasn't quite as perfectly sorted. Comb sort degrades to bubble-sort.

Python: converting a list of dictionaries to json

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

How do I insert multiple checkbox values into a table?

You need to declare the array in the HTML via

<input type="checkbox" name="Days[]" value="Daily">

Also you can insert multiple items with one query like this

$query = "INSERT INTO example (orange) VALUES ";
for ($i=0; $i<count($checkBox); $i++)
    $query .= "('" . $checkBox[$i] . "'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );

Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.

How do I add button on each row in datatable?

Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:

  1. fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]

  2. dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered. I just hardcoded this info to your data. You should get the right values from counts in your server sided script.

    {
     "iTotalRecords":"6",
     "iTotalDisplayRecords":"6",
      "aaData": [
    [
        "1",
        "sameek",
        "sam",
        "sam",
        "[email protected]",
        "1",
        ""
    ],...
    
  3. If you have the column names already set in the html part, you don't need to add sTitle.

  4. The mRender Function takes three parameters:

    • data = The data for this cell, as defined in mData
    • type = The datatype (can be ignored mostly)
    • full = The full data array for this row.

So your mRender function should look like this:

  "mRender": function(data, type, full) {
    return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
  }

Find a working Plunker here

Convert string to variable name in python

x='buffalo'    
exec("%s = %d" % (x,2))

After that you can check it by:

print buffalo

As an output you will see: 2

Check If only numeric values were entered in input. (jQuery)

Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit

if(phone.match(/^\d+$/)) {
    // your code here
}

How can I check whether Google Maps is fully loaded?

You could check the GMap2.isLoaded() method every n milliseconds to see if the map and all its tiles were loaded (window.setTimeout() or window.setInterval() are your friends).

While this won't give you the exact event of the load completion, it should be good enough to trigger your Javascript.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

TypeError: 'list' object cannot be interpreted as an integer

The error is from this:

def playSound(myList):
  for i in range(myList): # <= myList is a list, not an integer

You cannot pass a list to range which expects an integer. Most likely, you meant to do:

 def playSound(myList):
  for list_item in myList:

OR

 def playSound(myList):
  for i in range(len(myList)):

OR

 def playSound(myList):
  for i, list_item in enumerate(myList):

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

Yes. Run ssh-add on the client machine. Then repeat command ssh-copy-id [email protected]

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

C# Wait until condition is true

This implementation is totally based on Sinaesthetic's, but adding CancellationToken and keeping the same execution thread and context; that is, delegating the use of Task.Run() up to the caller depending on whether condition needs to be evaluated in the same thread or not.

Also, notice that, if you don't really need to throw a TimeoutException and breaking the loop is enough, you might want to make use of cts.CancelAfter() or new CancellationTokenSource(millisecondsDelay) instead of using timeoutTask with Task.Delay plus Task.WhenAny.

public static class AsyncUtils
{
    /// <summary>
    ///     Blocks while condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks until condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (!condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     The cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitWhileAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }

    /// <summary>
    ///     Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitUntilAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }
}

How to print a groupby object

to print all (or arbitrarily many) lines of the grouped df:

import pandas as pd
pd.set_option('display.max_rows', 500)

grouped_df = df.group(['var1', 'var2'])
print(grouped_df)

REACT - toggle class onclick

Well, your addActiveClass needs to know what was clicked. Something like this could work (notice that I've added the information which divs are active as a state array, and that onClick now passes the information what was clicked as a parameter after which the state is accordingly updated - there are certainly smarter ways to do it, but you get the idea).

class Test extends Component(){

  constructor(props) {
    super(props);
    this.state = {activeClasses: [false, false, false]};
    this.addActiveClass= this.addActiveClass.bind(this);
  }

  addActiveClass(index) {
    const activeClasses = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)].flat();
    this.setState({activeClasses});
  }

  render() {
    const activeClasses = this.state.activeClasses.slice();
    return (
      <div>
        <div className={activeClasses[0]? "active" : "inactive"} onClick={() => this.addActiveClass(0)}>
          <p>0</p>
        </div>
        <div className={activeClasses[1]? "active" : "inactive"} onClick={() => this.addActiveClass(1)}>
          <p>1</p>
        </div>
          <div  onClick={() => this.addActiveClass(2)}>
          <p>2</p>
        </div>
      </div>
    );
  }
}

Defining constant string in Java?

We usually declare the constant as static. The reason for that is because Java creates copies of non static variables every time you instantiate an object of the class.

So if we make the constants static it would not do so and would save memory.

With final we can make the variable constant.

Hence the best practice to define a constant variable is the following:

private static final String YOUR_CONSTANT = "Some Value"; 

The access modifier can be private/public depending on the business logic.

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

WCF - How to Increase Message Size Quota

For HTTP:

<bindings>
  <basicHttpBinding>
    <binding name="basicHttp" allowCookies="true"
             maxReceivedMessageSize="20000000" 
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
        <readerQuotas maxDepth="200" 
             maxArrayLength="200000000"
             maxBytesPerRead="4096"
             maxStringContentLength="200000000"
             maxNameTableCharCount="16384"/>
    </binding>
  </basicHttpBinding>
</bindings>

For TCP:

<bindings>
  <netTcpBinding>
    <binding name="tcpBinding"
             maxReceivedMessageSize="20000000"
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
      <readerQuotas maxDepth="200"
           maxArrayLength="200000000"
           maxStringContentLength="200000000"
           maxBytesPerRead="4096"
           maxNameTableCharCount="16384"/>
    </binding>
  </netTcpBinding>
</bindings>

IMPORTANT:

If you try to pass complex object that has many connected objects (e.g: a tree data structure, a list that has many objects...), the communication will fail no matter how you increased the Quotas. In such cases, you must increase the containing objects count:

<behaviors>
  <serviceBehaviors>
    <behavior name="NewBehavior">
      ...
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

What is a good game engine that uses Lua?

Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines

How to get enum value by string or int

Could be much simpler if you use TryParse or Parse and ToObject methods.

public static class EnumHelper
{
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val;
        return Enum.TryParse<T>(str, true, out val) ? val : default(T);
    }

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }

        return (T)Enum.ToObject(enumType, intValue);
    }
}

As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

Get elements by attribute when querySelectorAll is not available without using libraries?

A little modification on @kevinfahy 's answer, to allow getting the attribute by value if needed:

function getElementsByAttributeValue(attribute, value){
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++) {
    if (allElements[i].getAttribute(attribute) !== null) {
      if (!value || allElements[i].getAttribute(attribute) == value)
        matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

Convert string in base64 to image and save on filesystem in Python

If the imagestr was bitmap data (which we now know it isn't) you could use this

imagestr is the base64 encoded string
width is the width of the image
height is the height of the image

from PIL import Image
from base64 import decodestring

image = Image.fromstring('RGB',(width,height),decodestring(imagestr))
image.save("foo.png")

Since the imagestr is just the encoded png data

from base64 import decodestring

with open("foo.png","wb") as f:
    f.write(decodestring(imagestr))

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Open your Controller.cs file and near your public ActionResult Index(), in place of Index write the name of your page you want to run in the browser. For me it was public ActionResult Login().

Parsing GET request parameters in a URL that contains another URL

if (isset($_SERVER['HTTPS'])){
    echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}else{
    echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}

Class 'DOMDocument' not found

PHP8: (latest version)

sudo apt-get install php8.0-xml

PHP7:

sudo apt-get install php7.1-xml

You can also do:

sudo apt-get install php-dom

and apt-get will show you where it is.

socket programming multiple client to one server

Here is code for Multiple Client to one Server Working Fine .. Give it a try :)

Server.java:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{


}
Multi(Socket s) throws IOException{
    this.s=s;
    infromClient = new DataInputStream(s.getInputStream());
}
public void run(){  

    String SQL=new String();
    try {
        SQL = infromClient.readUTF();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Query: " + SQL); 
    try {
        System.out.println("Socket Closing");
        s.close();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
       }
   }  
}
public class Server {

public static void main(String args[]) throws IOException, 
InterruptedException{   

    while(true){
        ServerSocket ss=new ServerSocket(11111);
        System.out.println("Server is Awaiting"); 
        Socket s=ss.accept();
        Multi t=new Multi(s);
        t.start();

        Thread.sleep(2000);
        ss.close();
    }    




    }   
}

Client1.java:

 import java.io.DataOutputStream;
 import java.io.ObjectInputStream;
 import java.net.Socket;


public class client1 {
   public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I  am  client 1";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
}

Client2.java

import java.io.DataOutputStream; 
import java.net.Socket;


public class client2 {
    public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I am  Client 2";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
 }

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Python Dictionary contains List as Value - How to update?

An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:

l = dictionary.get('C1')
for i in range(len(l)):
    l[i] += 10

Linux command to print directory structure in the form of a tree

I'm prettifying the output of @Hassou's answer with:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/-/+/' -e '$s/+/+/'

This is much like the output of tree now:

.
+-pkcs11
+-pki
+---ca-trust
+-----extracted
+-------java
+-------openssl
+-------pem
+-----source
+-------anchors
+-profile.d
+-ssh

You can also make an alias of it:

alias ltree=$'ls -R | grep ":$" | sed -e \'s/:$//\' -e \'s/[^-][^\/]*\//--/g\' -e \'s/-/+/\' -e \'$s/+/+/\''

BTW, tree is not available in some environment, like MinGW. So the alternate is helpful.

How do I compile C++ with Clang?

Solution 1:

  clang++ your.cpp

Solution 2:

  clang your.cpp -lstdc++

Solution 3:

   clang -x c++ your.cpp

Java: Find .txt files in specified folder

Here is my platform specific code(unix)

public static List<File> findFiles(String dir, String... names)
    {
        LinkedList<String> command = new LinkedList<String>();
        command.add("/usr/bin/find");
        command.add(dir);
        List<File> result = new LinkedList<File>();
        if (names.length > 1)
            {
                List<String> newNames = new LinkedList<String>(Arrays.asList(names));
                String first = newNames.remove(0);
                command.add("-name");
                command.add(first);
                for (String newName : newNames)
                    {
                        command.add("-or");
                        command.add("-name");
                        command.add(newName);
                    }
            }
        else if (names.length > 0)
            {
                command.add("-name");
                command.add(names[0]);
            }
        try
            {
                ProcessBuilder pb = new ProcessBuilder(command);
                Process p = pb.start();
                p.waitFor();
                InputStream is = p.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null)
                    {
                        // System.err.println(line);
                        result.add(new File(line));
                    }
                p.destroy();
            }
        catch (Exception e)
            {
                e.printStackTrace();
            }
        return result;
    }

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

Android WebView not loading an HTTPS URL

override onReceivedSslError and remove

super.onReceivedSslError(view, handler, error)

And to solve Google security:

setDomStorageEnabled(true);

Full code is:

webView.enableJavaScript();
webView.getSettings().setDomStorageEnabled(true); // Add this
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // DO NOT CALL SUPER METHOD
            super.onReceivedSslError(view, handler, error);
        }
    });

Creating a singleton in Python

You probably never need a singleton in Python. Just define all your data and functions in a module and you have a de facto singleton:

import datetime
file_name=None

def set_file_name(new_file_name: str):
    global file_name
    file_name=new_file_name

def write(message: str):
    global file_name
    if file_name:
        with open(file_name, 'a+') as f:
            f.write("{} {}\n".format(datetime.datetime.now(), message))
    else:
        print("LOG: {}", message)

To use:

    import log
    log.set_file_name("debug.log")
    log.write("System starting")
    ...

If you really absolutely have to have a singleton class then I'd go with:

    class My_Singleton(object):
        def foo(self):
            pass

    my_singleton = My_Singleton()

To use:

    from mysingleton import my_singleton
    my_singleton.foo()

where mysingleton.py is your filename that My_Singleton is defined in. This works because after the first time a file is imported, Python doesn't re-execute the code.

Create Excel files from C# without office

If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx

Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).

Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.

OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.

If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.