Programs & Examples On #Ocaml

OCaml is a strict statically-typed functional programming language, focusing on expressiveness, correctness and efficiency.

Does functional programming replace GoF design patterns?

I think only two GoF Design Patterns are designed to introduce the functional programming logic into natural OO language. I think about Strategy and Command. Some of the other GoF design patterns can be modified by functional programming to simplify the design and keep the purpose.

Language Books/Tutorials for popular languages

Common Lisp

I would add "Practical Common Lisp", by Peter Seibel to the lisp list. It is particularly good at providing examples (MP3 parsing, shoutcast server, HTML compiler) that are topical.

http://gigamonkeys.com/book/

multiple packages in context:component-scan, spring config

If x.y.z is the common package then you can use:

<context:component-scan base-package="x.y.z.*">

it will include all the package that is start with x.y.z like: x.y.z.controller,x.y.z.service etc.

Can you test google analytics on a localhost address?

Updated for 2014

This can now be achieved by simply setting the domain to none.

ga('create', 'UA-XXXX-Y', 'none');

See: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains#localhost

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

Read connection string from web.config

You need to add a reference to System.Configuration and then use:

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

Android button font size

In XML file, the font size of ant text including the button, textView, editText and others can be changed by the adding

android:textSize="10sp"

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

Change Timezone in Lumen or Laravel 5

Use php time zones from php manual Php time zones

For example mine i changed from the UTC value in config/app.php with

'timezone' => 'Africa/Nairobi',

Truncate/round whole number in JavaScript?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

convert '1' to '0001' in JavaScript

Just to demonstrate the flexibility of javascript: you can use a oneliner for this

function padLeft(nr, n, str){
    return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
    return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5));       //=> '00023'
console.log((23).padLeft(5));     //=> '00023'
console.log((23).padLeft(5,' ')); //=> '   23'
console.log(padLeft(23,5,'>>'));  //=> '>>>>>>23'

If you want to use this for negative numbers also:

Number.prototype.padLeft = function (n,str) {
    return (this < 0 ? '-' : '') + 
            Array(n-String(Math.abs(this)).length+1)
             .join(str||'0') + 
           (Math.abs(this));
}
console.log((-23).padLeft(5));     //=> '-00023'

Alternative if you don't want to use Array:

number.prototype.padLeft = function (len,chr) {
 var self = Math.abs(this)+'';
 return (this<0 && '-' || '')+
         (String(Math.pow( 10, (len || 2)-self.length))
           .slice(1).replace(/0/g,chr||'0') + self);
}

HTTP Basic Authentication - what's the expected web browser experience?

If there are no credentials provided in the request headers, the following is the minimum response required for IE to prompt the user for credentials and resubmit the request.

Response.Clear();
Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
Response.AddHeader("WWW-Authenticate", "Basic");

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

I think is because you have try to persist an object that have a reference to another object that is not persist yet, and so it try in the "DB side" to put a reference to a row that not exists

How do I revert an SVN commit?

svn merge -c -M PATH

This saved my life.

I was having the same issue, after reverting back also I was not seeing old code. After running the above command I got a clean old version code.

BeanFactory vs ApplicationContext

Basically we can create spring container object in two ways

  1. using BeanFactory.
  2. using ApplicationContext.

both are the interfaces,

using implementation classes we can create object for spring container

coming to the differences

BeanFactory :

  1. Does not support the Annotation based dependency Injection.

  2. Doesn't Support I18N.

  3. By default its support Lazy loading.

  4. it doesn't allow configure to multiple configuration files.

ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));

ApplicationContext

  1. Support Annotation based dependency Injection.-@Autowired, @PreDestroy

  2. Support I18N

  3. Its By default support Aggresive loading.

  4. It allow to configure multiple configuration files.

ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");

Can I extend a class using more than 1 class in PHP?

You cannot have a class that extends two base classes. You could not have.

// this is NOT allowed (for all you google speeders)
Matron extends Nurse, HumanEntity

You could however have a hierarchy as follows...

Matron extends Nurse    
Consultant extends Doctor

Nurse extends HumanEntity
Doctor extends HumanEntity

HumanEntity extends DatabaseTable
DatabaseTable extends AbstractTable

and so on.

Get the last inserted row ID (with SQL statement)

Assuming a simple table:

CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);

We can capture IDENTITY values in a table variable for further consumption.

DECLARE @IDs TABLE(ID INT);

-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name) 
  OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';

SELECT ID FROM @IDs;

The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.

How to clear Route Caching on server: Laravel 5.2.37

you can define a route in web.php

Route::get('/clear/route', 'ConfigController@clearRoute');

and make ConfigController.php like this

   class ConfigController extends Controller
{
    public function clearRoute()
    {
        \Artisan::call('route:clear');
    }
}

and go to that route on server example http://your-domain/clear/route

Oracle: how to INSERT if a row doesn't exist

I found the examples a bit tricky to follow for the situation where you want to ensure a row exists in the destination table (especially when you have two columns as the primary key), but the primary key might not exist there at all so there's nothing to select.

This is what worked for me:

MERGE INTO table1 D
    USING (
        -- These are the row(s) you want to insert.
        SELECT 
        'val1' AS FIELD_A,
        'val2' AS FIELD_B
        FROM DUAL

    ) S ON (
        -- This is the criteria to find the above row(s) in the
        -- destination table.  S refers to the rows in the SELECT
        -- statement above, D refers to the destination table.
        D.FIELD_A = S.FIELD_A
        AND D.FIELD_B = S.FIELD_B
    )

    -- This is the INSERT statement to run for each row that
    -- doesn't exist in the destination table.
    WHEN NOT MATCHED THEN INSERT (
        FIELD_A,
        FIELD_B,
        FIELD_C
    ) VALUES (
        S.FIELD_A,
        S.FIELD_B,
        'val3'
    )

The key points are:

  • The SELECT statement inside the USING block must always return rows. If there are no rows returned from this query, no rows will be inserted or updated. Here I select from DUAL so there will always be exactly one row.
  • The ON condition is what sets the criteria for matching rows. If ON does not have a match then the INSERT statement is run.
  • You can also add a WHEN MATCHED THEN UPDATE clause if you want more control over the updates too.

Best C/C++ Network Library

Aggregated List of Libraries

How do I extract data from JSON with PHP?

The acepted Answer is very detailed and correct in most of the cases.

I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.

To solve it, i made this PHP function:

function load_utf8_file($filePath)
{
    $response = null;
    try
    {
        if (file_exists($filePath)) {
            $text = file_get_contents($filePath);
            $response = preg_replace("/^\xEF\xBB\xBF/", '', $text);          
        }     
    } catch (Exception $e) {
      echo 'ERROR: ',  $e->getMessage(), "\n";
   }
   finally{  }
   return $response;
}

Then i use it like this to load a JSON file and get a value from it:

$str = load_utf8_file('appconfig.json'); 
$json = json_decode($str, true); 
//print_r($json);
echo $json['prod']['deploy']['hostname'];

What is meant with "const" at end of function declaration?

Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.

MySQL, create a simple function

MySQL function example:

Open the mysql terminal:

el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>

Drop the function if it already exists

mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Create the function

mysql> create function hello(id INT)
    -> returns CHAR(50)
    -> return 'foobar';
Query OK, 0 rows affected (0.01 sec)

Create a simple table to test it out with

mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)

Insert three values into the table yar

mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

Select all the values from yar, run our function hello each time:

mysql> select id, hello(5) from yar;
+------+----------+
| id   | hello(5) |
+------+----------+
|    5 | foobar   |
|    7 | foobar   |
|    9 | foobar   |
+------+----------+
3 rows in set (0.01 sec)

Verbalize and internalize what just happened:

You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50) containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5) for each row returned by yar.

Git SSH error: "Connect to host: Bad file number"

I just had the same problem and tried every solution that I could find, but none worked. Eventually, I tried quitting Git Bash and re-opening it, and everything worked perfectly.

So, try quitting Git Bash and re-opening it.

What are some reasons for jquery .focus() not working?

The problem in my case was that I entered a value IN THE LAST NOT DISABLED ELEMENT of the site and used tab to raise the onChange-Event. After that there is no next element to get the focus, so the "browser"-Focus switches to the browser-functionality (tabs, menu, and so on) and is not any longer inside the html-content.

To understand that, place a displayed, not disabled dummy-textbox at the end of your html-code. In that you can "park" the focus for later replacing. Should work. In my case. All other tries didnt work, also the setTimeout-Version.

