Programs & Examples On #Tobjectlist

Delphi class for a list of objects

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I was having trouble with this issue and had tried everything that everyone had posted with no success. I finally was able to contact Google and got someone on the phone. With their help I had it fixed in minutes. Here's what worked for me...

  1. Settings --> Applicaitons --> Manage Applications --> All
  2. Select Download Manager; clear data; clear cache; go back
  3. Select Google Play Store; clear data; clear cache; go back
  4. Select Google Services Framework; clear data; clear cache; go back
  5. Turn off phone
  6. Turn on phone

It worked for me. Hope this helps someone. Also, be aware they did say that it could take a few minutes for it to work -- possibly up to 30 minutes after restarting the phone. I did notice when restarting the phone that the Google Play Store had to update itself first. But now it is resolved. Finally!

PHP Pass variable to next page

try this code

using hidden field we can pass php varibale to another page

page1.php

<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>

pass php variable to hidden field value so you can access this variable into another page

page2.php

<?php
 $text=$_POST['text'];
 echo $text;
?>

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

How do I list all the columns in a table?

For MySQL, use:

DESCRIBE name_of_table;

This also works for Oracle as long as you are using SQL*Plus, or Oracle's SQL Developer.

scp files from local to remote machine error: no such file or directory

If you want to copy everything in a Folder + have a special Port use this one. Works for me on Ubuntu 18.04 and a local machine with Mac OS X.

-r for recursive
-P for Port

scp -rP 1234 /Your_Directory/Source_Folder/ [email protected]:/target/folder

SQL - Update multiple records in one query

maybe for someone it will be useful

for Postgresql 9.5 works as a charm

INSERT INTO tabelname(id, col2, col3, col4)
VALUES
    (1, 1, 1, 'text for col4'),
    (DEFAULT,1,4,'another text for col4')
ON CONFLICT (id) DO UPDATE SET
    col2 = EXCLUDED.col2,
    col3 = EXCLUDED.col3,
    col4 = EXCLUDED.col4

this SQL updates existing record and inserts if new one (2 in 1)

Locate the nginx.conf file my nginx is actually using

% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf

If nginx was run without the -c option, then you can use the -V option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:

--prefix=PATH                      set installation prefix
--sbin-path=PATH                   set nginx binary pathname
--conf-path=PATH                   set nginx.conf pathname

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

python ValueError: invalid literal for float()

I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:

print repr(temp)

You'll likely see something in there that's escaped in the form \x00. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.

-- Edited for question changes --

It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like

map(float, temp.strip().split('\r\n'))

In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.

How to send an HTTP request using Telnet

You could do

telnet stackoverflow.com 80

And then paste

GET /questions HTTP/1.0
Host: stackoverflow.com


# add the 2 empty lines above but not this one

Here is a transcript

$ telnet stackoverflow.com 80
Trying 151.101.65.69...
Connected to stackoverflow.com.
Escape character is '^]'.
GET /questions HTTP/1.0
Host: stackoverflow.com

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
...

Ascending and Descending Number Order in java

Just sort the array in ascending order and print it backwards.

Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
    //print arr[i]
}

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Fluid layout in Bootstrap 3.

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

container-fluid is added back in Bootstrap 3.1

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style

.my-fluid-container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
}

How can I check if mysql is installed on ubuntu?

# mysqladmin -u root -p status

Output:

Enter password:
Uptime: 4  Threads: 1  Questions: 62  Slow queries: 0  Opens: 51  Flush tables: 1  Open tables: 45  Queries per second avg: 15.500

It means MySQL serer is running

If server is not running then it will dump error as follows

# mysqladmin -u root -p status

Output :

mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!

So Under Debian Linux you can type following command

# /etc/init.d/mysql status

Spring Boot @autowired does not work, classes in different package

I had the same problem. It worked for me when i removed the private modifier from the Autowired objects.

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

Display JSON Data in HTML Table

As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.

It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable

To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:

<div id="citytable"></div>

Then in the ajax success method you will want something like this

success: function(data){ 
    $("#citytable").mrjsontable({
        tableClass: "my-table",
        pageSize: 10, //you can change the page size here
        columns: [
            new $.fn.mrjsontablecolumn({
                heading: "City",
                data: "city"
            }),
            new $.fn.mrjsontablecolumn({
                heading: "City Status",
                data: "cStatus"
            })
        ],
        data: data
    });
}

Hope it helps somebody else!

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

My version written in typescript:

function changeColorLightness(color: number, lightness: number): number {
    return (Math.max(0, Math.min(((color & 0xFF0000) / 0x10000) + lightness, 0xFF)) * 0x10000) +
        (Math.max(0, Math.min(((color & 0x00FF00) / 0x100) + lightness, 0xFF)) * 0x100) +
        (Math.max(0, Math.min(((color & 0x0000FF)) + lightness, 0xFF)));
}

explanation:

export function changeColorLightness(color: number, lightness: number): number {
    const r = (color & 0xFF0000) / 0x10**4;
    const g = (color & 0x00FF00) / 0x10**2;
    const b = (color & 0x0000FF);

    const changedR = Math.max(0, Math.min(r + lightness, 0xFF));
    const changedG = Math.max(0, Math.min(g + lightness, 0xFF));
    const changedB = Math.max(0, Math.min(b + lightness, 0xFF));

    return (changedR * 0x10**4) + (changedG * 0x10**2) + changedB;
}

usage:

changeColorLightness(0x00FF00, 0x50);
changeColorLightness(parseInt("#00FF00".replace('#',''), 16), 0x50);
changeColorLightness(0x00FF00, 127.5);

HTML5 Audio stop function

This method works:

audio.pause();
audio.currentTime = 0;

But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.

First method: create a function and pass the audio

function stopAudio(audio) {
    audio.pause();
    audio.currentTime = 0;
}

//then using it:
stopAudio(audio);

Second method (favoured): extend the Audio class:

Audio.prototype.stop = function() {
    this.pause();
    this.currentTime = 0;
};

I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.

Then you can call the stop function on audio objects:

audio.stop();

FINALLY CHROME ISSUE WITH "canplaythrough":

I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.

So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:

//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
    $(this).off("canplaythrough");

    // rest of the code ...
});

BONUS:

Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).

For example if you wanted a "restart" method that restarted the audio it could look something like:

Audio.prototype.restart= function() {
    this.pause();
    this.currentTime = 0;
    this.play();
};

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

select Country_id,country_title from(
   select Country_id,country_title,row_number() over (partition by country_title 
   order by Country_id  ) rn from country)a
   where rn=1;

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here is a solution if you need to hook up some methods to @User for use in your views. No solution for any serious membership customization, but if the original question was needed for views alone then this perhaps would be enough. The below was used for checking a variable returned from a authorizefilter, used to verify if some links wehere to be presented or not(not for any kind of authorization logic or access granting).

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Security.Principal;

    namespace SomeSite.Web.Helpers
    {
        public static class UserHelpers
        {
            public static bool IsEditor(this IPrincipal user)
            {
                return null; //Do some stuff
            }
        }
    }

Then just add a reference in the areas web.config, and call it like below in the view.

@User.IsEditor()

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

You need to make sure that the previous container you launched is killed, before launching a new one that uses the same port.

docker container ls
docker rm -f <container-name>

TortoiseSVN icons overlay not showing after updating to Windows 10

I would recommend you to change Status cache of the Overlays.

Settings -> Icon Overlays -> Status cache