Checked this out for about an hour, because it made me insane :)

Mätes

How to add a vertical Separator?

<Style x:Key="MySeparatorStyle" TargetType="{x:Type Separator}">
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/>
                <Setter Property="Margin" Value="10,0,10,0"/>
                <Setter Property="Focusable" Value="false"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Separator}">
                            <Border 
                                  BorderBrush="{TemplateBinding BorderBrush}" 
                                  BorderThickness="{TemplateBinding BorderThickness}" 
                                  Background="{TemplateBinding Background}" 
                                  Height="20" 
                                  Width="3" 
                                  SnapsToDevicePixels="true"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

use

<StackPanel  Orientation="Horizontal"  >
       <TextBlock>name</TextBlock>
           <Separator Style="{StaticResource MySeparatorStyle}" ></Separator>
       <Button>preview</Button>
 </StackPanel>

How to remove/ignore :hover css style on touch devices

Try this easy 2019 jquery solution, although its been around a while;

  1. add this plugin to head:

    src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"

  2. add this to js:

    $("*").on("touchend", function(e) { $(this).focus(); }); //applies to all elements

  3. some suggested variations to this are:

    $(":input, :checkbox,").on("touchend", function(e) {(this).focus);}); //specify elements

    $("*").on("click, touchend", function(e) { $(this).focus(); }); //include click event

    css: body { cursor: pointer; } //touch anywhere to end a focus

Notes

  • place plugin before bootstrap.js to avoif affecting tooltips
  • only tested on iphone XR ios 12.1.12, and ipad 3 ios 9.3.5, using Safari or Chrome.

References:

https://code.jquery.com/ui/

https://api.jquery.com/category/selectors/jquery-selector-extensions/

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

Angular 2 Scroll to top on Route Change

You can also use scrollOffset in Route.ts. Ref. Router ExtraOptions

@NgModule({
  imports: [
    SomeModule.forRoot(
      SomeRouting,
      {
        scrollPositionRestoration: 'enabled',
        scrollOffset:[0,0]
      })],
  exports: [RouterModule]
})

How to make a owl carousel with arrows instead of next previous

If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

$('.your-class').owlCarousel({
        loop: true,
        items: 1, // Select Item Number
        autoplay:true,
        dots: false,
        nav: true,
        navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],

    });

How to prevent a double-click using jQuery?

"Easy Peasy"

$(function() {
     $('.targetClass').dblclick(false);
});

Get current time as formatted string in Go?

As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:

msec := time.Now().UnixNano() / 1000000

Resource: https://gobyexample.com/epoch

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

How to list all AWS S3 objects in a bucket using Java

This is direct from AWS documentation:

AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());        

ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
    .withBucketName(bucketName)
    .withPrefix("m");
ObjectListing objectListing;

do {
        objectListing = s3client.listObjects(listObjectsRequest);
        for (S3ObjectSummary objectSummary : 
            objectListing.getObjectSummaries()) {
            System.out.println( " - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + 
                    ")");
        }
        listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());

ExecutorService that interrupts tasks after a timeout

How about using the ExecutorService.shutDownNow() method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.

How can I add a hint or tooltip to a label in C# Winforms?

You have to add a ToolTip control to your form first. Then you can set the text it should display for other controls.

Here's a screenshot showing the designer after adding a ToolTip control which is named toolTip1:

enter image description here

Find element's index in pandas Series

you can use Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 

How to install npm peer dependencies automatically?

I solved it by rewriting package.json with the exact values warnings were about.

Warnings when running npm:

npm WARN [email protected] requires a peer of es6-shim@^0.33.3 but none was installed.
npm WARN [email protected] requires a peer of [email protected]

In package.json, write

"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",

Then, delete node_modules directory.

Finally, run the command below:

npm install

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

Spring's overriding bean

Since Spring 3.0 you can use @Primary annotation. As per documentation:

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the element's primary attribute in Spring XML.

You should use it on Bean definition like this:

@Bean
@Primary
public ExampleBean exampleBean(@Autowired EntityManager em) {
    return new ExampleBeanImpl(em);
}

or like this:

@Primary
@Service
public class ExampleService implements BaseServive {
}

How can I close a login form and show the main form without my application closing?

you should do it the other way round:

Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform

EDIT: As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).

Running multiple commands with xargs

You can use

cat file.txt | xargs -i  sh -c 'command {} | command2 {} && command3 {}'

{} = variable for each line on the text file

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

How to find the extension of a file in C#?

This solution also helps in cases of more than one extension like "Avishay.student.DB"

                FileInfo FileInf = new FileInfo(filePath);
                string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");

How to set top-left alignment for UILabel for iOS application?

Rather than re-explaining, I will link to this rather extensive & highly rated question/answer:

Vertically align text to top within a UILabel

The short answer is no, Apple didn't make this easy, but it is possible by changing the frame size.

Appending a line to a file only if it does not already exist

another sed solution is to always append it on the last line and delete a pre existing one.

sed -e '$a\' -e '<your-entry>' -e "/<your-entry-properly-escaped>/d"

"properly-escaped" means to put a regex that matches your entry, i.e. to escape all regex controls from your actual entry, i.e. to put a backslash in front of ^$/*?+().

this might fail on the last line of your file or if there's no dangling newline, I'm not sure, but that could be dealt with by some nifty branching...

Remove non-ASCII characters from CSV

I tried all the solutions and nothing worked. The following, however, does:

tr -cd '\11\12\15\40-\176'

Which I found here:

https://alvinalexander.com/blog/post/linux-unix/how-remove-non-printable-ascii-characters-file-unix

My problem needed it in a series of piped programs, not directly from a file, so modify as needed.

How to detect if a string contains at least a number?

DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'

IF PATINDEX('%[0-9]%', @str) > 0
   PRINT 'YES, The string has numbers'
ELSE
   PRINT 'NO, The string does not have numbers' 

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

'python3' is not recognized as an internal or external command, operable program or batch file

Yes, I think for Windows users you need to change all the python3 calls to python to solve your original error. This change will run the Python version set in your current environment. If you need to keep this call as it is (aka python3) because you are working in cross-platform or for any other reason, then a work around is to create a soft link. To create it, go to the folder that contains the Python executable and create the link. For example, this worked in my case in Windows 10 using mklink:

cd C:\Python3
mklink python3.exe python.exe

Use a (soft) symbolic link in Linux:

cd /usr/bin/python3
ln -s python.exe python3.exe

a href link for entire div in HTML/CSS

What I would do is put a span inside the <a> tag, set the span to block, and add size to the span, or just apply the styling to the <a> tag. Definitely handle the positioning in the <a> tag style. Add an onclick event to the a where JavaScript will catch the event, then return false at the end of the JavaScript event to prevent default action of the href and bubbling of the click. This works in cases with or without JavaScript enabled, and any AJAX can be handled in the Javascript listener.

If you're using jQuery, you can use this as your listener and omit the onclick in the a tag.

$('#idofdiv').live("click", function(e) {
    //add stuff here
    e.preventDefault; //or use return false
}); 

this allows you to attach listeners to any changed elements as necessary.

How to convert dataframe into time series?

See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,

Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

And further suggests an explicit conversion using order.by = as.POSIXct,

df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))

Where your format is assigned elswhere,

format <- "%m/%d/%Y" #see strptime for details

How do I open a second window from the first window in WPF?

This helped me: The Owner method basically ties the window to another window in case you want extra windows with the same ones.

LoadingScreen lc = new LoadingScreen();
lc.Owner = this;
lc.Show();

Consider this as well.

this.WindowState = WindowState.Normal;
this.Activate();

How to implement a binary search tree in Python?

    def BinaryST(list1,key):
    start = 0
    end = len(list1)
    print("Length of List: ",end)

    for i in range(end):
        for j in range(0, end-i-1):
            if(list1[j] > list1[j+1]):
                temp = list1[j]
                list1[j] = list1[j+1]
                list1[j+1] = temp

    print("Order List: ",list1)

    mid = int((start+end)/2)
    print("Mid Index: ",mid)

    if(key == list1[mid]):
        print(key," is on ",mid," Index")

    elif(key > list1[mid]):
        for rindex in range(mid+1,end):
            if(key == list1[rindex]):
                print(key," is on ",rindex," Index")
                break
            elif(rindex == end-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue

    elif(key < list1[mid]):
        for lindex in range(0,mid):
            if(key == list1[lindex]):
                print(key," is on ",lindex," Index")
                break
            elif(lindex == mid-1):
                print("Given key: ",key," is not in List")
                break
            else:
                continue


size = int(input("Enter Size of List: "))
list1 = []
for e in range(size):
    ele = int(input("Enter Element in List: "))
    list1.append(ele)

key = int(input("\nEnter Key for Search: "))

print("\nUnorder List: ",list1)
BinaryST(list1,key)

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

How to trigger an event after using event.preventDefault()

as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.

if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

Virtual member call in a constructor

Just to add my thoughts. If you always initialize the private field when define it, this problem should be avoid. At least below code works like a charm:

class Parent
{
    public Parent()
    {
        DoSomething();
    }
    protected virtual void DoSomething()
    {
    }
}

class Child : Parent
{
    private string foo = "HELLO";
    public Child() { /*Originally foo initialized here. Removed.*/ }
    protected override void DoSomething()
    {
        Console.WriteLine(foo.ToLower());
    }
}

How to scale down a range of numbers with a known min and max value

Here's how I understand it:


What percent does x lie in a range

Let's assume you have a range from 0 to 100. Given an arbitrary number from that range, what "percent" from that range does it lie in? This should be pretty simple, 0 would be 0%, 50 would be 50% and 100 would be 100%.

Now, what if your range was 20 to 100? We cannot apply the same logic as above (divide by 100) because:

20 / 100

doesn't give us 0 (20 should be 0% now). This should be simple to fix, we just need to make the numerator 0 for the case of 20. We can do that by subtracting:

(20 - 20) / 100

However, this doesn't work for 100 anymore because:

(100 - 20) / 100

doesn't give us 100%. Again, we can fix this by subtracting from the denominator as well:

(100 - 20) / (100 - 20)

A more generalized equation for finding out what % x lies in a range would be:

(x - MIN) / (MAX - MIN)

Scale range to another range

Now that we know what percent a number lies in a range, we can apply it to map the number to another range. Let's go through an example.

old range = [200, 1000]
new range = [10, 20]

If we have a number in the old range, what would the number be in the new range? Let's say the number is 400. First, figure out what percent 400 is within the old range. We can apply our equation above.

(400 - 200) / (1000 - 200) = 0.25

So, 400 lies in 25% of the old range. We just need to figure out what number is 25% of the new range. Think about what 50% of [0, 20] is. It would be 10 right? How did you arrive at that answer? Well, we can just do:

20 * 0.5 = 10

But, what about from [10, 20]? We need to shift everything by 10 now. eg:

((20 - 10) * 0.5) + 10

a more generalized formula would be:

((MAX - MIN) * PERCENT) + MIN

To the original example of what 25% of [10, 20] is:

((20 - 10) * 0.25) + 10 = 12.5

So, 400 in the range [200, 1000] would map to 12.5 in the range [10, 20]


TLDR

To map x from old range to new range:

OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN

What is the difference between char s[] and char *s?

char s[] = "hello";

declares s to be an array of char which is long enough to hold the initializer (5 + 1 chars) and initializes the array by copying the members of the given string literal into the array.

char *s = "hello";

declares s to be a pointer to one or more (in this case more) chars and points it directly at a fixed (read-only) location containing the literal "hello".

IPC performance: Named Pipe vs Socket

As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).

This benchmark shows a difference of about 12 to 15% faster speed for pipes.

Rails 3.1 and Image Assets

You'll want to change the extension of your css file from .css.scss to .css.scss.erb and do:

background-image:url(<%=asset_path "admin/logo.png"%>);

You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.

In production, make sure

rm -rf public/assets    
bundle exec rake assets:precompile RAILS_ENV=production

happens upon deployment.

Setting up a git remote origin

For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add to do this will result in "fatal: remote origin already exists."

Nutshell: git remote set-url origin https://github.com/username/repo

(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)

What's the best UI for entering date of birth?

I would prefer a datepicker (and a input box with documented format as a fall-back) for an international site.

Date formats vary and are sometimes hard to read if you are now used to them. Too bad many people aren't comfortable with ISO 8601. :-(

How do I create a MessageBox in C#?

MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like

if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
     //some interesting behaviour here
}

which I guess is a bit unwieldy but it gets the job done.

See https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here.

Git undo local branch delete

This worked for me:

git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

Remove a folder from git tracking

I know this is an old thread but I just wanted to add a little as the marked solution didn't solve the problem for me (although I tried many times).

The only way I could actually stop git form tracking the folder was to do the following:

  1. Make a backup of the local folder and put in a safe place.
  2. Delete the folder from your local repo
  3. Make sure cache is cleared git rm -r --cached your_folder/
  4. Add your_folder/ to .gitignore
  5. Commit changes
  6. Add the backup back into your repo

You should now see that the folder is no longer tracked.

Don't ask me why just clearing the cache didn't work for me, I am not a Git super wizard but this is how I solved the issue.

SET NOCOUNT ON usage

Regarding the triggers breaking NHibernate, I had that experience first-hand. Basically, when NH does an UPDATE it expects certain number of rows affected. By adding SET NOCOUNT ON to the triggers you get the number of rows back to what NH expected thereby fixing the issue. So yeah, I would definitely recommend turning it off for triggers if you use NH.

Regarding the usage in SPs, it's a matter of personal preference. I had always turned the row count off, but then again, there are no real strong arguments either way.

On a different note, you should really consider moving away from SP-based architecture, then you won't even have this question.

How to parse freeform street/postal address out of text, and into components

UPDATE: Geocode.xyz now works worldwide. For examples see https://geocode.xyz

For USA, Mexico and Canada, see geocoder.ca.

For example:

Input: something going on near the intersection of main and arthur kill rd new york

Output:

<geodata>
  <latt>40.5123510000</latt>
  <longt>-74.2500500000</longt>
  <AreaCode>347,718</AreaCode>
  <TimeZone>America/New_York</TimeZone>
  <standard>
    <street1>main</street1>
    <street2>arthur kill</street2>
    <stnumber/>
    <staddress/>
    <city>STATEN ISLAND</city>
    <prov>NY</prov>
    <postal>11385</postal>
    <confidence>0.9</confidence>
  </standard>
</geodata>

You may also check the results in the web interface or get output as Json or Jsonp. eg. I'm looking for restaurants around 123 Main Street, New York

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

You can try change your type connection to branch from ssh to https.

  1. nano project_path/.git/config
  2. Replace [email protected]:username/repository.git to https://[email protected]/username/repository_name.git
  3. Save file ctrl + o

After that you can try git pull without publickey

How to get all registered routes in Express?

A function to log all routes in express 4 (can be easily tweaked for v3~)

function space(x) {
    var res = '';
    while(x--) res += ' ';
    return res;
}

function listRoutes(){
    for (var i = 0; i < arguments.length;  i++) {
        if(arguments[i].stack instanceof Array){
            console.log('');
            arguments[i].stack.forEach(function(a){
                var route = a.route;
                if(route){
                    route.stack.forEach(function(r){
                        var method = r.method.toUpperCase();
                        console.log(method,space(8 - method.length),route.path);
                    })
                }
            });
        }
    }
}

listRoutes(router, routerAuth, routerHTML);

Logs output:

GET       /isAlive
POST      /test/email
POST      /user/verify

PUT       /login
POST      /login
GET       /player
PUT       /player
GET       /player/:id
GET       /players
GET       /system
POST      /user
GET       /user
PUT       /user
DELETE    /user

GET       /
GET       /login

Made this into a NPM https://www.npmjs.com/package/express-list-routes

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

The solutions that search a file for a substring can also search a string, eg. find or findstr.
In your case, the easy solution would be to pipe a string into the command instead of supplying a filename eg.

case-sensitive string:
echo "abcdefg" | find "bcd"

ignore case of string:
echo "abcdefg" | find /I "bcd"

IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1

What's the default password of mariadb on fedora?

I hit the same issue and none of the solutions worked. I then bumped an answer in stackexchange dba which lead to this link. So here is what I did:

  1. ran sudo mysqld_safe --skip-grant-tables --skip-networking &
  2. ran sudo mysql -uroot and got into mysql console
  3. run ALTER USER root@localhost identified via unix_socket; and flush privileges; consecutively to allow for password-less login

If you want to set the password then you need to do one more step, that is running ALTER USER root@localhost IDENTIFIED VIA mysql_native_password; and SET PASSWORD = PASSWORD('YourPasswordHere'); consecutively.