Maybe this would help to reinitialise the cache.

enter image description here

Be sure touse the latest version of Tortoise.

What is the syntax for Typescript arrow functions with generics?

while the popular answer with extends {} works and is better than extends any, it forces the T to be an object

const foo = <T extends {}>(x: T) => x;

to avoid this and preserve the type-safety, you can use extends unknown instead

const foo = <T extends unknown>(x: T) => x;

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

How to make Visual Studio copy a DLL file to the output directory?

$(OutDir) turned out to be a relative path in VS2013, so I had to combine it with $(ProjectDir) to achieve the desired effect:

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(ProjectDir)$(OutDir)"

BTW, you can easily debug the scripts by adding 'echo ' at the beginning and observe the expanded text in the build output window.

How Can I Remove “public/index.php” in the URL Generated Laravel?

If you use IIS Windows Server add web.config file in root folder and put the below code :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{URL}" pattern="^system.*" ignoreCase="false" />
                    </conditions>
                    <action type="Rewrite" url="/index.php/{R:1}" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{R:1}" pattern="^(index\.php|images|robots\.txt|css)" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

and if you use .htaccess use this one :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

How to define an optional field in protobuf 3

Since protobuf release 3.15, proto3 supports using the optional keyword (just as in proto2) to give a scalar field presence information.

syntax = "proto3";

message Foo {
    int32 bar = 1;
    optional int32 baz = 2;
}

A has_baz()/hasBaz() method is generated for the optional field above, just as it was in proto2.

Under the hood, protoc effectively treats an optional field as if it were declared using a oneof wrapper, as CyberSnoopy’s answer suggested:

message Foo {
    int32 bar = 1;
    oneof optional_baz {
        int32 baz = 2;
    }
}

If you’ve already used that approach, you can now simplify your message declarations (switch from oneof to optional) and code, since the wire format is the same.

The nitty-gritty details about field presence and optional in proto3 can be found in the Application note: Field presence doc.

Historical note: Experimental support for optional in proto3 was first announced on Apr 23, 2020 in this comment. Using it required passing protoc the --experimental_allow_proto3_optional flag in releases 3.12-3.14.

PHP strtotime +1 month adding an extra month

try this:

$endOfCycle = date("Y-m", time()+2592000);

this adds 30 days, not exactly a month tough.

Java program to connect to Sql Server and running the sample query From Eclipse

Right click your project--->Build path---->configure Build path----> Libraries Tab--->Add External jars--->(Navigate to the location where you have kept the sql driver jar)--->ok

PowerShell: Run command from script's directory

This would work fine.

Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir

How to break nested loops in JavaScript?

The another trick is by setting the parent loop to reach the end and then break the current loop

function foo()
{
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                k = 5; // Set this then break
                break;
            }
          console.log(m);
        }
    }
}

CSS: Control space between bullet and <li>

Use padding-left:1em; text-indent:-1em for the <li> tag.
Then, list-style-position: inside for the <ul> tag.

<ul style='list-style-position: inside;'>
  <li style='padding-left: 1em; text-indent: -1em;'>Item 1</li>
</ul>

How to cancel a local git commit

Use below command:

$ git reset HEAD~1

After this you also able to view files what revert back like below response.

Unstaged changes after reset:
M   application/config/config.php
M   application/config/database.php

How to put a UserControl into Visual Studio toolBox

The issue with my designer was 32 vs 64 bit issue. I could add the control to tool box after following the instructions in Cannot add Controls from 64-bit Assemblies to the Toolbox or Use in Designers Within the Visual Studio IDE MS KB article.

Convert Unix timestamp to a date string

Python:

python -c "from datetime import datetime; print(datetime.fromtimestamp($TIMESTAMP))"

How to get the current time in milliseconds in C Programming

If you're on a Unix-like system, use gettimeofday and convert the result from microseconds to milliseconds.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.

Checking the following section in DatabaseInterface.class.php,

        define(
            'PMA_MYSQL_INT_VERSION',
            PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
        );

I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start and stop.

# restart the service
systemd restart php-fpm

# start and stop the service
systemd stop php-fpm
systemd start php-fpm

Doing a stop followed by a start fixed the issue for me.

Inline Form nested within Horizontal Form in Bootstrap 3

A much simpler solution, without all the inside form-group elements

<div class="form-group">
       <label for="birthday" class="col-xs-2 control-label">Birthday</label>
       <div class="col-xs-10">
           <div class="form-inline">
               <input type="text" class="form-control" placeholder="year" style="width:70px;"/>
               <input type="text" class="form-control" placeholder="month" style="width:80px;"/>
               <input type="text" class="form-control" placeholder="day" style="width:100px;"/>                        
           </div>
     </div>
</div>

... and it will look like this,

enter image description here

Cheers!

Arduino error: does not name a type?

My code was out of void setup() or void loop() in Arduino.

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

I read all the comments and thought that GitHub made it too difficult for normal user to create GitHub pages until I visited GitHub theme Page where its clearly mentioned that there is a section of "GitHub Pages" under settings Page of the concerned repo where you can choose the option "use the master branch for GitHub Pages." and voilà!!...checkout that particular repo on https://username.github.io/reponame

screenshot to support my answer

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

How do I POST urlencoded form data with $http without jQuery?

All of these look like overkill (or don't work)... just do this:

$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                     `&password=${ encodeURIComponent(password) }` +
                     '&grant_type=password'
).success(function (data) {

How can I remove the search bar and footer added by the jQuery DataTables plugin?

Just a reminder you can't initialise DataTable on the same <table> element twice.

If you encounter same issue then you can set searching and paging false while initializing DataTable on your HTML <table> like this

 $('#tbl').DataTable({
    searching: false, 
    paging: false,
    dom: 'Bfrtip',
    buttons: [
       'copy', 'csv', 'excel', 'pdf', 'print'
    ]
 });

How to call Base Class's __init__ method from the child class?

As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super() since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__ instead. Here is the code after incorporating these changes :

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):

    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__ with super()

How to render a PDF file in Android

To add a little light to this, I would have to go with the pdf.js solution from Mozilla. Here is the link to an already well written implementation of this: https://bitbucket.org/butelo/pdfviewer/.

Here are the edits that I added in my Android Activity:

private String getInternalPDFURL(String interalPDFName){
    return "file:///android_asset/pdfviewer/index.html?pdf=" + interalPDFName + ".pdf";
}

Here are the edits I made in pdffile.js:

var url = '../' + getPDFURL();

function getPDFURL(){
    var query = window.location.search.substring(1);
    var vars = query.split("=");
    var pdfPage = vars[1];
    return pdfPage;
}

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

Can I install/update WordPress plugins without providing FTP access?

open wp-config.php file and add the following line:

define('FS_METHOD', 'direct');

this is working for me ...Thanks

How do I check out an SVN project into Eclipse as a Java project?

If it wasn't checked in as a Java Project, you can add the java nature as shown here.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

javascript change background color on click

I'm suggest that you learn about Jquery, most popular JS library. With jquery it's simple to acomplish what you want.Simle example below:

$(“#DIV_YOU_WANT_CHANGE”).click(function() {
    $(this).addClass(“.your_class_with_new_color”);
}); 

Integrity constraint violation: 1452 Cannot add or update a child row:

I had the same error, the problem was that I was trying to add role_id foreign to the users table, but role_id did not have a default value, so the DB did not allow me to insert the column because I already had some users and it didn't know how to add the column to them. Since I was in development I just used migrate:fresh, but if I was on production, I would probably set a default value to the role_id and not make it not constrained until I had the corresponding role on the DB.