UPDATE

Faced this issue recently and here is how I resolved it with recent version, but before that some background. Mariadb does not require a password when is run as root. So first run it as a root. Then once in the Mariadb console, change password there. If you are content with running it as admin, you can just keep doing it but I find that cumbersome especially because I cannot use that with DB Admin Tools. TL;DR here is how I did it on Mac (should be similar for *nix systems)

sudo mariadb-secure-installation

then follow instructions on the screen!

Hope this will help someone and serve me a reference for future problems

Javascript / Chrome - How to copy an object from the webkit inspector as code

You can copy an object to your clip board using copy(JSON.stringify(Object_Name)); in the console.

Eg:- Copy & Paste the below code in your console and press ENTER. Now, try to paste(CTRL+V for Windows or CMD+V for mac) it some where else and you will get {"name":"Daniel","age":25}

var profile = {
    name: "Daniel",
    age: 25
};

copy(JSON.stringify(profile));

MySQL Error: #1142 - SELECT command denied to user

I run into this problem as well, the case with me was incorrect naming . I was migrating from local server to online server. my SQL command had "database.tablename.column" structure. the name of database in online server was different. for example my code was "pet.item.name" while it needed to be "pet_app.item.name" changing database name solved my problem.

How to save a spark DataFrame as csv on disk?

I had similar issue where i had to save the contents of the dataframe to a csv file of name which i defined. df.write("csv").save("<my-path>") was creating directory than file. So have to come up with the following solutions. Most of the code is taken from the following dataframe-to-csv with little modifications to the logic.

def saveDfToCsv(df: DataFrame, tsvOutput: String, sep: String = ",", header: Boolean = false): Unit = {
    val tmpParquetDir = "Posts.tmp.parquet"

    df.repartition(1).write.
        format("com.databricks.spark.csv").
        option("header", header.toString).
        option("delimiter", sep).
        save(tmpParquetDir)

    val dir = new File(tmpParquetDir)
    val newFileRgex = tmpParquetDir + File.separatorChar + ".part-00000.*.csv"
    val tmpTsfFile = dir.listFiles.filter(_.toPath.toString.matches(newFileRgex))(0).toString
    (new File(tmpTsvFile)).renameTo(new File(tsvOutput))

    dir.listFiles.foreach( f => f.delete )
    dir.delete
    }

How to move certain commits to be based on another branch in git?

I believe it's:

git checkout master
git checkout -b good_quickfix2
git cherry-pick quickfix2^
git cherry-pick quickfix2

How to play videos in android from assets folder or raw folder?

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

Scale an equation to fit exact page width

\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

or

\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}

Stopping python using ctrl+c

Capture the KeyboardInterrupt (which is launched by pressing ctrl+c) and force the exit:

from sys import exit

try:
    # Your code
    command = input('Type your command: ')

except KeyboardInterrupt:
    # User interrupt the program with ctrl+c
    exit()

How to go from one page to another page using javascript?

Easier method is window.location.href = "http://example.com/new_url";

But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.

html form -

<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >         
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" name="submitBt"value="LogIn" />
</form>

javascript validation-

function validateForm(){
    var uname = document.forms["myForm"]["username"].value;
    var pass = document.forms["myForm"]["password"].value;

    if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){

        return true;
    }else{
        return false;
    }
}

function isEmpty(elemValue, field){
    if((elemValue == "") || (elemValue == null)){
        alert("you can not have "+field+" field empty");
        return true;
    }else{
        return false;
    }
}

check if user in the database using php

<?php
    $con = mysqli_connect("localhost","root","1234","users");

    if(mysqli_connect_errno()){
        echo "Couldn't connect ".mysqli_connect_error();
    }else{
        //echo "connection successful <br />";
    }

    $uname_tb = $_POST['username'];
    $pass_tb = $_POST['password'];

    $query ="SELECT * FROM user";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
            echo "Login Successful";
            header('Location: dashbord.php');
            exit();
        }else{
            echo "You are not in our database".mysqli_connect_error();
        }
    }
    mysqli_close($con);
?>

Reading Space separated input in python

For Python3:

a, b = list(map(str, input().split()))
v = int(b)

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

No signing certificate "iOS Distribution" found

enter image description here

Solution Steps:

  1. Unchecked "Automatically manage signing".

  2. Select "Provisioning profile" in "Signing (Release)" section.

  3. No signing certificate error will be show.

  4. Then below the error has a "Manage Certificates" button. click the button.

enter image description here

  1. This window will come. Click the + sign and click "iOS Distribution". xcode will create the private key for your distribution certificate and error will be gone.

How do I get the file extension of a file in Java?

Without use of any library, you can use the String method split as follows :

        String[] splits = fileNames.get(i).split("\\.");

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }

How to delete/remove nodes on Firebase

In case you are using axios and trying via a service call.

URL: https://react-16-demo.firebaseio.com/
Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE

axios.delete(`https://react-16-demo.firebaseio.com/todos/-Lhu8a0uoSRixdmECYPE.json`). then();

can help.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

for the people who are facing below error in mysql 5.7+ version -

Access denied for user 'root'@'localhost' (using password: YES)
  1. Open new terminal

  2. sudo /etc/init.d/mysql stop ... MySQL Community Server 5.7.8-rc is stopped

  3. sudo mysqld_safe --skip-grant-tables & this will skipp all grant level privileges and start the mysql in safe mode Sometimes the process got stucked just because of

grep: write error: Broken pipe 180102 11:32:28 mysqld_safe Logging to '/var/log/mysql/error.log'.

Simply press Ctrl+Z or Ctrl+C to interrupt and exit process

  1. mysql -u root

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

  1. mysql> use mysql;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

  1. mysql> update user set authentication_string=password('password') where user='root'; Query OK, 4 rows affected, 1 warning (0.03 sec) Rows matched: 4 Changed: 4 Warnings: 1

  2. mysql> flush privileges; Query OK, 0 rows affected (0.00 sec)

  3. mysql> quit Bye

  4. sudo /etc/init.d/mysql stop

..180102 11:37:12 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended . * MySQL Community Server 5.7.8-rc is stopped arif@ubuntu:~$ sudo /etc/init.d/mysql start .. * MySQL Community Server 5.7.8-rc is started

  1. mysql -u root -p

    Enter password:

    Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)

after mysql 5.7+ version the column password replaced by name authentication_string from the mysql.user table.

hope these steps will help anyone, thanks.

Java reading a file into an ArrayList?

A one-liner with commons-io:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

The same with guava:

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));

what innerHTML is doing in javascript?

innerHTML explanation with example:

The innerHTML manipulates the HTML content of an element(get or set). In the example below if you click on the Change Content link it's value will be updated by using innerHTML property of anchor link Change Content

Example:

_x000D_
_x000D_
<a id="example" onclick='testFunction()'>Change Content</a>_x000D_
_x000D_
<script>_x000D_
  function testFunction(){_x000D_
    // change the content using innerHTML_x000D_
    document.getElementById("example").innerHTML = "This is dummy content";_x000D_
_x000D_
    // get the content using innerHTML_x000D_
    alert(document.getElementById("example").innerHTML)_x000D_
_x000D_
  }_x000D_
</script>_x000D_
    
_x000D_
_x000D_
_x000D_

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

Ubuntu: OpenJDK 8 - Unable to locate package

sudo apt-get update
sudo apt-get  install openjdk-8-jdk

this should work

Why should we typedef a struct so often in C?

A> a typdef aids in the meaning and documentation of a program by allowing creation of more meaningful synonyms for data types. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).

B> a structure defines a type. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit

C> typedef'ing a struct is explained in A above.

D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames.

Why I've got no crontab entry on OS X when using vim?

Use another text editor

env EDITOR=nano crontab -e 

or

env EDITOR=code crontab -e 

How does the keyword "use" work in PHP and can I import classes with it?

You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

How to wait in a batch script?

I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html

Calculate percentage saved between two numbers?

100% - discounted price / full price

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

You need junit-dep.jar because the junit.jar has a copy of old Hamcrest classes.

Center Triangle at Bottom of Div

Check this:

http://jsfiddle.net/SxKr5/3/

.hero1
{
    width: 90%;
    height: 200px;
    margin: auto;
    background-color: #e15915;
}

.hero2
{
    width: 0px;
    height: 0px;
    border-style: solid;
    margin: auto;
    border-width: 90px 58px 0 58px;
    border-color: #e15915 transparent transparent transparent;
    line-height: 0px;
    _border-color: #e15915 #000000 #000000 #000000;
    _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000')
}

C++ convert hex string to signed integer

This worked for me:

string string_test = "80123456";
unsigned long x;
signed long val;

std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val;  // if I try this val = 0
val = (signed long)x;  // However, if I cast the unsigned result I get val = 0x80123456 

MVC 4 Razor adding input type date

 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()

How to add a default include path for GCC in Linux?

Create an alias for gcc with your favorite includes.

alias mygcc='gcc -I /whatever/'

Best way to combine two or more byte arrays in C#

Concat is the right answer, but for some reason a handrolled thing is getting the most votes. If you like that answer, perhaps you'd like this more general solution even more:

    IEnumerable<byte> Combine(params byte[][] arrays)
    {
        foreach (byte[] a in arrays)
            foreach (byte b in a)
                yield return b;
    }

which would let you do things like:

    byte[] c = Combine(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }).ToArray();

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

MySQL command line client for Windows

You can also download MySql workbench (31Mo) which includes mysql.exe and mysqldump.exe.

I successfully tested this when i had to run Perl scripts using DBD:MySql module to run SQL statements against a distant MySql db.

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How to read a string one letter at a time in python

# Retain a map of the Morse code
conversion = {}

# Read map from file, add it to the datastructure
morseCodeFile = file('morseCode.txt')
for line in moreCodeFile:
    conversion[line[0]] = line[2:]
morseCodeFile.close()

# Ask for input from the user
s = raw_input("Please enter string to translate")
# Go over each character, and print it the translation.
# Defensive programming: do something sane if the user 
# inputs non-Morse compatible strings.    
for c in s:
    print conversion.get(c, "No translation for "+c)

Xcode 4: How do you view the console?

You need to click Log Navigator icon (far right in left sidebar). Then choose your Debug/Run session in left sidebar, and you will have console in editor area.

enter image description here

Spark java.lang.OutOfMemoryError: Java heap space

Broadly speaking, spark Executor JVM memory can be divided into two parts. Spark memory and User memory. This is controlled by property spark.memory.fraction - the value is between 0 and 1. When working with images or doing memory intensive processing in spark applications, consider decreasing the spark.memory.fraction. This will make more memory available to your application work. Spark can spill, so it will still work with less memory share.

The second part of the problem is division of work. If possible, partition your data into smaller chunks. Smaller data possibly needs less memory. But if that is not possible, you are sacrifice compute for memory. Typically a single executor will be running multiple cores. Total memory of executors must be enough to handle memory requirements of all concurrent tasks. If increasing executor memory is not a option, you can decrease the cores per executor so that each task gets more memory to work with. Test with 1 core executors which have largest possible memory you can give and then keep increasing cores until you find the best core count.

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

How to run a program without an operating system?

How do you run a program all by itself without an operating system running?

You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).

Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?

General answer to the question: it can be done. It's often referred to as "bare metal programming". To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.

Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.

Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.

Edit: This article, and the whole wiki.osdev.org will anwer most of your questions http://wiki.osdev.org/Introduction

Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.

Convert Mongoose docs to json

It worked for me:

Products.find({}).then(a => console.log(a.map(p => p.toJSON())))


also if you want use getters, you should add its option also (on defining schema):

new mongoose.Schema({...}, {toJSON: {getters: true}})

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

This might help someone:

I am installing the latest Java on my system for development, and currently it's Java SE 7. Now, let's dive into this "madness", as you put it...

All of these are the same (when developers are talking about Java for development):

  • Java SE 7
  • Java SE v1.7.0
  • Java SE Development Kit 7

Starting with Java v1.5:

  • v5 = v1.5.
  • v6 = v1.6.
  • v7 = v1.7.

And we can assume this will remain for future versions.

Next, for developers, download JDK, not JRE.

JDK will contain JRE. If you need JDK and JRE, get JDK. Both will be installed from the single JDK install, as you will see below.

As someone above mentioned:

  • JDK = Java Development Kit (developers need this, this is you if you code in Java)
  • JRE = Java Runtime Environment (users need this, this is every computer user today)
  • Java SE = Java Standard Edition

Here's the step by step links I followed (one step leads to the next, this is all for a single download) to download Java for development (JDK):

  1. Visit "Java SE Downloads": http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Click "JDK Download" and visit "Java SE Development Kit 7 Downloads": http://www.oracle.com/technetwork/java/javase/downloads/java-se-jdk-7-download-432154.html (note that following the link from step #1 will take you to a different link as JDK 1.7 updates, later versions, are now out)
  3. Accept agreement :)
  4. Click "Java SE Development Kit 7 (Windows x64)": http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-windows-x64.exe (for my 64-bit Windows 7 system)
  5. You are now downloading (hopefully the latest) JDK for your system! :)

Keep in mind the above links are for reference purposes only, to show you the step by step method of what it takes to download the JDK.

And install with default settings to:

  • “C:\Program Files\Java\jdk1.7.0\” (JDK)
  • “C:\Program Files\Java\jre7\” (JRE) <--- why did it ask a new install folder? it's JRE!

Remember from above that JDK contains JRE, which makes sense if you know what they both are. Again, see above.

After your install, double check “C:\Program Files\Java” to see both these folders. Now you know what they are and why they are there.

I know I wrote this for newbies, but I enjoy knowing things in full detail, so I hope this helps.

What is the difference between Serializable and Externalizable in Java?

When considering options for improving performance, don't forget custom serialization. You can let Java do what it does well, or at least good enough, for free, and provide custom support for what it does badly. This is usually a lot less code than full Externalizable support.

C# Reflection: How to get class reference from string?

We can use

Type.GetType()

to get class name and can also create object of it using Activator.CreateInstance(type);

using System;
using System.Reflection;

namespace MyApplication
{
    class Application
    {
        static void Main()
        {
            Type type = Type.GetType("MyApplication.Action");
            if (type == null)
            {
                throw new Exception("Type not found.");
            }
            var instance = Activator.CreateInstance(type);
            //or
            var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
        }
    }

    public class Action
    {
        public string key { get; set; }
        public string Value { get; set; }
    }
}

How do I auto size columns through the Excel interop objects?

This might be too late but if you add

 worksheet.Columns.AutoFit();

or

 worksheet.Rows.AutoFit();

it also works.

How to execute .sql file using powershell?

with 2008 Server 2008 and 2008 R2

Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100

with 2012 and 2014

Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location

Get all mysql selected rows into an array

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

Passing multiple values to a single PowerShell script parameter

I call a scheduled script who must connect to a list of Server this way:

Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"

Then inside the script:

param($list_of_servers)
...
Connect-Viserver $list_of_servers.split(",")

The split operator returns an array of string

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Why do we check up to the square root of a prime number to determine if it is prime?

Let's say we have a number "a", which is not prime [not prime/composite number means - a number which can be divided evenly by numbers other than 1 or itself. For example, 6 can be divided evenly by 2, or by 3, as well as by 1 or 6].

6 = 1 × 6 or 6 = 2 × 3

So now if "a" is not prime then it can be divided by two other numbers and let's say those numbers are "b" and "c". Which means

a=b*c.

Now if "b" or "c" , any of them is greater than square root of "a "than multiplication of "b" & "c" will be greater than "a".

So, "b" or "c" is always <= square root of "a" to prove the equation "a=b*c".

Because of the above reason, when we test if a number is prime or not, we only check until square root of that number.

error: Your local changes to the following files would be overwritten by checkout

I encountered the same problem and solved it by

git checkout -f branch

and its specification is rather clear.

-f, --force

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Reset IntelliJ UI to Default

Recent Versions

Window -> Restore Default Layout

(Thanks to Seven4X's answer)

Older Versions

You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.

It depends on the OS:

https://intellij-support.jetbrains.com/entries/23358108

How to render html with AngularJS templates

So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:

<html>
  <body ng-app="yourApp">
    <div class="span12">
      <div ng-view=""></div>
    </div>
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Then yourView.html could just be:

<div>
  <h1>{{ stuff.h1 }}</h1>
  <p>{{ stuff.content }}</p>
</div>

scripts.js could have your controller with data $scope'd to it.

angular.module('yourApp')
    .controller('YourCtrl', function ($scope) {
      $scope.stuff = {
        'h1':'Title',
        'content':"A paragraph..."
      };
    });

Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)