Local dependency in package.json

Curious.....at least on Windows (my npm is 3.something) I needed to do:

"dependencies": {
 "body-parser": "^1.17.1",
 "module1": "../module1",
 "module2": "../module2",

When I did an npm install ../module1 --save it resulted in absolute paths and not relative per the documentation.

I messed around a little more and determined that ../xxx was sufficient.

Specifically, I have the local node modules checked out to say d:\build\module1, d:\build\module2 and my node project (application) in d:\build\nodeApp.

To 'install', I:

d:\build\module1> rmdir "./node_modules" /q /s && npm install
d:\build\module2> rmdir "./node_modules" /q /s && npm install
d:\build\nodeApp> rmdir "./node_modules" /q /s && npm install

module1's package.json has a dependency of "module2": "../module2"; module2 has no local dependency; nodeApp has dependencies "module1": "../module1" and "module2": "../module2".

Not sure if this only works for me since all 3 folders (module1, module2 and nodeApp) sit on that same level.......

How to turn off magic quotes on shared hosting?

This will solve the problem of getting "Class 'PDO' not found" when you create a local php.ini file.

If you can't turn off magic quotes using the htaccess file (for reasons already given by Pete Bailey) just:

  1. Create a text file
  2. Rename it to 'php.ini'
  3. Add the lines

    magic_quotes_gpc = Off
    magic_quotes_runtime = Off
    magic_quotes_sybase = Off
    extension=pdo.so
    extension=pdo_mysql.so

  4. Save it to the directory/ies in which your scripts are executing.

Update: if you want to have just one copy of the new php.ini file then add this line to your root .htaccess file:

SetEnv PHPRC /path/to/site/root/public_html/php.ini

Obviously you need to move the ini file to this location of it's not there already.

Hope that saves someone the 2 hours it's just taken me!

Apply function to each column in a data frame observing each columns existing data type

A solution using retype() from hablar to coerce factors to character or numeric type depending on feasability. I'd use dplyr for applying max to each column.

Code

library(dplyr)
library(hablar)

# Retype() simplifies each columns type, e.g. always removes factors
d <- d %>% retype()

# Check max for each column
d %>% summarise_all(max)

Result

Not the new column types.

     v1 v2       v3 v4   
  <dbl> <chr> <dbl> <chr>
1 0.974 j      1.09 J   

Data

# Sample data borrowed from @joran
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

How many socket connections possible?

depends on the application. if there is only a few packages from each client, 100K is very easy for linux. A engineer of my team had done a test years ago, the result shows : when there is no package from client after connection established, linux epoll can watch 400k fd for readablity at cpu usage level under 50%.

Can Selenium WebDriver open browser windows silently in the background?

For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome

How to assign a heredoc value to a variable in Bash?

You can avoid a useless use of cat and handle mismatched quotes better with this:

$ read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

If you don't quote the variable when you echo it, newlines are lost. Quoting it preserves them:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If you want to use indentation for readability in the source code, use a dash after the less-thans. The indentation must be done using only tabs (no spaces).

$ read -r -d '' VAR <<-'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
    EOF
$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If, instead, you want to preserve the tabs in the contents of the resulting variable, you need to remove tab from IFS. The terminal marker for the here doc (EOF) must not be indented.

$ IFS='' read -r -d '' VAR <<'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
EOF
$ echo "$VAR"
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''

Tabs can be inserted at the command line by pressing Ctrl-V Tab. If you are using an editor, depending on which one, that may also work or you may have to turn off the feature that automatically converts tabs to spaces.

Java 8 optional: ifPresent return object orElseThrow exception

I'd prefer mapping after making sure the value is available

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

or one liner

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

How to see query history in SQL Server Management Studio

If the queries you are interested in are dynamic queries that fail intermittently, you could log the SQL and the datetime and user in a table at the time the dynamic statement is created. It would be done on a case-by case basis though as it requires specific programming to happen and it takes a littel extra processing time, so do it only for those few queries you are most concerned about. But having a log of the specific statements executed can really help when you are trying to find out why it fails once a month only. Dynamic queries are hard to thoroughly test and sometimes you get one specific input value that just won't work and doing this logging at the time the SQL is created is often the best way to see what specifically wasn in the sql that was built.

Creating a Custom Event

Yes, provided you have access to the object definition and can modify it to declare the custom event

public event EventHandler<EventArgs> ModelChanged;

And normally you'd back this up with a private method used internally to invoke the event:

private void OnModelChanged(EventArgs e)
{
    if (ModelChanged != null)
        ModelChanged(this, e);
}

Your code simply declares a handler for the declared myMethod event (you can also remove the constructor), which would get invoked every time the object triggers the event.

myObject.myMethod += myNameEvent;

Similarly, you can detach a handler using

myObject.myMethod -= myNameEvent;

Also, you can write your own subclass of EventArgs to provide specific data when your event fires.

Java's L number (long) specification

I hope you won't mind a slight tangent, but thought you may be interested to know that besides F (for float), D (for double), and L (for long), a proposal has been made to add suffixes for byte and shortY and S respectively. This would eliminate to the need to cast to bytes when using literal syntax for byte (or short) arrays. Quoting the example from the proposal:

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

cruddy code like

 byte[] stuff = { 0x00, 0x7F, (byte)0x80,  (byte)0xFF};

can be recoded as

 byte[] ufum7 = { 0x00y, 0x7Fy, 0x80y, 0xFFy };

Joe Darcy is overseeing Project Coin for Java 7, and his blog has been an easy way to track these proposals.

How to remove a web site from google analytics

To delete a web property, you simply need to delete every profile within the property. Once the last profile has been deleted, the web property with cease to exist in the GA account. That's all there is to it! -- Source

Can a java file have more than one class?

There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.

You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:

Top level classes:
1 public class
0 private class
any number of default/protected classes

Inner classes:
any number of inner classes with any visibility (default, private, protected, public)

Please correct me if I am wrong.

Android - how to replace part of a string by another string?

rekaszeru

I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..

Im using a EditText as an example


// GIVE TARGET TEXT BOX A NAME

 EditText textbox = (EditText) findViewById(R.id.your_textboxID);

// STRING TO REPLACE

 String oldText = "hello"
 String newText = "Hi";      
 String textBoxText = textbox.getText().toString();

// REPLACE STRINGS WITH RETURNED STRINGS

String returnedString = textBoxText.replace( oldText, newText );

// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX

textbox.setText(returnedString);

This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !

Obviously this example requires that you have a EditText with the ID set to your_textboxID

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

How do I create a new line in Javascript?

To create a new line, symbol is '\n'

var i;
for(i=10; i>=0; i= i-1){
   var s;
   for(s=0; s<i; s = s+1){
    document.write("*");
   }
   //i want this to print a new line
   document.write('\n');

}

If you are outputting to the page, you'll want to use "<br/>" instead of '/n';

Escape characters in JavaScript

how to get domain name from URL

I know the question is seeking a regex solution but in every attempt it won't work to cover everything

I decided to write this method in Python which only works with urls that have a subdomain (i.e. www.mydomain.co.uk) and not multiple level subdomains like www.mail.yahoo.com

def urlextract(url):
  url_split=url.split(".")
  if len(url_split) <= 2:
      raise Exception("Full url required with subdomain:",url)
  return {'subdomain': url_split[0], 'domain': url_split[1], 'suffix': ".".join(url_split[2:])}

Setting timezone to UTC (0) in PHP

Is 'UTC' a valid timezone identifier on your system?

<?php
if (date_default_timezone_set('UTC')){
    echo "UTC is a valid time zone";
}else{
    echo "The system doesn't know WTFUTC.  Maybe try updating tzinfo with your package manager?";
}

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

How to get parameters from a URL string?

In Laravel, I'm use:

private function getValueFromString(string $string, string $key)
{
    parse_str(parse_url($string, PHP_URL_QUERY), $result);

    return isset($result[$key]) ? $result[$key] : null;
}

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Your local port is using by another app. I faced the same problem! You can try the following step:

  1. Go to command line and run it as administrator!

  2. Type:

    netstat -ano | find ":5000"
    => TCP    0.0.0.0:5000           0.0.0.0:0              LISTENING       4032
       TCP    [::]:5000              [::]:0                 LISTENING       4032
    
  3. Type:

    TASKKILL /F /PID 4032
    

=> SUCCESS: The process with PID 4032 has been terminated.

Note: My 5000 local port was listing by PID 4032. You should give yours!

Change background color on mouseover and remove it after mouseout

Try this , its working and simple

HTML

?????????????????????<html>
<head></head>
<body>
    <div class="forum">
        test
    </div>
</body>
</html>?????????????????????????????????????????????

Javascript

$(document).ready(function() {
    var colorOrig=$(".forum").css('background-color');
    $(".forum").hover(
    function() {
        //mouse over
        $(this).css('background', '#ff0')
    }, function() {
        //mouse out
        $(this).css('background', colorOrig)
    });
});?

css ?

.forum{
    background:#f0f;
}?

live demo

http://jsfiddle.net/caBzg/

database vs. flat files

Difference between database and flat files are given below:

  • Database provide more flexibility whereas flat file provide less flexibility.

  • Database system provide data consistency whereas flat file can not provide data consistency.

  • Database is more secure over flat files.
  • Database support DML and DDL whereas flat files can not support these.

  • Less data redundancy in database whereas more data redundancy in flat files.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

If an existing (non-bare) checkout begins giving this error, check your .git/config file; if core.bare is true, remove that config line

How to append one file to another in Linux from the shell?

Another solution:

cat file1 | tee -a file2

tee has the benefit that you can append to as many files as you like, for example:

cat file1 | tee -a file2 file3 file3

will append the contents of file1 to file2, file3 and file4.

From the man page:

-a, --append
       append to the given FILEs, do not overwrite

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You could also use it clean and simple (but wrong! because you should use format like Mark Byers said) by doing:

print 'This is my %s formatted with %d arguments' % ('string', 2)

Giving graphs a subtitle in matplotlib

The solution that worked for me is:

  • use suptitle() for the actual title
  • use title() for the subtitle and adjust it using the optional parameter y:
    import matplotlib.pyplot as plt
    """
            some code here
    """
    plt.title('My subtitle',fontsize=16)
    plt.suptitle('My title',fontsize=24, y=1)
    plt.show()

There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y until you get it right.

How do I solve the INSTALL_FAILED_DEXOPT error?

As this seems to be a problem I have myself encountered multiple times and this time none of the shared solutions helped me, I'll still post what helped me personally and what I believe may help someone else in future:

Go to your project's directory and find build/intermediates/dex-cache/cache file. Remove it - as name suggests, it's a cached dex file that may be outdated if you have made changes to your project's dependencies, build tools version etc.

What is time(NULL) in C?

You have to refer to the documentation for ctime. time is a function that takes one parameter of type time_t * (a pointer to a time_t object) and assigns to it the current time. Instead of passing this pointer, you can also pass NULL and then use the returned time_t value instead.

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

bootstrap 4 file input doesn't show the file name

This works with Bootstrap 4.1.3:

<script>
    $("input[type=file]").change(function () {
        var fieldVal = $(this).val();

        // Change the node's value by removing the fake path (Chrome)
        fieldVal = fieldVal.replace("C:\\fakepath\\", "");

        if (fieldVal != undefined || fieldVal != "") {
            $(this).next(".custom-file-label").attr('data-content', fieldVal);
            $(this).next(".custom-file-label").text(fieldVal);
        }
    });
</script>

Format decimal for percentage values?

Use the P format string. This will vary by culture:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)