angular.module('yourApp', [])
.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/yourView.html',
      controller: 'YourCtrl'
    });
});

I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

HTML5 validation when the input type is not "submit"

Either you can change the button type to submit

<button type="submit"  onclick="submitform()" id="save">Save</button>

Or you can hide the submit button, keep another button with type="button" and have click event for that button

<form>
    <button style="display: none;" type="submit" >Hidden button</button>
    <button type="button" onclick="submitForm()">Submit</button>
</form>

Get an image extension from an uploaded file in Laravel

You can use the pathinfo() function built into PHP for that:

$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];

Or more concisely, you can pass an option get get it directly;

$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

Using switch statement with a range of value in each case?

I don't think you can do that in Java. Best bet is to just put the code in the last case of the range.

switch (num) {
  case 1: case 2: case 3: case 4: case 5: 
     System.Out.Println("testing case 1 to 5");
     break;
  case 6: case 7: case 8: case 9: case 10:
     System.Out.Println("testing case 6 to 10");
     break;
  default:
     //
}

Multiple Java versions running concurrently under Windows

Or use links. While it is rather unpleasant to update the PATH in a running environment, it's easy to recreate a link to a new version of JRE/JDK. So:

  • install different versions of JDK you want to use
  • create a link to that folder either by junction or by built-in mklink command
  • set the PATH to the link
  • If other version of java is to be used, delete the link, create a new one, PATH/JAVA_HOME/hardcoded scripts remain untouched

Difference between static class and singleton pattern?

As I understand the difference between a Static class and non-Static Singleton class, the static is simply a non-instantiated "type" in C#, where the Singleton is a true "object". In other words, all the static members in a static class are assigned to the type but in the Singleton are housed under the object. But keep in mind, a static class still behaves like a reference type as its not a value type like a Struct.

That means when you create a Singleton, because the class itself isnt static but its member is, the advantage is the static member inside the Singleton that refers to itself is connected to an actual "object" rather than a hollow "type" of itself. That sort of clarifies now the difference between a Static and a Non-Static Singleton beyond its other features and memory usage, which is confusing for me.

Both use static members which are single copies of a member, but the Singleton wraps the referenced member around a true instantiated "object" who's address exists in addition to its static member. That object itself has properties wherein in can be passed around and referenced, adding value. The Static class is just a type so it doesn't exist except to point to its static members. That concept sort of cemented the purpose of the Singleton vs Static Class beyond the inheritance and other issues.

Converting string from snake_case to CamelCase in Ruby

The ruby core itself has no support to convert a string from snake case to (upper) camel case (also known as pascal case).

So you need either to make your own implementation or use an existing gem.

There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

require 'lucky_case'

# to get upper camel case (pascal case) as string
LuckyCase.pascal_case('app_user') # => 'AppUser'
# to get the pascal case constant
LuckyCase.constantize('app_user') # => AppUser
# or the opposite way
LuckyCase.snake_case('AppUser')   # => app_user

You can even monkey patch the String class if you want to:

require 'lucky_case/string'

'app_user'.pascal_case # => 'AppUser'
'app_user'.constantize # => AppUser
# ...

Have a look at the offical repository for more examples and documentation:

https://github.com/magynhard/lucky_case

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

i got [ReflectionException] Class Seeder does not exist too and when i use composer dump-autoload, i got an error preg_match(): JIT compilation failed: no more memory when i run it.

What i did is that i change ;pcre.jit=1 to pcre.jit=Off in php.ini! You can find the path by using php --ini in your terminal!

I am using mac with php 7.3! Hope that help any of you guys out there!

Angular 5 Service to read local .json file

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

See this article for more details.

How can I make the browser wait to display the page until it's fully loaded?

You could start by having your site's main index page contain only a message saying "Loading". From here you could use ajax to fetch the contents of your next page and embed it into the current one, on completion removing the "Loading" message.

You might be able to get away with just including a loading message container at the top of your page which is 100% width/height and then removing the said div on load complete.

The latter may not work perfectly in both situations and will depends on how the browser renders content.

I'm not entirely sure if its a good idea. For simple static sites I would say not. However, I have seen a lot of heavy javascript sites lately from design companies that use complex animation and are one page. These sites use a loading message to wait for all scripts/html/css to be loaded so that the page functions as expected.

Is it valid to define functions in JSON results?

Nope, definitely not.

If you use a decent JSON serializer, it won't let you serialize a function like that. It's a valid OBJECT, but not valid JSON. Whatever that website's intent, it's not sending valid JSON.

Can't import Numpy in Python

The following command worked for me:

python.exe -m pip install numpy

Any way to declare an array in-line?

Draemon is correct. You can also declare m as taking varargs:

void m(String... strs) {
    // strs is seen as a normal String[] inside the method
}

m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here

Send file via cURL from form POST in PHP

For my the @ symbol did not work, so I do some research and found this way and it work for me, I hope this help you.

    $target_url = "http://server:port/xxxxx.php";           
    $fname = 'file.txt';   
    $cfile = new CURLFile(realpath($fname));

        $post = array (
                  'file' => $cfile
                  );    

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch);

    if ($result === FALSE) {
        echo "Error sending" . $fname .  " " . curl_error($ch);
        curl_close ($ch);
    }else{
        curl_close ($ch);
        echo  "Result: " . $result;
    }   

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

How to dynamically change the color of the selected menu item of a web page?

Try this. It holds the color until another item is clicked.

<style type="text/css">

.activeElem{
 background-color:lightblue
}       
.desactiveElem{
 background-color:none
}       

}

</style>

<script type="text/javascript">
var activeElemId;
function activateItem(elemId) {
 document.getElementById(elemId).className="activeElem";
 if(null!=activeElemId) {
   document.getElementById(activeElemId).className="desactiveElem";
 }
 activeElemId=elemId;

}
</script>

<li id="aaa"><a href="#" onclick="javascript:activateItem('aaa');">AAA</a>
<li id="bbb"><a href="#" onClick="javascript:activateItem('bbb');">BBB</a>
<li id="ccc"><a href="#" onClick="javascript:activateItem('ccc');">CCC</a>

error : expected unqualified-id before return in c++

Suggestions:

  • use consistent 3-4 space indenting and you will find these problems much easier
  • use a brace style that lines up {} vertically and you will see these problems quickly
  • always indent control blocks another level
  • use a syntax highlighting editor, it helps, you'll thank me later

for example,

type
functionname( arguments )
{
    if (something)
    {
        do stuff
    }
    else
    {
        do other stuff
    }
    switch (value)
    {
        case 'a':
            astuff
            break;
        case 'b':
            bstuff
            //fallthrough //always comment fallthrough as intentional
        case 'c':
            break;
        default: //always consider default, and handle it explicitly
            break;
    }
    while ( the lights are on )
    {
        if ( something happened )
        {
            run around in circles
            if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
            {
                scream and shout
            }
        }
    }
    return typevalue; //always return something, you'll thank me later
}

Explicitly select items from a list or tuple

like often when you have a boolean numpy array like mask

[mylist[i] for i in np.arange(len(mask), dtype=int)[mask]]

A lambda that works for any sequence or np.array:

subseq = lambda myseq, mask : [myseq[i] for i in np.arange(len(mask), dtype=int)[mask]]

newseq = subseq(myseq, mask)

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Are you passing the DISPLAY parameter to your Jenkins job?

I assume you are trying to execute the tests in headless mode, too. So setup some x service (i.e. Xvfb) and pass the DISPLAY number to your job. Worked for me.

Closing Excel Application Process in C# after Data Access

Killing Excel is not always easy; see this article: 50 Ways to Kill Excel

This article takes the best advice from Microsoft (MS Knowlege Base Article) on how to get Excel to quit nicely, but then also makes sure about it by killing the process if necessary. I like having a second parachute.

Make sure to Close any open workbooks, Quit the application and Release the xlApp object. Finally check to see if the process is still alive and if so then kill it.

This article also makes sure that we don't kill all Excel processes but only kills the exact process that was started.

See also Get Process from Window Handle

Here is the code I use: (works every time)