Can't clone a github repo on Linux via HTTPS

I met the same problem, the error message and OS info are as follows

OS info:

CentOS release 6.5 (Final)

Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

error info:

Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs

fatal: HTTP request failed

git & curl version info

git info :git version 1.7.1

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

debugging

$ curl --verbose https://github.com

  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • Initializing NSS with certpath: sql:/etc/pki/nssdb
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12190
  • Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /

  • Connection died, retrying a fresh connect

  • Closing connection #0
  • Issue another request to this URL: 'https://github.com'
  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • TLS disabled due to previous handshake failure
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12286
  • Closing connection #0
  • SSL connect error curl: (35) SSL connect error

after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows

sudo yum update -y nss curl libcurl

Cannot start session without errors in phpMyAdmin

Knowing this thread is marked as solved, it shows up early on Google Search for the given term. So I thought it might be useful to mention another reason that can lead to this error.

If you enabled "safe/secure cookies", that has to be disabled for phpMyAdmin as it wont work with them being activated. So make sure you have nothing like:

Header set Set-Cookie HttpOnly;Secure

in your config.

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

You can fix that by running this: On Fedora:

sudo dnf install redhat-rpm-config

How to run mvim (MacVim) from Terminal?

If you go the brew route, the best way to install would be:

brew install macvim --with-override-system-vim

That will provide mvim, vim, vi, view, etc. in /usr/local/bin (all symlinked to the copy in the Cellar). This also removes the need to create any aliases and also changes your vi, vim, etc. to all use the same Vim distribution as your MacVim.

Javascript dynamic array of strings

Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.

<script type="text/javascript">

var arr = [];

function add() {
   var inp = document.getElementById('num');
   arr.push(inp.value);
   inp.value = '';
}

function show() {
   var html = '';
   for (var i=0; i<arr.length; i++) {
      html += '<div>' + arr[i] + '</div>';
   }
   var con = document.getElementById('container');
   con.innerHTML = html;
}

</script>

<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

The errors actually vary. It's helpful to run ./emulator with -verbose option, as it will show the actual errors.

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

Passing arguments to AsyncTask, and returning results

Change your method to look like this:

String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list

And change your async task implementation

public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(baraj_mapa.this);
        dialog.setTitle("Calculating...");
        dialog.setMessage("Please wait...");
        dialog.setIndeterminate(true);
        dialog.show();
    }

    protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> passed = passing[0]; //get passed arraylist

        //Some calculations...

        return result; //return result
    }

    protected void onPostExecute(ArrayList<String> result) {
        dialog.dismiss();
        String minim = result.get(0);
        int min = Integer.parseInt(minim);
        String glons = result.get(1);
        String glats = result.get(2);
        double glon = Double.parseDouble(glons);
        double glat = Double.parseDouble(glats);
        GeoPoint g = new GeoPoint(glon, glat);
        String korisni_linii = result.get(3);
    }

UPD:

If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:

new calc_stanica() {
    protected void onPostExecute(ArrayList<String> result) {
      // here you have access to the context in which execute was called in first place. 
      // You'll have to mark all the local variables final though..
     }
}.execute(passing);

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