Sub UsingExcel()

    'declare process; will be used later to attach the Excel process
    Dim XLProc As Process

    'call the sub that will do some work with Excel
    'calling Excel in a separate routine will ensure that it is 
    'out of scope when calling GC.Collect
    'this works better especially in debug mode
    DoOfficeWork(XLProc)

    'Do garbage collection to release the COM pointers
    'http://support.microsoft.com/kb/317109
    GC.Collect()
    GC.WaitForPendingFinalizers()

    'I prefer to have two parachutes when dealing with the Excel process
    'this is the last answer if garbage collection were to fail
    If Not XLProc Is Nothing AndAlso Not XLProc.HasExited Then
        XLProc.Kill()
    End If

End Sub

'http://msdn.microsoft.com/en-us/library/ms633522%28v=vs.85%29.aspx
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, _
    ByRef lpdwProcessId As Integer) As Integer
End Function

Private Sub ExcelWork(ByRef XLProc As Process)

    'start the application using late binding
    Dim xlApp As Object = CreateObject("Excel.Application")

    'or use early binding
    'Dim xlApp As Microsoft.Office.Interop.Excel

    'get the window handle
    Dim xlHWND As Integer = xlApp.hwnd

    'this will have the process ID after call to GetWindowThreadProcessId
    Dim ProcIdXL As Integer = 0

    'get the process ID
    GetWindowThreadProcessId(xlHWND, ProcIdXL)

    'get the process
    XLProc = Process.GetProcessById(ProcIdXL)


    'do some work with Excel here using xlApp

    'be sure to save and close all workbooks when done

    'release all objects used (except xlApp) using NAR(x)


    'Quit Excel 
    xlApp.quit()

    'Release
    NAR(xlApp)

End Sub

Private Sub NAR(ByVal o As Object)
    'http://support.microsoft.com/kb/317109
    Try
        While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
        End While
    Catch
    Finally
        o = Nothing
    End Try
End Sub

Easy way to password-protect php page

Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.

Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.

They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.

If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Possible reasons for timeout when trying to access EC2 instance

My issue - I had port 22 open for "My IP" and changed the internet connection and IP address change caused. So had to change it back.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

What is the difference between DBMS and RDBMS?

DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.

Features:

  • Normal book keeping system, Flat files, MS Excel, FoxPRO, XML, etc.
  • Less or No provision for: Constraints, Security, ACID rules, users, etc.

RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.

  • SQL Server, Sybase, Oracle, MySQL, IBM DB2, MS Access, etc.

Features:

  • Database, with Tables having relations maintained by FK
  • DDL, DML
  • Data Integrity & ACID rules
  • Multiple User Access
  • Backup & Restore
  • Database Administration

Can I set background image and opacity in the same property?

Simple solution

if you need to set the gradient to background-image only:

background-image: url(IMAGE_URL); /* fallback for older browsers */

background-image: linear-gradient(to bottom, rgba(0,0,0,0.6) 0%,rgba(0,0,0,0.6) 100%), url(IMAGE_URL);

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

Completely removing phpMyAdmin

Try purge

sudo aptitude purge phpmyadmin

Not sure this works with plain old apt-get though

Openssl is not recognized as an internal or external command

Steps to create Hash Key. 
1: Download openssl from Openssl for Windows . I downloaded the Win64 version 
2:Unzip and copy all the files in the bin folder including openssl.exe(All file of bin folder) 
3:Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.8.0_05\bin 
4:Paste all the files you copied from Openssl’s bin folder to the Jdk folder. 

then go C:\Program Files\Java\jdk1.8.0_05\bin and press shift key and right click and open cmd

C:\Program Files\Java\jdk1.8.0_05\bin>//cmd path 

that is for Sha1 past this
keytool -exportcert -alias androiddebugkey -keystore "C:\User\ABC\.android.keystore" | openssl sha1 -binary | openssl base64
//and ABC is system name put own system name

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

Android - Center TextView Horizontally in LinearLayout

What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal" and the android:layout_gravity attribute can be removed.

How to reload current page?

Because it's the same component. You can either listen to route change by injecting the ActivatedRoute and reacting to changes of params and query params, or you can change the default RouteReuseStrategy, so that a component will be destroyed and re-rendered when the URL changes instead of re-used.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

bash script read all the files in directory

A simple loop should be working:

for file in /var/*
do
    #whatever you need with "$file"
done

See bash filename expansion

Check if a given time lies between two times regardless of date

/**
 * @param initialTime - in format HH:mm:ss
 * @param finalTime   - in format HH:mm:ss
 * @param timeToCheck - in format HH:mm:ss
 * @return initialTime <= timeToCheck < finalTime
 * @throws IllegalArgumentException if passed date with wrong format
 */
public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, String timeToCheck) throws IllegalArgumentException {
    String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
    if (initialTime.matches(reg) && finalTime.matches(reg) && timeToCheck.matches(reg)) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        Date inTime = parseDate(dateFormat, initialTime);
        Date finTime = parseDate(dateFormat, finalTime);
        Date checkedTime = parseDate(dateFormat, timeToCheck);

        if (finalTime.compareTo(initialTime) < 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(finTime);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            finTime = calendar.getTime();
            if (timeToCheck.compareTo(initialTime) < 0) {
                calendar.setTime(checkedTime);
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                checkedTime = calendar.getTime();
            }
        }

        return (checkedTime.after(inTime) || checkedTime.compareTo(inTime) == 0) && checkedTime.before(finTime);
    } else {
        throw new IllegalArgumentException("Not a valid time, expecting HH:MM:SS format");
    }
}

/**
 * @param initialTime - in format HH:mm:ss
 * @param finalTime   - in format HH:mm:ss
 * @return initialTime <= now < finalTime
 * @throws IllegalArgumentException if passed date with wrong format
 */
public static boolean isNowBetweenTwoTime(String initialTime, String finalTime) throws IllegalArgumentException {
    return isTimeBetweenTwoTime(initialTime, finalTime,
            String.valueOf(DateFormat.format("HH:mm:ss", new Date()))
    );
}

private static Date parseDate(SimpleDateFormat dateFormat, String data) {
    try {
        return dateFormat.parse(data);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Not a valid time");
    }
}

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

Access to file download dialog in Firefox

I have a solution for this issue, check the code:

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

driver.navigate().to("http://www.myfile.com/hey.csv");

from jquery $.ajax to angular $http

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

There are number of things to notice:

  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

How can I set size of a button?

Try with setPreferredSize instead of setSize.

UPDATE: GridLayout take up all space in its container, and BoxLayout seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.

Since GridLayout make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.

import javax.swing.*;
import java.awt.*;

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel(new GridLayout(4, 4));
        firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                firstPanel.add(new JButton());
            }
        }

        JPanel firstGluePanel = new JPanel(new BorderLayout());
        firstGluePanel.add(firstPanel, BorderLayout.WEST);
        firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        JPanel secondPanel = new JPanel(new GridLayout(13, 5));
        secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                secondPanel.add(new JButton());
            }
        }

        JPanel secondGluePanel = new JPanel(new BorderLayout());
        secondGluePanel.add(secondPanel, BorderLayout.WEST);
        secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        mainPanel.add(firstGluePanel);
        mainPanel.add(secondGluePanel);
        frame.getContentPane().add(mainPanel);

        //frame.setSize(400,600);
        frame.pack();
        frame.setVisible(true);
    }
}

How to customize <input type="file">?

Here is one way which I like because it makes the input fill out the whole container. The trick is the "font-size: 100px", and it need to go with the "overflow: hidden" and the relative position.

<div id="upload-file-container" >
   <input type="file" />
</div>

#upload-file-container {
   width: 200px;
   height: 50px;
   position: relative;
   border: dashed 1px black;
   overflow: hidden;
}

#upload-file-container input[type="file"]
{
   margin: 0;
   opacity: 0;   
   font-size: 100px;
}

How to find Port number of IP address?

Port numbers are defined by convention. HTTP servers generally listen on port 80, ssh servers listen on 22. But there are no requirements that they do.

How do you set the max number of characters for an EditText in Android?

You can use a InputFilter, that's the way:

EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);

How to gracefully handle the SIGKILL signal in Java

I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).

This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.

But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).

As other users commented, the usage of shutdown hooks seems mandatory.

So, how do I would handle it?

Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).

As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.

So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Interrupting threads");
        Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
        for (Thread th : runningThreads) {
            if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.getClass().getName().startsWith("org.brutusin")) {
                System.out.println("Interrupting '" + th.getClass() + "' termination");
                th.interrupt();
            }
        }
        for (Thread th : runningThreads) {
            try {
                if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.isInterrupted()) {
                    System.out.println("Waiting '" + th.getName() + "' termination");
                    th.join();
                }
            } catch (InterruptedException ex) {
                System.out.println("Shutdown interrupted");
            }
        }
        System.out.println("Shutdown finished");
    }
});