You can solve it just in 1 second!

just use this url:

http://127.0.0.1/phpmyadmin/

instead of

http://localhost/phpmyadmin/

Xcode 10: A valid provisioning profile for this executable was not found

I had this issue occurring in Xcode 10.3 after I switched over to my XCTest unit test target then back to the project run time target.

Turns out I had a different Teams selected in my provisioning profile for each target.

To fix it :

  • Clean Build Folder

  • Make sure all may targets are using the same Team. See Profile Signing under the general tab.

  • If not using same Team for all targets, clean before switching to a build target with

    different team selected.

Select records from today, this week, this month php mysql

A better solution for "today" is:

SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())

How to get file size in Java

Try this:

long length = f.length();

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

Android: how to make keyboard enter button say "Search" and handle its click?

In xml file, put imeOptions="actionSearch" and inputType="text", maxLines="1":

<EditText
    android:id="@+id/search_box"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search"
    android:imeOptions="actionSearch"
    android:inputType="text"
    android:maxLines="1" />

How to make a Java Generic method static?

You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:

public class ArrayUtils {
    public static <T> E[] appendToArray(E[] array, E item) {
        E[] result = (E[])new Object[array.length+1];
        result[array.length] = item;
        return result;
    }
}

Is there a minlength validation attribute in HTML5?

In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.

Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.

Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.

How can I find a specific element in a List<T>?

public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));

What is PHPSESSID?

PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself

How to use ESLint with Jest

Pattern based configs are scheduled for 2.0.0 release of ESLint. For now, however, you will have to create two separate tasks (as mentioned in the comments). One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.

P.S. There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals.

Check if a string is a valid Windows directory (folder) path

Here is a solution that leverages the use of Path.GetFullPath as recommended in the answer by @SLaks.

In the code that I am including here, note that IsValidPath(string path) is designed such that the caller does not have to worry about exception handling.

You may also find that the method that it calls, TryGetFullPath(...), also has merit on its own when you wish to safely attempt to get an absolute path.

/// <summary>
/// Gets a value that indicates whether <paramref name="path"/>
/// is a valid path.
/// </summary>
/// <returns>Returns <c>true</c> if <paramref name="path"/> is a
/// valid path; <c>false</c> otherwise. Also returns <c>false</c> if
/// the caller does not have the required permissions to access
/// <paramref name="path"/>.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="TryGetFullPath"/>
public static bool IsValidPath(string path)
{
    string result;
    return TryGetFullPath(path, out result);
}

/// <summary>
/// Returns the absolute path for the specified path string. A return
/// value indicates whether the conversion succeeded.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute
/// path information.
/// </param>
/// <param name="result">When this method returns, contains the absolute
/// path representation of <paramref name="path"/>, if the conversion
/// succeeded, or <see cref="String.Empty"/> if the conversion failed.
/// The conversion fails if <paramref name="path"/> is null or
/// <see cref="String.Empty"/>, or is not of the correct format. This
/// parameter is passed uninitialized; any value originally supplied
/// in <paramref name="result"/> will be overwritten.
/// </param>
/// <returns><c>true</c> if <paramref name="path"/> was converted
/// to an absolute path successfully; otherwise, false.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="IsValidPath"/>
public static bool TryGetFullPath(string path, out string result)
{
    result = String.Empty;
    if (String.IsNullOrWhiteSpace(path)) { return false; }
    bool status = false;

    try
    {
        result = Path.GetFullPath(path);
        status = true;
    }
    catch (ArgumentException) { }
    catch (SecurityException) { }
    catch (NotSupportedException) { }
    catch (PathTooLongException) { }

    return status;
}

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

This is another related post Lombok not working with IntelliJ 2020.3 Community Edition which may resolve the question when user use lombook and IntelliJ 2020.3 CommunityEdition.

return error message with actionResult

You need to return a view which has a friendly error message to the user

catch (Exception ex)
{
   // to do :log error
   return View("Error");
}

You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.

If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions

[HttpPost]
public ActionResult Create(CustomerVM model)
{
  try
  {
   //save customer
    return Json(new { status="success",message="customer created"});
  }
  catch(Exception ex)
  {
    //to do: log error
   return Json(new { status="error",message="error creating customer"});
  }
} 

If you want to show the error in the form user submitted, You may use ModelState.AddModelError method along with the Html helper methods like Html.ValidationSummary etc to show the error to the user in the form he submitted.

How to create an empty file at the command line in Windows?

You could also use:

echo. 2>foo

The debug output for echo. will almost definitely be empty.

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

Objective-C and Swift URL encoding

 NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)@"parameter",NULL,(CFStringRef)@"!*'();@&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );

NSURL * url = [[NSURL alloc] initWithString:[@"address here" stringByAppendingFormat:@"?cid=%@",encodedString, nil]];

how to get param in method post spring mvc?

You should use @RequestParam on those resources with method = RequestMethod.GET

In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType).

Typically, multipart/form-data is used to upload files.

How do I make a MySQL database run completely in memory?

Additional thoughts :

Ramdisk - setting the temp drive MySQL uses as a RAM disk, very easy to set up.

memcache - memcache server is easy to set up, use it to store the results of your queries for X amount of time.

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:

   os.path.basename(filename)

due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

scp with port number specified

Hope this will help someone looking for a perfect answer

Copying a folder or file from a server with a port defined to another server or local machine

  1. Go to a directory where you have admin rights preferably your home directory on the machine where you want to copy files to
  2. Write the command below

scp -r -P port user@IP_address:/home/file/pathDirectory .

**Note:** The last . on the command directs it to copy everything in that folder to your directory of preference

How do I find out what License has been applied to my SQL Server installation?

SELECT SERVERPROPERTY('LicenseType') as Licensetype, 
       SERVERPROPERTY('NumLicenses') as LicenseNumber,
       SERVERPROPERTY('productversion') as Productverion, 
       SERVERPROPERTY ('productlevel')as ProductLevel, 
       SERVERPROPERTY ('edition') as SQLEdition,@@VERSION as SQLversion

I had installed evaluation edition.Refer screenshot enter image description here

How do I update a formula with Homebrew?

I think the correct way to do is

brew upgrade mongodb

It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply

brew upgrade

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

How to print all key and values from HashMap in Android?

Kotlin Answer

for ((key, value) in map.entries) {
    // do something with `key`
    // so something with `value`
}

You may find other solutions that include filterValues. Just keep in mind that retrieving a Key value using filterValues will include braces [].

val key = map.filterValues {it = position}.keys

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

How to programmatically set the ForeColor of a label to its default?

The default (when created with the designer) is:

label.ForeColor = SystemColors.ControlText;

This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).

Exception: Can't bind to 'ngFor' since it isn't a known native property

In my case I made the mistake of copying *ng-for= from the docs.

https://angular.io/guide/user-input

Correct me if I am wrong. But it seems *ng-for= has been changed to *ngFor=

Java: String - add character n-times

How I did it:

final int numberOfSpaces = 22;
final char[] spaceArray = new char[numberOfSpaces];
Arrays.fill(spaces, ' ');

Now add it to your StringBuilder

stringBuilder.append(spaceArray);

or String

final String spaces = String.valueOf(spaceArray);

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

Create excel ranges using column numbers in vba?

These answers seem strangely convoluted. Unless I'm missing something...if you want to convert numbers to letters, you can just stock them all in an array using a for loop then call on the number associated with that column letter. Like so

For intloop = 1 To 26
    colcheck(intloop) = Chr$(64 + intloop)
    For lenloop = 1 To 26
        colcheck((intloop * 26) + lenloop) = Chr$(64 + intloop) & Chr$(64 + lenloop)
        For terloop = 1 To 26
            colcheck((intloop * 676) + (lenloop * 26) + terloop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop)
            For qualoop = 1 To 26
                colcheck((intloop * 17576) + (lenloop * 676) + (terloop * 26) + qualoop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop) & Chr$(64 + qualoop)
            Next qualoop
        Next terloop
    Next lenloop
Next intloop

Then just use colcheck(yourcolumnnumberhere) and you will get the column heading associated with that letter (i.e. colcheck(703) = AAA

How to make Java work with SQL Server?

Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).

I used 1.5 for the other server, so I waisted a lot of time on this.

Tricky issue.

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

how to reference a YAML "setting" from elsewhere in the same YAML file?

I've create a library, available on Packagist, that performs this function: https://packagist.org/packages/grasmash/yaml-expander

Example YAML file:

type: book
book:
  title: Dune
  author: Frank Herbert
  copyright: ${book.author} 1965
  protaganist: ${characters.0.name}
  media:
    - hardcover
characters:
  - name: Paul Atreides
    occupation: Kwisatz Haderach
    aliases:
      - Usul
      - Muad'Dib
      - The Preacher
  - name: Duncan Idaho
    occupation: Swordmaster
summary: ${book.title} by ${book.author}
product-name: ${${type}.title}

Example logic:

// Parse a yaml string directly, expanding internal property references.
$yaml_string = file_get_contents("dune.yml");
$expanded = \Grasmash\YamlExpander\Expander::parse($yaml_string);
print_r($expanded);

Resultant array:

array (
  'type' => 'book',
  'book' => 
  array (
    'title' => 'Dune',
    'author' => 'Frank Herbert',
    'copyright' => 'Frank Herbert 1965',
    'protaganist' => 'Paul Atreides',
    'media' => 
    array (
      0 => 'hardcover',
    ),
  ),
  'characters' => 
  array (
    0 => 
    array (
      'name' => 'Paul Atreides',
      'occupation' => 'Kwisatz Haderach',
      'aliases' => 
      array (
        0 => 'Usul',
        1 => 'Muad\'Dib',
        2 => 'The Preacher',
      ),
    ),
    1 => 
    array (
      'name' => 'Duncan Idaho',
      'occupation' => 'Swordmaster',
    ),
  ),
  'summary' => 'Dune by Frank Herbert',
);

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

What is the difference between the HashMap and Map objects in Java?

Map is the static type of map, while HashMap is the dynamic type of map. This means that the compiler will treat your map object as being one of type Map, even though at runtime, it may point to any subtype of it.

This practice of programming against interfaces instead of implementations has the added benefit of remaining flexible: You can for instance replace the dynamic type of map at runtime, as long as it is a subtype of Map (e.g. LinkedHashMap), and change the map's behavior on the fly.

A good rule of thumb is to remain as abstract as possible on the API level: If for instance a method you are programming must work on maps, then it's sufficient to declare a parameter as Map instead of the stricter (because less abstract) HashMap type. That way, the consumer of your API can be flexible about what kind of Map implementation they want to pass to your method.

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

How do I disable Git Credential Manager for Windows?

pretty old topic but this is maybe a help for someone searching for the problem where the above tips does not solved it.

I use

git credential-manager remove -force

How to have EditText with border in Android Lollipop

Write editTextBackground.xml in drawable folder in resources

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="@color/borderColor" />
</shape>

don't forget to declare color in resources named borderColor.

and assign this background to the EditText in xml background attribute

<EditText
    android:id="@+id/text"
    android:background="@drawable/editTextBackground"
    />

and it'll set border to EditText.

UPDATE

You can change border of edit text without drawable by using style attribute

style="@style/Widget.AppCompat.EditText"

for more details visit customize edit text

How do you remove all the options of a select box and then add one option and select it with jQuery?

You can do simply by replacing html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');

Difference between FetchType LAZY and EAGER in Java Persistence API?

The Lazy Fetch type is by default selected by Hibernate unless you explicitly mark Eager Fetch type. To be more accurate and concise, difference can be stated as below.

FetchType.LAZY = This does not load the relationships unless you invoke it via the getter method.

FetchType.EAGER = This loads all the relationships.

Pros and Cons of these two fetch types.

Lazy initialization improves performance by avoiding unnecessary computation and reduce memory requirements.

Eager initialization takes more memory consumption and processing speed is slow.

Having said that, depends on the situation either one of these initialization can be used.

XSS prevention in JSP/Servlet web application

XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

For example:

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as &lt;, &gt;, &quot;, &apos; and &amp;.

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp;amp; instead of &amp; and ultimately the enduser would see &amp; being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.


An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

Better way to call javascript function in a tag

Some advantages to the second option:

  1. You can use this inside onclick to reference the anchor itself (doing the same in option 1 will give you window instead).

  2. You can set the href to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();" and return false from inside the function or onclick="return someFunction(); return false;" to prevent default action).

  3. I've seen weird stuff happen when using href="javascript:someFunction()" and the function returns a value; the whole page would get replaced by just that value.

Pitfalls

Inline code:

  1. Runs in document scope as opposed to code defined inside <script> tags which runs in window scope; therefore, symbols may be resolved based on an element's name or id attribute, causing the unintended effect of attempting to treat an element as a function.

  2. Is harder to reuse; delicate copy-paste is required to move it from one project to another.

  3. Adds weight to your pages, whereas external code files can be cached by the browser.

Best way to implement keyboard shortcuts in a Windows Forms application?

If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.

If not, you could create one and set its visible property to false.

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

Detecting the onload event of a window opened with window.open

If the pop-up's document is from a different domain, this is simply not possible.

Update April 2015: I was wrong about this: if you own both domains, you can use window.postMessage and the message event in pretty much all browsers that are relevant today.

If not, there's still no way you'll be able to make this work cross-browser without some help from the document being loaded into the pop-up. You need to be able to detect a change in the pop-up that occurs once it has loaded, which could be a variable that JavaScript in the pop-up page sets when it handles its own load event, or if you have some control of it you could add a call to a function in the opener.

IE and Edge fix for object-fit: cover;

I achieved satisfying results with:

min-height: 100%;
min-width: 100%;

this way you always maintain the aspect ratio.

The complete css for an image that will replace "object-fit: cover;":

width: auto;
height: auto;
min-width: 100%;
min-height: 100%;
position: absolute;
right: 50%;
transform: translate(50%, 0);

How do I find a default constraint using INFORMATION_SCHEMA?

WHILE EXISTS( 
    SELECT * FROM  sys.all_columns 
    INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
    INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
    INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
    WHERE 
    schemas.name = 'dbo'
    AND ST.name = 'MyTable'
)
BEGIN 
DECLARE @SQL NVARCHAR(MAX) = N'';

SET @SQL = (  SELECT TOP 1
     'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
   FROM 
      sys.all_columns

         INNER JOIN
      sys.tables ST
         ON all_columns.object_id = ST.object_id

         INNER JOIN 
      sys.schemas
         ON ST.schema_id = schemas.schema_id

         INNER JOIN
      sys.default_constraints
         ON all_columns.default_object_id = default_constraints.object_id

   WHERE 
         schemas.name = 'dbo'
      AND ST.name = 'MyTable'
      )
   PRINT @SQL
   EXECUTE sp_executesql @SQL 

   --End if Error 
   IF @@ERROR <> 0 
   BREAK