Complete test application at github: https://github.com/idelvall/kill-test

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Choosing the best concurrency list in Java

had better be List

The only List implementation in java.util.concurrent is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.

That said, are you sure you need it to be a List? There are a lot more options for concurrent Queues and Maps (and you can make Sets from Maps), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.

For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

Total Number of Row Resultset getRow Method

As others have answered there is no way to get the count of rows without iterating till the end. You could do that, but you may not want to, note the following points:

  1. For a many RDBMS systems ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. See this question on SO. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.

  2. A default ResultSet object is not updatable and has a cursor that moves forward only. I think this means that unless you execute the query with ResultSet.TYPE_SCROLL_INSENSITIVE rSet.beforeFirst() will throw SQLException. The reason it is this way is because there is cost with scrollable cursor. According to the documentation, it may throw SQLFeatureNotSupportedException even if you create a scrollable cursor.

  3. Populating and returning a List<Operations> means that you will also need extra memory. For very large resultsets this will not work at all.

So the big question is which RDBMS?. All in all I would suggest not logging the number of records.

Python Prime number checker

def is_prime(n):
    return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet smtp.mydomain.com 25

And copy and paste the below

helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box
.
quit

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

Git push error pre-receive hook declined

Despite the question is specific to gitlab, but similar errors can happen on github, depending how it is set up (usually Github Enterprise).

You need to familiarize yourself with the following concepts:

  • pre-receive hooks
  • organization webhooks
  • Webhooks

Webhooks are more commonly understood than other two items.

The Pre-receive hooks

are scripts that run on the GitHub Enterprise server to enforce policy. When a push occurs, each script runs in an isolated environment to determine whether the push is accepted or rejected.

Organization webhooks:

Webhook events are also sent from your repository to your "organization webhooks". more info.

These are set up in your github enterprise. They are specific to the version of the github enterprise. You may have no visibility because of your access limitations (developer, maintainer, admin, etc).

Convert absolute path into relative path given a current directory using Bash

I took your question as a challenge to write this in "portable" shell code, i.e.

  • with a POSIX shell in mind
  • no bashisms such as arrays
  • avoid calling externals like the plague. There's not a single fork in the script! That makes it blazingly fast, especially on systems with significant fork overhead, like cygwin.
  • Must deal with glob characters in pathnames (*, ?, [, ])

It runs on any POSIX conformant shell (zsh, bash, ksh, ash, busybox, ...). It even contains a testsuite to verify its operation. Canonicalization of pathnames is left as an exercise. :-)

#!/bin/sh

# Find common parent directory path for a pair of paths.
# Call with two pathnames as args, e.g.
# commondirpart foo/bar foo/baz/bat -> result="foo/"
# The result is either empty or ends with "/".
commondirpart () {
   result=""
   while test ${#1} -gt 0 -a ${#2} -gt 0; do
      if test "${1%${1#?}}" != "${2%${2#?}}"; then   # First characters the same?
         break                                       # No, we're done comparing.
      fi
      result="$result${1%${1#?}}"                    # Yes, append to result.
      set -- "${1#?}" "${2#?}"                       # Chop first char off both strings.
   done
   case "$result" in
   (""|*/) ;;
   (*)     result="${result%/*}/";;
   esac
}

# Turn foo/bar/baz into ../../..
#
dir2dotdot () {
   OLDIFS="$IFS" IFS="/" result=""
   for dir in $1; do
      result="$result../"
   done
   result="${result%/}"
   IFS="$OLDIFS"
}

# Call with FROM TO args.
relativepath () {
   case "$1" in
   (*//*|*/./*|*/../*|*?/|*/.|*/..)
      printf '%s\n' "'$1' not canonical"; exit 1;;
   (/*)
      from="${1#?}";;
   (*)
      printf '%s\n' "'$1' not absolute"; exit 1;;
   esac
   case "$2" in
   (*//*|*/./*|*/../*|*?/|*/.|*/..)
      printf '%s\n' "'$2' not canonical"; exit 1;;
   (/*)
      to="${2#?}";;
   (*)
      printf '%s\n' "'$2' not absolute"; exit 1;;
   esac

   case "$to" in
   ("$from")   # Identical directories.
      result=".";;
   ("$from"/*) # From /x to /x/foo/bar -> foo/bar
      result="${to##$from/}";;
   ("")        # From /foo/bar to / -> ../..
      dir2dotdot "$from";;
   (*)
      case "$from" in
      ("$to"/*)       # From /x/foo/bar to /x -> ../..
         dir2dotdot "${from##$to/}";;
      (*)             # Everything else.
         commondirpart "$from" "$to"
         common="$result"
         dir2dotdot "${from#$common}"
         result="$result/${to#$common}"
      esac
      ;;
   esac
}

set -f # noglob

set -x
cat <<EOF |
/ / .
/- /- .
/? /? .
/?? /?? .
/??? /??? .
/?* /?* .
/* /* .
/* /** ../**
/* /*** ../***
/*.* /*.** ../*.**
/*.??? /*.?? ../*.??
/[] /[] .
/[a-z]* /[0-9]* ../[0-9]*
/foo /foo .
/foo / ..
/foo/bar / ../..
/foo/bar /foo ..
/foo/bar /foo/baz ../baz
/foo/bar /bar/foo  ../../bar/foo
/foo/bar/baz /gnarf/blurfl/blubb ../../../gnarf/blurfl/blubb
/foo/bar/baz /gnarf ../../../gnarf
/foo/bar/baz /foo/baz ../../baz
/foo. /bar. ../bar.
EOF
while read FROM TO VIA; do
   relativepath "$FROM" "$TO"
   printf '%s\n' "FROM: $FROM" "TO:   $TO" "VIA:  $result"
   if test "$result" != "$VIA"; then
      printf '%s\n' "OOOPS! Expected '$VIA' but got '$result'"
   fi
done

# vi: set tabstop=3 shiftwidth=3 expandtab fileformat=unix :

java.io.IOException: Broken pipe

You may have not set the output file.

What does an exclamation mark mean in the Swift language?

John is an optional Person, meaning it can hold a value or be nil.

john.apartment = number73

is used if john is not an optional. Since john is never nil we can be sure it won't call apartment on a nil value. While

john!.apartment = number73

promises the compiler that john is not nil then unwraps the optional to get john's value and accesses john's apartment property. Use this if you know that john is not nil. If you call this on a nil optional, you'll get a runtime error.

The documentation includes a nice example for using this where convertedNumber is an optional.

if convertedNumber {
    println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
    println("\(possibleNumber) could not be converted to an integer")
}

Alter table add multiple columns ms sql

You need to remove the brackets

ALTER TABLE Countries
ADD  
HasPhotoInReadyStorage  bit,
 HasPhotoInWorkStorage  bit,
 HasPhotoInMaterialStorage bit,
 HasText  bit;

Get specific ArrayList item

As many have already told you:

mainList.get(3);

Be sure to check the ArrayList Javadoc.

Also, be careful with the arrays indices: in Java, the first element is at index 0. So if you are trying to get the third element, your solution would be mainList.get(2);

Error while installing json gem 'mkmf.rb can't find header files for ruby'

I also encountered this problem because I install Ruby on Ubuntu via brightbox, and I thought ruby-dev is the trunk of ruby. So I did not install. Install ruby2.3-dev fixes it:

sudo apt-get install ruby2.3-dev

PHP: Call to undefined function: simplexml_load_string()

For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:

extension=php_xmlrpc.dll

Then simply install php7.0-xml:

sudo apt-get install php7.0-xml

And restart PHP:

sudo service php7.0-fpm restart

And restart Apache:

sudo service apache2 restart

If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).

How do I get PHP errors to display?

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

How is Java platform-independent when it needs a JVM to run?

Doesn't independent means that Java code should be able to run on any machine and would need no special software to be installed (JVM in this case has to be present in the machine)?

With Java, you can compile source code on Windows and the compiled code (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is platform independent.

In other words, you have both portability of source code and portability of compiled code.

Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.

The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the compiled code is specific to each architecture, it is platform independent.

In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.

Why are my PowerShell scripts not running?

It could be PowerShell's default security level, which (IIRC) will only run signed scripts.

Try typing this:

set-executionpolicy remotesigned

That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run.

Then try executing your script again.