END 

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

Stashing only staged changes in git - is it possible?

Out of your comments to Mike Monkiewicz answer I suggest to use a simpler model: Use regular development branches, but use the squash option of the merge to get a single commit in your master branch:

git checkout -b bug1    # create the development branch
* hack hack hack *      # do some work
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
* hack hack hack *
git commit
git checkout master     # go back to the master branch
git merge --squash bug1 # merge the work back
git commit              # commit the merge (don't forget
                        #    to change the default commit message)
git branch -D bug1      # remove the development branch

The advantage of this procedure is that you can use the normal git work flow.

C# string replace

Set your Textbox value in a string like:

string MySTring = textBox1.Text;

Then replace your string. For example, replace "Text" with "Hex":

MyString = MyString.Replace("Text", "Hex");

Or for your problem (replace "," with ;) :

MyString = MyString.Replace(@""",""", ",");

Note: If you have "" in your string you have to use @ in the back of "", like:

@"","";

Is there a simple way to convert C++ enum to string?

Adding even more simplicity of use to Jasper Bekkers' fantastic answer:

Set up once:

#define MAKE_ENUM(VAR) VAR,
#define MAKE_STRINGS(VAR) #VAR,
#define MAKE_ENUM_AND_STRINGS(source, enumName, enumStringName) \
    enum enumName { \
    source(MAKE_ENUM) \
    };\
const char* const enumStringName[] = { \
    source(MAKE_STRINGS) \
    };

Then, for usage:

#define SOME_ENUM(DO) \
    DO(Foo) \
    DO(Bar) \
    DO(Baz)
...
MAKE_ENUM_AND_STRINGS(SOME_ENUM, someEnum, someEnumNames)

How to dismiss keyboard for UITextView with return key?

UITextView does not have any methods which will be called when the user hits the return key. If you want the user to be able to add only one line of text, use a UITextField. Hitting the return and hiding the keyboard for a UITextView does not follow the interface guidelines.

Even then if you want to do this, implement the textView:shouldChangeTextInRange:replacementText: method of UITextViewDelegate and in that check if the replacement text is \n, hide the keyboard.

There might be other ways but I am not aware of any.

Mailx send html message

There are many different versions of mail around. When you go beyond mail -s subject to1@address1 to2@address2

  • With some mailx implementations, e.g. from mailutils on Ubuntu or Debian's bsd-mailx, it's easy, because there's an option for that.

    mailx -a 'Content-Type: text/html' -s "Subject" to@address <test.html
    
  • With the Heirloom mailx, there's no convenient way. One possibility to insert arbitrary headers is to set editheaders=1 and use an external editor (which can be a script).

    ## Prepare a temporary script that will serve as an editor.
    
    ## This script will be passed to ed.
    temp_script=$(mktemp)
    cat <<'EOF' >>"$temp_script"
    1a
    Content-Type: text/html
    .
    $r test.html
    w
    q
    EOF
    ## Call mailx, and tell it to invoke the editor script
    EDITOR="ed -s $temp_script" heirloom-mailx -S editheaders=1 -s "Subject" to@address <<EOF
    ~e
    .
    EOF
    rm -f "$temp_script"
    
  • With a general POSIX mailx, I don't know how to get at headers.

If you're going to use any mail or mailx, keep in mind that

  • This isn't portable even within a given Linux distribution. For example, both Ubuntu and Debian have several alternatives for mail and mailx.

  • When composing a message, mail and mailx treats lines beginning with ~ as commands. If you pipe text into mail, you need to arrange for this text not to contain lines beginning with ~.

If you're going to install software anyway, you might as well install something more predictable than mail/Mail/mailx. For example, mutt. With Mutt, you can supply most headers in the input with the -H option, but not Content-Type, which needs to be set via a mutt option.

mutt -e 'set content_type=text/html' -s 'hello' 'to@address' <test.html

Or you can invoke sendmail directly. There are several versions of sendmail out there, but they all support sendmail -t to send a mail in the simplest fashion, reading the list of recipients from the mail. (I think they don't all support Bcc:.) On most systems, sendmail isn't in the usual $PATH, it's in /usr/sbin or /usr/lib.

cat <<'EOF' - test.html | /usr/sbin/sendmail -t
To: to@address
Subject: hello
Content-Type: text/html

EOF

How do I print the elements of a C++ vector in GDB?

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

Could not complete the operation due to error 80020101. IE

when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?

wrap it in

if (window.myTimeout) { 
  clearTimeout(myTimeout);
  myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(.. and this is a matter of variable scope. If so, try this:

window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
    window.message="Logged out";   
}
function timerReset()
{


    clearTimeout(window.myTimeout);
    window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

How to check a string for specific characters?

Quick comparison of timings in response to the post by Abbafei:

import timeit

def func1():
    phrase = 'Lucky Dog'
    return any(i in 'LD' for i in phrase)

def func2():
    phrase = 'Lucky Dog'
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__': 
    func1_time = timeit.timeit(func1, number=100000)
    func2_time = timeit.timeit(func2, number=100000)
    print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))

Output:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.


EDIT : TL;DR -- For long strings, if-then is still much faster than any!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:

# Tested in Python 2.7.14

import timeit
from string import ascii_letters
from random import choice

def create_random_string(length=1000):
    random_list = [choice(ascii_letters) for x in range(length)]
    return ''.join(random_list)

def function_using_any(phrase):
    return any(i in 'LD' for i in phrase)

def function_using_if_then(phrase):
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__':
    random_string = create_random_string(length=2000)
    func1_time = timeit.timeit(stmt="function_using_any(random_string)",
                               setup="from __main__ import function_using_any, random_string",
                               number=200000)
    func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
                               setup="from __main__ import function_using_if_then, random_string",
                               number=200000)
    print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))

Output:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!

How can we generate getters and setters in Visual Studio?

I use Visual Studio 2013 Professional.

  • Place your cursor at the line of an instance variable.

    Enter image description here

  • Press combine keys Ctrl + R, Ctrl + E, or click the right mouse button. Choose context menu RefactorEncapsulate Field..., and then press OK.

    Enter image description here

  • In Preview Reference Changes - Encapsulate Field dialog, press button Apply.

    Enter image description here

  • This is result:

    Enter image description here



You also place the cursor for choosing a property. Use menu EditRefactorEncapsulate Field...

  • Other information:

    Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).

    And

    private int productID;
    
    public int ProductID
    {
        get { return productID; }
        set { productID = value; }
    }
    

    becomes

    public int ProductID { get; set; }
    

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Is the practice of returning a C++ reference variable evil?

You should return a reference to an existing object that isn't going away immediately, and where you don't intend any transfer of ownership.

Never return a reference to a local variable or some such, because it won't be there to be referenced.

You can return a reference to something independent of the function, which you don't expect the calling function to take the responsibility for deleting. This is the case for the typical operator[] function.

If you are creating something, you should return either a value or a pointer (regular or smart). You can return a value freely, since it's going into a variable or expression in the calling function. Never return a pointer to a local variable, since it will go away.

Finding out the name of the original repository you cloned from in Git

Powershell version of command for git repo name:

(git config --get remote.origin.url) -replace '.*/' -replace '.git'

Two dimensional array list

If your platform matrix supports Java 7 then you can use like below

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

Using an integer as a key in an associative array in JavaScript

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

Force sidebar height 100% using CSS (with a sticky bottom image)?

Position absolute, top:0 and bottom:0 for the sidebar and position relative for the wrapper (or container) witch content all the elements and it's done !

How do I edit SSIS package files?

You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.

Have a look at this link:

http://www.microsoft.com/downloads/details.aspx?familyid=3C856B93-369F-4C6F-9357-C35384179543&displaylang=en

How do I get the RootViewController from a pushed controller?

For all who are interested in a swift extension, this is what I'm using now:

extension UINavigationController {
    var rootViewController : UIViewController? {
        return self.viewControllers.first
    }
}

How to execute a command in a remote computer?

Another solution is to use WMI.NET or Windows Management Instrumentation.

Using the .NET Framework namespace System.Management, you can automate administrative tasks using Windows Management Instrumentation (WMI).

Code Sample

using System.Management;
...
var processToRun = new[] { "notepad.exe" };
var connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", REMOTE_COMPUTER_NAME), connection);
var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);

If you have trouble with authentication, then check the DCOM configuration.

  1. On the target machine, run dcomcnfg from the command prompt.
  2. Expand Component Services\Computers\My Computer\DCOM Config
  3. Find Windows Management Instruction, identified with GUID 8BC3F05E-D86B-11D0-A075-00C04FB68820 (you can see this in the details view).
  4. Edit the properties and then add the username you are trying to login with under the permissions tab.
  5. You may need to reboot the service or the entire machine.

NOTE: All paths used for the remote process need to be local to the target machine.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to split a file into equal parts, without breaking individual lines?

var dict = File.ReadLines("test.txt")
               .Where(line => !string.IsNullOrWhitespace(line))
               .Select(line => line.Split(new char[] { '=' }, 2, 0))
               .ToDictionary(parts => parts[0], parts => parts[1]);


or 

    enter code here

line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1][email protected][email protected]"

PHP - check if variable is undefined

You can use -

$isTouch = isset($variable);

It will return true if the $variable is defined. if the variable is not defined it will return false.

Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

If you want to check for false, 0 etc You can then use empty() -

$isTouch = empty($variable);

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

Disable-web-security in Chrome 48+

The chosen answer is good, but for those who are still struggling with what they are talking about(your first time dealing with this issue), the following worked for me.

I created a new shortcut to Chrome on my desktop, right clicked it, and set the "Target" field to the following,

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"

The directory can be anything you want, I decided to make an empty folder called chrome dev in my C: directory. It has nothing to do where chrome is installed on your computer. It's just a fluff type thing.

This link also has clear directions for other OSes. How to disable web securityin Chrome

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

remove this work for me:

<filtering>true</filtering>

I guess it is caused by this filtering bug

Detect & Record Audio in Python

The pyaudio website has many examples that are pretty short and clear: http://people.csail.mit.edu/hubert/pyaudio/

Update 14th of December 2019 - Main example from the above linked website from 2017:


"""PyAudio Example: Play a WAVE file."""

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()

JavaScript object: access variable property by name as string

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

After installation of Gulp: “no command 'gulp' found”

I solved the issue removing gulp and installing gulp-cli again:

rm /usr/local/bin/gulp
npm install -g gulp-cli

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

PYTHONPATH vs. sys.path

Along with the many other reasons mentioned already, you could also point outh that hard-coding

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

How to get first character of a string in SQL?

SUBSTRING ( MyColumn, 1 , 1 ) for the first character and SUBSTRING ( MyColumn, 1 , 2 ) for the first two.

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

Android background music service

i had problem to run it and i make some changes to run it with mp3 source. here is BackfrounSoundService.java file. consider that my mp3 file is in my sdcard in my phone .

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("service", "onCreate");
        player = new MediaPlayer();
        try {
            player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.setLooping(true); // Set looping
        player.setVolume(100, 100);

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service", "onStartCommand");
        try {
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }

    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }

    public void onPause() {

    }

    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

What is "String args[]"? parameter in main method Java

args contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:

$ java MyProg -f file.txt

Then args will be an array containing the strings "-f" and "file.txt".

jQuery hasClass() - check for more than one class

use default js match() function:

if( element.attr('class') !== undefined && element.attr('class').match(/class1|class2|class3|class4|class5/) ) {
  console.log("match");
}

to use variables in regexp, use this:

var reg = new RegExp(variable, 'g');
$(this).match(reg);

by the way, this is the fastest way: http://jsperf.com/hasclass-vs-is-stackoverflow/22

How do I check whether a file exists without exceptions?

import os.path

if os.path.isfile(filepath):
   print("File exists")

Generic type conversion FROM string

With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

public static class ConversionExtensions
{
        public static object Convert(this object value, Type t)
        {
            Type underlyingType = Nullable.GetUnderlyingType(t);

            if (underlyingType != null && value == null)
            {
                return null;
            }
            Type basetype = underlyingType == null ? t : underlyingType;
            return System.Convert.ChangeType(value, basetype);
        }

        public static T Convert<T>(this object value)
        {
            return (T)value.Convert(typeof(T));
        }
}

Examples

            string stringValue = null;
            int? intResult = stringValue.Convert<int?>();

            int? intValue = null;
            var strResult = intValue.Convert<string>();

Simple DateTime sql query

You missed single quote sign:

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

Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.

SELECT *
FROM TABLENAME 
WHERE 
    DateTime >= '2011-04-12T00:00:00.000' AND 
    DateTime <= '2011-05-25T03:53:04.000'

Laravel Eloquent "WHERE NOT IN"

Query Builder:

DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();

Eloquent:

SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();

Is there a /dev/null on Windows?

You have to use start and $NUL for this in Windows PowerShell:

Type in this command assuming mySum is the name of your application and 5 10 are command line arguments you are sending.

start .\mySum  5 10 > $NUL 2>&1

The start command will start a detached process, a similar effect to &. The /B option prevents start from opening a new terminal window if the program you are running is a console application. and NUL is Windows' equivalent of /dev/null. The 2>&1 at the end will redirect stderr to stdout, which will all go to NUL.

Running Composer returns: "Could not open input file: composer.phar"

To solve this issue the first thing you need to do is to get the last version of composer :

curl -sS https://getcomposer.org/installer | php

I recommend you to move the composer.phar file to a global “bin” directoy, in my case (OS X) the path is:

mv composer.phar /usr/local/bin/composer.phar

than you need to create an alias file for an easy access

alias composer='/usr/local/bin/composer.phar'

If everything is ok, now it is time to verify our Composer version:

composer --version

Let's make composer great again.

How can I get the MAC and the IP address of a connected client in PHP?

For windows server I think u can use this:

<?php
echo exec('getmac');
?>

Xcode 4: create IPA file instead of .xcarchive

I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!

I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

How to replace space with comma using sed?

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

Define the selected option with the old input in Laravel / Blade

Also, you can use the ? operator to avoid having to use @if @else @endif syntax. Change:

@if (Input::old('title') == $key)
      <option value="{{ $key }}" selected>{{ $val }}</option>
@else
      <option value="{{ $key }}">{{ $val }}</option>
@endif

Simply to:

<option value="{{ $key }}" {{ (Input::old("title") == $key ? "selected":"") }}>{{ $val }}</option>

How do I check if file exists in jQuery or pure JavaScript?

I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

It seems to work great, hope this helps someone!