Programs & Examples On #Apache felix

Apache Felix is a community effort to implement the OSGi R4 Service Platform and other interesting OSGi-related technologies under the Apache license.

Reading my own Jar's Manifest

  public static Manifest getManifest( Class<?> cl ) {
    InputStream inputStream = null;
    try {
      URLClassLoader classLoader = (URLClassLoader)cl.getClassLoader();
      String classFilePath = cl.getName().replace('.','/')+".class";
      URL classUrl = classLoader.getResource(classFilePath);
      if ( classUrl==null ) return null;
      String classUri = classUrl.toString();
      if ( !classUri.startsWith("jar:") ) return null;
      int separatorIndex = classUri.lastIndexOf('!');
      if ( separatorIndex<=0 ) return null;
      String manifestUri = classUri.substring(0,separatorIndex+2)+"META-INF/MANIFEST.MF";
      URL url = new URL(manifestUri);
      inputStream = url.openStream();
      return new Manifest( inputStream );
    } catch ( Throwable e ) {
      // handle errors
      ...
      return null;
    } finally {
      if ( inputStream!=null ) {
        try {
          inputStream.close();
        } catch ( Throwable e ) {
          // ignore
        }
      }
    }
  }

How do I use Apache tomcat 7 built in Host Manager gui?

I'm not sure about Tomcat 7, but with Tomcat 6... once you start Tomcat: By going into the bin directory and starting startup.bat (win) or startup.sh (Unix/osx) it will spin up a local instance of the server running usually on port 8080 by default. Then by going to http://localhost:8080/ and seeing that it is running, there is a link to the manager. If that page is not there, you can try loading the manager by going directly to manager/html, and that will load the Host Manager gui.

http://localhost:8080/manager/html

Make sure Tomcat is running first and that 8080 is the right port. These are just the defaults that tomcat usually runs with.

To login you need to edit the conf/tomcat-users.xml, and create a Manager GUI role

<role rolename="manager-gui"/>

and add that to a user

<user username="admin" password="password" roles="manager-gui"/>

Then when you go to Manager GUI app at http://localhost:8080/manager/html it will prompt you for a username/password, which you added to that config file.

Executing an EXE file using a PowerShell script

& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode

or

[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")

UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:

Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"

Percentage calculation

With C# String formatting you can avoid the multiplication by 100 as it will make the code shorter and cleaner especially because of less brackets and also the rounding up code can be avoided.

(current / maximum).ToString("0.00%");

// Output - 16.67%

How to show/hide an element on checkbox checked/unchecked states using jQuery?

    <label  onclick="chkBulk();">
    <div class="icheckbox_flat-green" style="position: relative;">
      <asp:CheckBox ID="chkBulkAssign" runat="server" class="flat" 
       Style="position: 
         absolute; opacity: 0;" />
      </div>
      Bulk Assign
     </label>



    function chkBulk() {
    if ($('[id$=chkBulkAssign]')[0].checked) {
    $('div .icheckbox_flat-green').addClass('checked');
    $("[id$=btneNoteBulkExcelUpload]").show();           
    }
   else {
   $('div .icheckbox_flat-green').removeClass('checked');
   $("[id$=btneNoteBulkExcelUpload]").hide();
   } 

How to convert NSDate into unix timestamp iphone sdk?

If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:

+ (NSTimeInterval)getUTCFormateDate{

    NSDateComponents *comps = [[NSCalendar currentCalendar] 
                               components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
                               fromDate:[NSDate date]];
    [comps setHour:0];
    [comps setMinute:0];    
    [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];  
}

Alter table to modify default value of column

For Sql Azure the following query works :

ALTER TABLE [TableName] ADD  DEFAULT 'DefaultValue' FOR ColumnName
GO

How To Convert A Number To an ASCII Character?

You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character:

You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character:

char c = (char)65;
char c = Convert.ToChar(65); 

Also, ASCII.GetString decodes a range of bytes from a byte array into a string:

string s = Encoding.ASCII.GetString(new byte[]{ 65 });

Keep in mind that, ASCIIEncoding does not provide error detection. Any byte greater than hexadecimal 0x7F is decoded as the Unicode question mark ("?").

How to get values from IGrouping

From definition of IGrouping :

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

you can just iterate through elements like this:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

How to achieve pagination/table layout with Angular.js?

Here is my solution. @Maxim Shoustin's solution has some issue with sorting. I also wrap the whole thing to a directive. The only dependency is UI.Bootstrap.pagination, which did a great job on pagination.

Here is the plunker

Here is the github source code.

java SSL and cert keystore

Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":

javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType

The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.

Path of currently executing powershell script

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

How to check programmatically if an application is installed or not in Android?

Check App is installed or not in Android by using kotlin.

Creating kotlin extension.

fun PackageManager.isAppInstalled(packageName: String): Boolean = try {
        getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        true
    } catch (e: Exception) {
        false
    }

Now, can check if app is install or not

if (packageManager.isAppInstalled("AppPackageName")) {
    // App is installed
}else{
    // App is not installed
}

Online PHP syntax checker / validator

To expand on my comment.

You can validate on the command line using php -l [filename], which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.

Here's an example of the output when run on a file containing:

<?php
echo no quotes or semicolon

Results in:

PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Errors parsing badfile.php

I suggested you build your own validator.

A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l and echos the output.

Note: this is not a security risk it does not execute the file, just checks for syntax errors.

Here's a really basic example of creating your own:

<?php
if (isset($_FILES['file'])) {
    echo '<pre>';
    passthru('php -l '.$_FILES['file']['tmp_name']);
    echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:

SQL> grant dba to UserName; //Put This username which user show this error message.

Grant succeeded.

Check if a key exists inside a json object

This code causes esLint issue: no-prototype-builtins

foo.hasOwnProperty("bar") 

The suggest way here is:

Object.prototype.hasOwnProperty.call(foo, "bar");

ImportError: No module named xlsxwriter

I am not sure what caused this but it went all well once I changed the path name from Lib into lib and I was finally able to make it work.

jQuery and AJAX response header

cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:

  $.ajax({
   type: 'POST',
   url:'url.do',
   data: formData,
   success: function(data, textStatus, request){
        alert(request.getResponseHeader('some_header'));
   },
   error: function (request, textStatus, errorThrown) {
        alert(request.getResponseHeader('some_header'));
   }
  });

According to docs the XMLHttpRequest object is available as of jQuery 1.4.

How do I get next month date from today's date and insert it in my database?

I know - sort of late. But I was working at the same problem. If a client buys a month of service, he/she expects to end it a month later. Here's how I solved it:

    $now = time(); 
    $day = date('j',$now);
    $year = date('o',$now);
    $month = date('n',$now);
    $hour = date('G');
    $minute = date('i');
    $month += $count;
    if ($month > 12)        {
            $month -= 12;
            $year++; 
            }
    $work = strtotime($year . "-" . $month . "-01");
    $avail = date('t',$work);
    if ($day > $avail)
            $day = $avail;
    $stamp = strtotime($year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute);

This will calculate the exact day n*count months from now (where count <= 12). If the service started March 31, 2019 and runs for 11 months, it will end on Feb 29, 2020. If it runs for just one month, the end date is Apr 30, 2019.

Maven build debug in Eclipse

if you are using Maven 2.0.8+, then it will be very simple, run mvndebug from the console, and connect to it via Remote Debug Java Application with port 8000.

Does bootstrap have builtin padding and margin classes?

Bootstrap versions before 4 and 5 do not define ml, mr, pl, and pr.

Bootstrap versions 4 and 5 define the classes of ml, mr, pl, and pr.

For example:

mr--1
ml--1
pr--1
pl--1

How to access POST form fields

Use express-fileupload package:

var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')

app.use(fileUpload());

app.post('/', function(req, res) {
  var email = req.body.email;
  res.send('<h1>Email :</h1> '+email);
});

http.listen(3000, function(){
  console.log('Running Port:3000');
});

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

Query to list all stored procedures

I wrote this simple tsql to list the text of all stored procedures. Be sure to substitute your database name in field.

use << database name >>
go

declare @aQuery nvarchar(1024);
declare @spName nvarchar(64);
declare allSP cursor for
select p.name  from sys.procedures p where p.type_desc = 'SQL_STORED_PROCEDURE' order by p.name;
open allSP;
fetch next from allSP into @spName;
while (@@FETCH_STATUS = 0)
begin
    set @aQuery = 'sp_helptext [Extract.' + @spName + ']';
    exec sp_executesql @aQuery;
    fetch next from allSP;
end;
close allSP;
deallocate allSP;

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Right click your project and choose properties in the properties dialog check the Java Compiler settings, maybe you have different workspace settings.

How to create a fixed-size array of objects

The best you are going to be able to do for now is create an array with an initial count repeating nil:

var sprites = [SKSpriteNode?](count: 64, repeatedValue: nil)

You can then fill in whatever values you want.


In Swift 3.0 :

var sprites = [SKSpriteNode?](repeating: nil, count: 64)

how to convert numeric to nvarchar in sql command

declare @MyNumber float 
set @MyNumber = 123.45 
select 'My number is ' + CAST(@MyNumber as nvarchar(max))

Get selected option text with JavaScript

React / Latest JavaScript

onChange = { e => e.currentTarget.option[e.selectedIndex].text }

will give you exact value if values are inside a loop.

PHP - Check if two arrays are equal

If you want to check non associative arrays, here is the solution:

$a = ['blog', 'company'];
$b = ['company', 'blog'];

(count(array_unique(array_merge($a, $b))) === count($a)) ? 'Equals' : 'Not Equals';
// Equals

How to switch to the new browser window, which opens after click on the button?

 main you can do :

 String mainTab = page.goToNewTab ();
 //do what you want
 page.backToMainPage(mainTab);  

 What you need to have in order to use the main   

        private static Set<String> windows;

            //get all open windows 
            //return current window
            public String initWindows() {
                windows = new HashSet<String>();
                driver.getWindowHandles().stream().forEach(n ->   windows.add(n));
                return driver.getWindowHandle();
            }

            public String getNewWindow() {
                List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
                        .collect(Collectors.toList());
                logger.info(newWindow.get(0));
                return newWindow.get(0);
            }


            public String goToNewTab() {
                String startWindow = driver.initWindows();
                driver.findElement(By.cssSelector("XX")).click();
                String newWindow = driver.getNewWindow();
                driver.switchTo().window(newWindow);
                return startWindow;
            }

            public void backToMainPage(String startWindow) {
                driver.close();
                driver.switchTo().window(startWindow);
            }

Using Switch Statement to Handle Button Clicks

I use Butterknife with switch-case to handle this kind of cases:

    @OnClick({R.id.button_bireysel, R.id.button_kurumsal})
        public void onViewClicked(View view) {
            switch (view.getId()) {


                case R.id.button_bireysel:
 //Do something

                    break;
                case R.id.button_kurumsal:

     //Do something

                    break;

            }
        }

But the thing is there is no default case and switch statement falls through

Remap values in pandas column with a dict

Adding to this question if you ever have more than one columns to remap in a data dataframe:

def remap(data,dict_labels):
    """
    This function take in a dictionnary of labels : dict_labels 
    and replace the values (previously labelencode) into the string.

    ex: dict_labels = {{'col1':{1:'A',2:'B'}}

    """
    for field,values in dict_labels.items():
        print("I am remapping %s"%field)
        data.replace({field:values},inplace=True)
    print("DONE")

    return data

Hope it can be useful to someone.

Cheers

Android Studio how to run gradle sync manually?

I presume it is referring to Tools > Android > "Sync Project with Gradle Files" from the Android Studio main menu.

Flushing footer to bottom of the page, twitter bootstrap

Here's how to implement this from the official page:

http://getbootstrap.com/2.3.2/examples/sticky-footer.html

I just tested it right now and it WORKS GREAT! :)

HTML

<body>

    <!-- Part 1: Wrap all page content here -->
    <div id="wrap">

      <!-- Begin page content -->
      <div class="container">
        <div class="page-header">
          <h1>Sticky footer</h1>
        </div>
        <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
      </div>

      <div id="push"></div>
    </div>

    <div id="footer">
      <div class="container">
        <p class="muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
      </div>
    </div>
</body>

The relevant CSS code is this:

/* Sticky footer styles
-------------------------------------------------- */
html,
body {
    height: 100%;
    /* The html and body elements cannot have any padding or margin. */
}

/* Wrapper for page content to push down footer */
#wrap {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    /* Negative indent footer by it's height */
    margin: 0 auto -30px;
}

/* Set the fixed height of the footer here */
#push,
#footer {
    height: 30px;
}

#footer {
    background-color: #f5f5f5;
}

/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
    #footer {
        margin-left: -20px;
        margin-right: -20px;
        padding-left: 20px;
        padding-right: 20px;
    }
}

Python - Create list with numbers between 2 values?

Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result

For instance, standard command list(range(1,-3)) returns empty list [], while this function will return [-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.

boundingRectWithSize for NSAttributedString returning wrong size

textView.textContainerInset = UIEdgeInsetsZero;
NSString *string = @"Some string";
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.0f], NSForegroundColorAttributeName:[UIColor blackColor]};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:attributes];
[textView setAttributedText:attributedString];
CGRect textViewFrame = [textView.attributedText boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.frame)-8.0f, 9999.0f) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
NSLog(@"%f", ceilf(textViewFrame.size.height));

Works on all fonts perfectly!

Database development mistakes made by application developers

15 - Using some crazy construct and application logic instead of a simple COALESCE.

How do I force a favicon refresh?

This is a workaround for the chrome bug: change the rel attribute to stylesheet! Keep the original link though. Works like a charm:

I came up with this workaround because we also have a requirement to be able to update customer's sites / production code and I didn't find any of the other solutions to work.

Completely removing phpMyAdmin

I had same problem. Try the following command. This solved my problem.

sudo apt-get install libapache2-mod-php5

How to create a DB for MongoDB container on start up?

UPD Today I avoid Docker Swarm, secrets, and configs. I'd run it with docker-compose and the .env file. As long as I don't need autoscaling. If I do, I'd probably choose k8s. And database passwords, root account or not... Do they really matter when you're running a single database in a container not connected to the outside world?.. I'd like to know what you think about it, but Stack Overflow is probably not well suited for this sort of communication.

Mongo image can be affected by MONGO_INITDB_DATABASE variable, but it won't create the database. This variable determines current database when running /docker-entrypoint-initdb.d/* scripts. Since you can't use environment variables in scripts executed by Mongo, I went with a shell script:

docker-swarm.yml:

version: '3.1'

secrets:
  mongo-root-passwd:
    file: mongo-root-passwd
  mongo-user-passwd:
    file: mongo-user-passwd

services:
  mongo:
    image: mongo:3.2
    environment:
      MONGO_INITDB_ROOT_USERNAME: $MONGO_ROOT_USER
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/mongo-root-passwd
      MONGO_INITDB_USERNAME: $MONGO_USER
      MONGO_INITDB_PASSWORD_FILE: /run/secrets/mongo-user-passwd
      MONGO_INITDB_DATABASE: $MONGO_DB
    volumes:
      - ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
    secrets:
      - mongo-root-passwd
      - mongo-user-passwd

init-mongo.sh:

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
    var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
    var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
    var admin = db.getSiblingDB('admin');
    admin.auth(rootUser, rootPassword);

    var user = '$MONGO_INITDB_USERNAME';
    var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
    db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});
EOF

Alternatively, you can store init-mongo.sh in configs (docker config create) and mount it with:

configs:
    init-mongo.sh:
        external: true
...
services:
    mongo:
        ...
        configs:
            - source: init-mongo.sh
              target: /docker-entrypoint-initdb.d/init-mongo.sh

And secrets can be not stored in a file.

A couple of gists on the matter.

How does one extract each folder name from a path?

Or, if you need to do something with each folder, have a look at the System.IO.DirectoryInfo class. It also has a Parent property that allows you to navigate to the parent directory.

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

How can I get the current PowerShell executing file?

I would argue that there is a better method, by setting the scope of the variable $MyInvocation.MyCommand.Path:

ex> $script:MyInvocation.MyCommand.Name

This method works in all circumstances of invocation:

EX: Somescript.ps1

function printme () {
    "In function:"
    ( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
    ( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
    ( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
}
"Main:"
( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
" "
printme
exit

OUTPUT:

PS> powershell C:\temp\test.ps1
Main:
MyInvocation.ScriptName:
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: test.ps1

In function:
MyInvocation.ScriptName: C:\temp\test.ps1
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: printme

Notice how the above accepted answer does NOT return a value when called from Main. Also, note that the above accepted answer returns the full path when the question requested the script name only. The scoped variable works in all places.

Also, if you did want the full path, then you would just call:

$script:MyInvocation.MyCommand.Path

How to keep the spaces at the end and/or at the beginning of a String?

There is also the solution of using CDATA. Example:

<string name="test"><![CDATA[Hello          world]]></string>

But in general I think \u0020 is good enough.

How can I recover the return value of a function passed to multiprocessing.Process?

You can use the exit built-in to set the exit code of a process. It can be obtained from the exitcode attribute of the process:

import multiprocessing

def worker(procnum):
    print str(procnum) + ' represent!'
    exit(procnum)

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    result = []
    for proc in jobs:
        proc.join()
        result.append(proc.exitcode)
    print result

Output:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

OK, got it working. Turns out that an NTFS volume where the DB files were located got heavily fragmented. Stopped SQL Server, defragmented the whole thing and all it was fine ever since.

How to format numbers as currency string?

Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.

Method 0 (RegExp)

Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

Method 1

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

Method 2 (Split to Array)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Usage Example

console.log('======== Demo ========')
console.log(
    (1234567).format(0),
    (1234.56).format(2),
    (-1234.56).format(0)
);
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

// if not using async, browser will stop responding while running.
// this will create a new thread to benchmark
async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
next();

ResourceDictionary in a separate assembly

I'm working with .NET 4.5 and couldn't get this working... I was using WPF Custom Control Library. This worked for me in the end...

<ResourceDictionary Source="/MyAssembly;component/mytheme.xaml" />

source: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/11a42336-8d87-4656-91a3-275413d3cc19

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

How do I add options to a DropDownList using jQuery?

You may want to clear your DropDown first $('#DropDownQuality').empty();

I had my controller in MVC return a select list with only one item.

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    

Read each line of txt file to new array element

$yourArray = file("pathToFile.txt", FILE_IGNORE_NEW_LINES);

FILE_IGNORE_NEW_LINES avoid to add newline at the end of each array element
You can also use FILE_SKIP_EMPTY_LINES to Skip empty lines

reference here

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

In which case do you use the JPA @JoinTable annotation?

It lets you handle Many to Many relationship. Example:

Table 1: post

post has following columns
____________________
|  ID     |  DATE   |
|_________|_________|
|         |         |
|_________|_________|

Table 2: user

user has the following columns:

____________________
|     ID  |NAME     |
|_________|_________|
|         |         |
|_________|_________|

Join Table lets you create a mapping using:

@JoinTable(
  name="USER_POST",
  joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
  inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))

will create a table:

____________________
|  USER_ID| POST_ID |
|_________|_________|
|         |         |
|_________|_________|

Delete first character of a string in Javascript

_x000D_
_x000D_
String.prototype.trimStartWhile = function(predicate) {_x000D_
    if (typeof predicate !== "function") {_x000D_
     return this;_x000D_
    }_x000D_
    let len = this.length;_x000D_
    if (len === 0) {_x000D_
        return this;_x000D_
    }_x000D_
    let s = this, i = 0;_x000D_
    while (i < len && predicate(s[i])) {_x000D_
     i++;_x000D_
    }_x000D_
    return s.substr(i)_x000D_
}_x000D_
_x000D_
let str = "0000000000ABC",_x000D_
    r = str.trimStartWhile(c => c === '0');_x000D_
    _x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

how to create dynamic two dimensional array in java?

There are no multi-dimensional arrays in Java, there are, however, arrays of arrays.

Just make an array of however large you want, then for each element make another array however large you want that one to be.

int array[][];

array = new int[10][];

array[0] = new int[9];
array[1] = new int[8];
array[2] = new int[7];
array[3] = new int[6];
array[4] = new int[5];
array[5] = new int[4];
array[6] = new int[3];
array[7] = new int[2];
array[8] = new int[1];
array[9] = new int[0];

Alternatively:

List<Integer>[] array;

array = new List<Integer>[10];

// of you can do "new ArrayList<Integer>(the desired size);" for all of the following
array[0] = new ArrayList<Integer>();
array[1] = new ArrayList<Integer>();
array[2] = new ArrayList<Integer>();
array[3] = new ArrayList<Integer>();
array[4] = new ArrayList<Integer>();
array[5] = new ArrayList<Integer>();
array[6] = new ArrayList<Integer>();
array[7] = new ArrayList<Integer>();
array[8] = new ArrayList<Integer>();
array[9] = new ArrayList<Integer>();

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

How can I convert a string to an int in Python?

Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)

def convert(str):
    try:
        base = 10  # default
        if ':' in str:
            sstr = str.split(':')
            base, str = int(sstr[0]), sstr[1]
        val = int(str, base)
    except ValueError:
        val = None

    return val

val = convert(raw_input("Enter value:"))
# 10     : Decimal
# 16:a   : Hex, 10
# 2:1010 : Binary, 10

How to delete mysql database through shell command

If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf, and put in it:

[client]
user = "you"
password = "your-password"

For the sake of conversation:

echo 'DROP DATABASE foo;' | mysql

Original purpose of <input type="hidden">?

I'll provide a simple Server Side Real World Example here, say if the records are looped and each record has a form with a delete button and you need to delete a specific record, so here comes the hidden field in action, else you won't get the reference of the record to be deleted in this case, it will be id

For example

<?php
    if(isset($_POST['delete_action'])) {
        mysqli_query($connection, "DELETE FROM table_name 
                                   WHERE record_id = ".$_POST['row_to_be_deleted']);
                                   //Here is where hidden field value is used
    }

    while(condition) {
?>
    <span><?php echo 'Looped Record Name'; ?>
    <form method="post">
        <input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>" />
        <input type="submit" name="delete_action" />
    </form>
<?php
    }
?>

Disable Drag and Drop on HTML elements?

This JQuery Worked for me :-

$(document).ready(function() {
  $('#con_image').on('mousedown', function(e) {
      e.preventDefault();
  });
});

How to view the stored procedure code in SQL Server Management Studio

You can view all the objects code stored in the database with this query:

    USE [test] --Database Name
SELECT
    sch.name+'.'+ob.name AS       [Object], 
    ob.create_date, 
    ob.modify_date, 
    ob.type_desc, 
    mod.definition
FROM 
     sys.objects AS ob
     LEFT JOIN sys.schemas AS sch ON
            sch.schema_id = ob.schema_id
     LEFT JOIN sys.sql_modules AS mod ON
            mod.object_id = ob.object_id
WHERE mod.definition IS NOT NULL --Selects only objects with the definition (code)

What's an easy way to read random line from a file in Unix command line?

Here's a simple Python script that will do the job:

import random, sys
lines = open(sys.argv[1]).readlines()
print(lines[random.randrange(len(lines))])

Usage:

python randline.py file_to_get_random_line_from

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

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

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Rank function in MySQL

A tweak of Daniel's version to calculate percentile along with rank. Also two people with same marks will get the same rank.

set @totalStudents = 0;
select count(*) into @totalStudents from marksheets;
SELECT id, score, @curRank := IF(@prevVal=score, @curRank, @studentNumber) AS rank, 
@percentile := IF(@prevVal=score, @percentile, (@totalStudents - @studentNumber + 1)/(@totalStudents)*100),
@studentNumber := @studentNumber + 1 as studentNumber, 
@prevVal:=score
FROM marksheets, (
SELECT @curRank :=0, @prevVal:=null, @studentNumber:=1, @percentile:=100
) r
ORDER BY score DESC

Results of the query for a sample data -

+----+-------+------+---------------+---------------+-----------------+
| id | score | rank | percentile    | studentNumber | @prevVal:=score |
+----+-------+------+---------------+---------------+-----------------+
| 10 |    98 |    1 | 100.000000000 |             2 |              98 |
|  5 |    95 |    2 |  90.000000000 |             3 |              95 |
|  6 |    91 |    3 |  80.000000000 |             4 |              91 |
|  2 |    91 |    3 |  80.000000000 |             5 |              91 |
|  8 |    90 |    5 |  60.000000000 |             6 |              90 |
|  1 |    90 |    5 |  60.000000000 |             7 |              90 |
|  9 |    84 |    7 |  40.000000000 |             8 |              84 |
|  3 |    83 |    8 |  30.000000000 |             9 |              83 |
|  4 |    72 |    9 |  20.000000000 |            10 |              72 |
|  7 |    60 |   10 |  10.000000000 |            11 |              60 |
+----+-------+------+---------------+---------------+-----------------+

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Is it possible to select the last n items with nth-child?

If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

$('ul li:nth-last-child(1)').addClass('last');

And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

In Android Q (Android 10) you can't enable/disable wifi programmatically anymore. Use Settings Panel to toggle wifi connectivity:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
    startActivityForResult(panelIntent, 0)
} else {
    // use previous solution, add appropriate permissions to AndroidManifest file (see answers above)
    (this.context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>

Dynamic height for DIV

calculate the height of each link no do this

document.getElementById("products").style.height= height_of_each_link* no_of_link

How to read data From *.CSV file using javascript?

I am using d3.js for parsing csv file. Very easy to use. Here is the docs.

Steps:

  • npm install d3-request

Using Es6;

import { csv } from 'd3-request';
import url from 'path/to/data.csv';

csv(url, function(err, data) {
 console.log(data);
})

Please see docs for more.

Update - d3-request is deprecated. you can use d3-fetch

How can I download a file from a URL and save it in Rails?

Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end

Role/Purpose of ContextLoaderListener in Spring?

Listener class - Listens on an event (Eg.. Server startup/shutdown)

ContextLoaderListener -

  1. Listens during server start up/shutdown
  2. Takes the Spring configuration files as input and creates the beans as per configuration and make it ready (destroys the bean during shutdown)
  3. Configuration files can be provided like this in web.xml

    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>  
    

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

From milliseconds to hour, minutes, seconds and milliseconds

not really eleganter, but a bit shorter would be

function to_tuple(x):
   y = 60*60*1000
   h = x/y
   m = (x-(h*y))/(y/60)
   s = (x-(h*y)-(m*(y/60)))/1000
   mi = x-(h*y)-(m*(y/60))-(s*1000)

   return (h,m,s,mi)

Extract Data from PDF and Add to Worksheet

This doesn't seem to work with the Adobe Type library. As soon as it gets to Open, I get a 429 error. Acrobat works fine though...

Change an image with onclick()

function chkicon(num,allsize) {
    var  flagicon = document.getElementById("flagicon"+num).value;

    if(flagicon=="plus"){
         //alert("P== "+flagicon);

         for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }


         document.images["pic"+num].src = "../images/minus.gif";
         document.getElementById("flagicon"+num).value = "minus";

    }else if(flagicon=="minus"){
         //alert("M== "+flagicon);

          document.images["pic"+num].src  = "../images/plus.gif";    
          document.getElementById("flagicon"+num).value = "plus";

    }else{
          for (var i = 0; i < allsize; i++) {
            if(document.getElementById("flagicon"+i).value !=""){
               document.getElementById("flagicon"+i).value = "plus";
               document.images["pic"+i].src  = "../images/plus.gif";
            }
          }
    }
}

Read and Write CSV files including unicode with Python 2.7

Make sure you encode and decode as appropriate.

This example will roundtrip some example text in utf-8 to a csv file and back out to demonstrate:

# -*- coding: utf-8 -*-
import csv

tests={'German': [u'Straße',u'auslösen',u'zerstören'], 
       'French': [u'français',u'américaine',u'épais'], 
       'Chinese': [u'???',u'??',u'???']}

with open('/tmp/utf.csv','w') as fout:
    writer=csv.writer(fout)    
    writer.writerows([tests.keys()])
    for row in zip(*tests.values()):
        row=[s.encode('utf-8') for s in row]
        writer.writerows([row])

with open('/tmp/utf.csv','r') as fin:
    reader=csv.reader(fin)
    for row in reader:
        temp=list(row)
        fmt=u'{:<15}'*len(temp)
        print fmt.format(*[s.decode('utf-8') for s in temp])

Prints:

German         Chinese        French         
Straße         ???            français       
auslösen       ??             américaine     
zerstören      ???            épais  

When should I use Memcache instead of Memcached?

Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:

  1. Cas tokens. This made my life much easier and is an easy preventive system for stale data. Whenever you pull something from the cache, you can receive with it a cas token (a double number). You can than use that token to save your updated object. If no one else updated the value while your thread was running, the swap will succeed. Otherwise a newer cas token was created and you are forced to reload the data and save it again with the new token.
  2. Read through callbacks are the best thing since sliced bread. It has simplified much of my code.
  3. getDelayed() is a nice feature that can reduce the time your script has to wait for the results to come back from the server.
  4. While the memcached server is supposed to be very stable, it is not the fastest. You can use binary protocol instead of ASCII with the newer client.
  5. Whenever you save complex data into memcached the client used to always do serialization of the value (which is slow), but now with memcached client you have the option of using igbinary. So far I haven't had the chance to test how much of a performance gain this can be.

All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.

If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.

I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.

UPDATE

Zend Framework 2 has an adapter for Memcached which can be found here

Set a form's action attribute when submitting?

Attach to the submit button click event and change the action attribute in the event handler.

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

You can add this at the beginning after #include <iostream>:

using namespace std;

jquery toggle slide from left to right and back

See this: Demo

$('#cat_icon,.panel_title').click(function () {
   $('#categories,#cat_icon').stop().slideToggle('slow');
});

Update : To slide from left to right: Demo2

Note: Second one uses jquery-ui also

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

PHP json_decode() returns NULL with valid JSON?

It took me like an hour to figure it out, but trailing commas (which work in JavaScript) fail in PHP.
This is what fixed it for me:

str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);

What is a "thread" (really)?

Processes are like two people using two different computers, who use the network to share data when necessary. Threads are like two people using the same computer, who don't have to share data explicitly but must carefully take turns.

Conceptually, threads are just multiple worker bees buzzing around in the same address space. Each thread has its own stack, its own program counter, etc., but all threads in a process share the same memory. Imagine two programs running at the same time, but they both can access the same objects.

Contrast this with processes. Processes each have their own address space, meaning a pointer in one process cannot be used to refer to an object in another (unless you use shared memory).

I guess the key things to understand are:

  • Both processes and threads can "run at the same time".
  • Processes do not share memory (by default), but threads share all of their memory with other threads in the same process.
  • Each thread in a process has its own stack and its own instruction pointer.

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

Determining 32 vs 64 bit in C++

I'm adding this answer as a use case and complete example for the runtime-check described in another answer.

This is the approach I've been taking for conveying to the end-user whether the program was compiled as 64-bit or 32-bit (or other, for that matter):

version.h

#ifndef MY_VERSION
#define MY_VERSION

#include <string>

const std::string version = "0.09";
const std::string arch = (std::to_string(sizeof(void*) * 8) + "-bit");

#endif

test.cc

#include <iostream>
#include "version.h"

int main()
{
    std::cerr << "My App v" << version << " [" << arch << "]" << std::endl;
}

Compile and Test

g++ -g test.cc
./a.out
My App v0.09 [64-bit]

assign headers based on existing row in dataframe in R

Try this:

colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ]          # removing the first row.

However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.

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).

Django ChoiceField

Better Way to Provide Choice inside a django Model :

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

Bubble Sort Homework

This is what happens when you use variable name of negative meaning, you need to invert their values. The following would be easier to understand:

sorted = False
while not sorted:
    ...

On the other hand, the logic of the algorithm is a little bit off. You need to check whether two elements swapped during the for loop. Here's how I would write it:

def bubble(values):
    length = len(values) - 1
    sorted = False
    while not sorted:
        sorted = True
        for element in range(0,length):
            if values[element] > values[element + 1]:
                 hold = values[element + 1]
                 values[element + 1] = values[element]
                 values[element] = hold
                 sorted = False
    return values

Node.js/Express.js App Only Works on Port 3000

I am using the minimist package and the node startup arguments to control the port.

node server.js --port 4000

or

node server.js -p 4000

Inside server.js, the port can be determined by

var argv = parseArgs(process.argv.slice(2))

const port = argv.port || argv.p || 3000;
console.log(`Listening on port ${port}...`)

//....listen(port);

and it defaults to 3000 if no port is passed as an argument.

You can then use listen on the port variable.

jQuery .get error response function?

You can get detail error by using responseText property.

$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
     } 
    });

Getting title and meta tags from external website

Now a days, most of the sites add meta tags to their sites providing information about their site or any particular article page. Such as news or blog sites.

I have created a Meta API which gives you required meta data ac like OpenGraph, Schema.Org, etc.

Check it out - https://api.sakiv.com/docs

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

You just have to use your local IP address:using the cmd command "ipconfig" and your server port number like this:

String webServiceUrl = "http://192.168.X.X:your_local_server_port/your_web_service_name.php"

And make sure you did set the internet permission in your project manifest

It's working perfectly for me

Good Luck

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

How to Execute SQL Server Stored Procedure in SQL Developer?

The stored procedures can be run in sql developer tool using the below syntax

BEGIN procedurename(); END;

If there are any parameters then it has to be passed.

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

form confirm before submit

$('#myForm').submit(function() {
    var c = confirm("Click OK to continue?");
    return c; //you can just return c because it will be true or false
});

How do I calculate a trendline for a graph?

Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.

// https://classroom.synonym.com/calculate-trendline-2709.html
package main

import (
    "fmt"
    "math"
)

func main() {

    graph := [][]float64{
        {1, 3},
        {2, 5},
        {3, 6.5},
    }

    n := len(graph)

    // get the slope
    var a float64
    var b float64
    var bx float64
    var by float64
    var c float64
    var d float64
    var slope float64

    for _, point := range graph {

        a += point[0] * point[1]
        bx += point[0]
        by += point[1]
        c += math.Pow(point[0], 2)
        d += point[0]

    }

    a *= float64(n)           // 97.5
    b = bx * by               // 87
    c *= float64(n)           // 42
    d = math.Pow(d, 2)        // 36
    slope = (a - b) / (c - d) // 1.75

    // calculating the y-intercept (b) of the Trendline
    var e float64
    var f float64

    e = by                            // 14.5
    f = slope * bx                    // 10.5
    intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3

    // output
    fmt.Println(slope)
    fmt.Println(intercept)

}

What is the proper declaration of main in C++?

From Standard docs., 3.6.1.2 Main Function,

It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { / ... / } and int main(int argc, char* argv[]) { / ... / }

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....

Hope that helps..

mysql stored-procedure: out parameter

I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...

I don't know what since I called some procedures before successfully (but there where no out parameters)...

For this one I had entered

CALL my_sqrt(4,@out_value);
SELECT @out_value;

And it results with an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2

Strangely, if I write just:

CALL my_sqrt(4,@out_value); 

The result message is: "Query canceled"

I guess, for now I will use only terminal...

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

I have been faced this problem.

The cause is your table don't have a primary key field.

And I have a simple solution: Set a field to primary key to specific filed that suit with your business logic. For example, I have database thesis_db and field thesis_id, I will press button Primary (key icon) to set thesis_id to become primary key field

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Using group by on multiple columns

Group By X means put all those with the same value for X in the one group.

Group By X, Y means put all those with the same values for both X and Y in the one group.

To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:

Table: Subject_Selection

+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001  |        1 | John     |
| ITB001  |        1 | Bob      |
| ITB001  |        1 | Mickey   |
| ITB001  |        2 | Jenny    |
| ITB001  |        2 | James    |
| MKB114  |        1 | John     |
| MKB114  |        1 | Erica    |
+---------+----------+----------+

When you use a group by on the subject column only; say:

select Subject, Count(*)
from Subject_Selection
group by Subject

You will get something like:

+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001  |     5 |
| MKB114  |     2 |
+---------+-------+

...because there are 5 entries for ITB001, and 2 for MKB114

If we were to group by two columns:

select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester

we would get this:

+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001  |        1 |     3 |
| ITB001  |        2 |     2 |
| MKB114  |        1 |     2 |
+---------+----------+-------+

This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")

Hopefully that makes sense.

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

How to clear out session on log out

session.abandon() will not remove the sessionID cookie from the browser. Therefore any new requests after this will take the same session ID. Hence, use Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); after session.abandon().

How to play only the audio of a Youtube video using HTML 5?

Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.

However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.

Java 8 Distinct by property

Extending Stuart Marks's answer, this can be done in a shorter way and without a concurrent map (if you don't need parallel streams):

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    final Set<Object> seen = new HashSet<>();
    return t -> seen.add(keyExtractor.apply(t));
}

Then call:

persons.stream().filter(distinctByKey(p -> p.getName());

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

Assets file project.assets.json not found. Run a NuGet package restore

Closing and re-opening Visual Studio solved this issue for me, once I had made sure the NuGet packages had been restored as per other answers posted here.

Edit: Sometimes just trying to build again fixes the problem.

How to select last two characters of a string

var member = "my name is maanu";

var answer=member.substring(0,member.length - 2);

alert(answer);

How to determine the current shell I'm working on

ps -p $$

should work anywhere that the solutions involving ps -ef and grep do (on any Unix variant which supports POSIX options for ps) and will not suffer from the false positives introduced by grepping for a sequence of digits which may appear elsewhere.

adding 1 day to a DATETIME format value

  1. Use strtotime to convert the string to a time stamp
  2. Add a day to it (eg: by adding 86400 seconds (24 * 60 * 60))

eg:

$time = strtotime($myInput);
$newTime = $time + 86400;

If it's only adding 1 day, then using strtotime again is probably overkill.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

Select multiple records based on list of Id's with linq

Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!

  var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
  var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();

This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)

BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:

  var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
  var shoppingCart = _dataContext.ShoppingCart
                     .Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
                     .ToList();

This will return 5 results from DB. Using 'contains' would be wrong in this case.

Push item to associative array in PHP

You can try.

$options['inputs'] = $options['inputs'] + $new_input;

How to get a dependency tree for an artifact?

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

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

enter image description here

lodash: mapping array to object

Another way with lodash

creating pairs, and then either construct a object or ES6 Map easily

_(params).map(v=>[v.name, v.input]).fromPairs().value()

or

_.fromPairs(params.map(v=>[v.name, v.input]))

Here is a working example

_x000D_
_x000D_
var params = [_x000D_
    { name: 'foo', input: 'bar' },_x000D_
    { name: 'baz', input: 'zle' }_x000D_
];_x000D_
_x000D_
var obj = _(params).map(v=>[v.name, v.input]).fromPairs().value();_x000D_
_x000D_
console.log(obj);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

CSS hide scroll bar if not needed

.container {overflow:auto;} will do the trick. If you want to control specific direction, you should set auto for that specific axis. A.E.

.container {overflow-y:auto;} .container {overflow-x:hidden;}

The above code will hide any overflow in the x-axis and generate a scroll-bar when needed on the y-axis.But you have to make sure that you content default height smaller than the container height; if not, the scroll-bar will not be hidden.

Passing a variable from node.js to html

What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

  1. npm install --save pug - to add it to the project and package.json file
  2. app.set('view engine', 'pug'); - register it as a view engine in express
  3. create a ./views folder and add a simple .pug file like so:
html
  head
    title= title
  body
    h1= message

note that the spacing is very important!

  1. create a route that returns the processed html:
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
});

This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

For more info on pug you can also check: https://github.com/pugjs/pug

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

use setRawInputType and setKeyListener

editTextNumberPicker.setRawInputType(InputType.TYPE_CLASS_NUMBER | 
                   InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_NUMBER_FLAG_SIGNED );
editTextNumberPicker.setKeyListener(DigitsKeyListener.getInstance(false,true));//set decimals and positive numbers. 

Checking if a worksheet-based checkbox is checked

It seems that in VBA macro code for an ActiveX checkbox control you use

If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

and for a Form checkbox control you use

If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

How to return multiple values in one column (T-SQL)?

You can use a function with COALESCE.

CREATE FUNCTION [dbo].[GetAliasesById]
(
    @userID int
)
RETURNS varchar(max)
AS
BEGIN
    declare @output varchar(max)
    select @output = COALESCE(@output + ', ', '') + alias
    from UserAliases
    where userid = @userID

    return @output
END

GO

SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID

GO

GSON - Date format

This is a bug. Currently you either have to set a timeStyle as well or use one of the alternatives described in the other answers.

findViewByID returns null

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

This would be wrong

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

This is correct

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

Generic Property in C#

Okay, I'll bite. You want something like this: If you declare a "property" like this:

Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.

public class PropertyFoo {
  public MyProp<String> Name;
}

this ends up as

public class PropertyFoo {
  public string Name {
    get { /* do predefined stuff here */ }
    set { /*other predefined stuff here */ }
  }
}

No. Not possible and not a property, really. Look for template/snippet support in your IDE.

Incrementing in C++ - When to use x++ or ++x?

It's not a question of preference, but of logic.

x++ increments the value of variable x after processing the current statement.

++x increments the value of variable x before processing the current statement.

So just decide on the logic you write.

x += ++i will increment i and add i+1 to x. x += i++ will add i to x, then increment i.

In Angular, how do you determine the active route?

Small improvement to @alex-correia-santos answer based on https://github.com/angular/angular/pull/6407#issuecomment-190179875

import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
// ...
export class App {
  constructor(private router: Router) {
  }

  // ...

  isActive(instruction: any[]): boolean {
    return this.router.isRouteActive(this.router.generate(instruction));
  }
} 

And use it like this:

<ul class="nav navbar-nav">
    <li [class.active]="isActive(['Home'])">
        <a [routerLink]="['Home']">Home</a>
    </li>
    <li [class.active]="isActive(['About'])">
        <a [routerLink]="['About']">About</a>
    </li>
</ul>

Disable mouse scroll wheel zoom on embedded Google Maps

I was having the same problem: when scrolling the page then the pointer becomes over the map, it starts to zoom in/out the map instead of continuing scrolling the page. :(

So I solved this putting a div with an .overlay exactly before each gmap iframe insertion, see:

<html>
  <div class="overlay" onClick="style.pointerEvents='none'"></div>
  <iframe src="https://mapsengine.google.com/map/embed?mid=some_map_id" width="640" height="480"></iframe>
</html>

In my CSS i created the class:

.overlay {
   background:transparent; 
   position:relative; 
   width:640px;
   height:480px; /* your iframe height */
   top:480px;  /* your iframe height */
   margin-top:-480px;  /* your iframe height */
}

The div will cover the map, preventing pointer events from getting to it. But if you click on the div, it becomes transparent to pointer events, activating the map again!

I hope get helped you :)

Convert string to Color in C#

The following can generate a color from name, hex, or known name.

Color beige = StringToColor("Beige");
Color purple = StringToColor("#800080");
Color window = StringToColor("Window");

public static Color StringToColor(string colorStr)
{
    TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
    var result = (Color)cc.ConvertFromString(colorStr);
    return result;
}

The snippet was taken from Jo Albahari's C# in a Nutshell.

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

Angular 5 - Copy to clipboard

Copy using angular cdk,

Module.ts

import {ClipboardModule} from '@angular/cdk/clipboard';

Programmatically copy a string: MyComponent.ts,

class MyComponent {
  constructor(private clipboard: Clipboard) {}

  copyHeroName() {
    this.clipboard.copy('Alphonso');
  }
}

Click an element to copy via HTML:

<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>

Reference: https://material.angular.io/cdk/clipboard/overview

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

Manifest merger failed : uses-sdk:minSdkVersion 14

I have some projects where I prefer to target L.MR1(SDKv22) and some projects where I prefer KK(SDKv19). Your result may be different, but this worked for me.

// Targeting L.MR1 (Android 5.1), SDK 22
android {
    compileSdkVersion 22
    buildToolsVersion "22"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 22
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // google support libraries (22)
    compile 'com.android.support:support-v4:22.0.0'
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support:cardview-v7:21.0.3'
    compile 'com.android.support:recyclerview-v7:21.0.3'
}



// Targeting KK (Android 4.4.x), SDK 19
android {
    compileSdkVersion 19
    buildToolsVersion "19.1"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 19
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // google libraries (19)
    compile 'com.android.support:support-v4:19.1+'
    compile 'com.android.support:appcompat-v7:19.1+'
    compile 'com.android.support:cardview-v7:+'
    compile 'com.android.support:recyclerview-v7:+'
}

Get latest from Git branch

use git pull:

git pull origin yourbranch

How to add Python to Windows registry

I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):

reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"

I find this easier than using Registry Editor but that's solely a personal preference.

The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.

How to add a new row to an empty numpy array

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Which is an empty array but it has the proper dimensionality.

>>> arr
array([], shape=(0, 3), dtype=int64)

Then be sure to append along axis 0:

arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:

In [210]: %%timeit
   .....: l = []
   .....: for i in xrange(1000):
   .....:     l.append([3*i+1,3*i+2,3*i+3])
   .....: l = np.asarray(l)
   .....: 
1000 loops, best of 3: 1.18 ms per loop

In [211]: %%timeit
   .....: a = np.empty((0,3), int)
   .....: for i in xrange(1000):
   .....:     a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
   .....: 
100 loops, best of 3: 18.5 ms per loop

In [214]: np.allclose(a, l)
Out[214]: True

The numpythonic way to do it depends on your application, but it would be more like:

In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop

In [221]: np.allclose(a, n)
Out[221]: True

Where to put a textfile I want to use in eclipse?

One path to take is to

  1. Add the file you're working with to the classpath
  2. Use the resource loader to locate the file:

        URL url = Test.class.getClassLoader().getResource("myfile.txt");
        System.out.println(url.getPath());
        ...
    
  3. Open it

How to make an anchor tag refer to nothing?

The correct way to handle this is to "break" the link with jQuery when you handle the link

HTML

<a href="#" id="theLink">My Link</a>

JS

$('#theLink').click(function(ev){
    // do whatever you want here

    ev.preventDefault();
    ev.stopPropagation();
});

Those final two calls stop the browser interpreting the click.

Rolling back local and remote git repository by 1 commit

I solved problem like yours by this commands:

git reset --hard HEAD^
git push -f <remote> <local branch>:<remote branch> 

Is it possible to add dynamically named properties to JavaScript object?

ES6 for the win!

const b = 'b';
const c = 'c';

const data = {
    a: true,
    [b]: true, // dynamic property
    [`interpolated-${c}`]: true, // dynamic property + interpolation
    [`${b}-${c}`]: true
}

If you log data you get this:

{
  a: true,
  b: true,
  interpolated-c: true,
  b-c: true
}

This makes use of the new Computed Property syntax and Template Literals.

How to get a tab character?

As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p

Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...

 <div style="padding-left:4.00em;">Indenented text </div>

Or as a regular class in a style sheet

.tabbed {padding-left:4.00em;}

Then the HTML might look like

<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>

Bin size in Matplotlib (Histogram)

Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

If you just want them equally distributed, you can simply use range:

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

Added to original answer

The above line works for data filled with integers only. As macrocosme points out, for floats you can use:

import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))

Fixing npm path in Windows 8 and 10

Installed Node Version Manager (NVM) for Windows: https://github.com/coreybutler/nvm-windows

I'm using Windows 10 - 64 bit so I run... Commands:

  • nvm arch 64 (to make default the 64 bit executable)
  • nvm list (to list all available node versions)
  • nvm install 8.0.0 (to download node version 8.0.0 - you can pick any)
  • nvm use 8.0.0 (to use that specific version)

In my case I had to just switch to version 8.5.0 and then switch back again to 8.0.0 and it was fixed. Apparently NVM sets the PATH variables whenever you do that switch.

window.open with headers

Use POST instead

Although it is easy to construct a GET query using window.open(), it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:

<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>

<input type="button" onclick="loadNnextPage()" value="Click me!">

<script>
function loadNnextPage() {
  document.getElementById("helper").headerData.value = "New";
  document.getElementById("helper").submit();
}
</script>

Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.

Problems with GET

  • Query strings get stored in browser history,
  • can be shoulder-surfed
  • copy-pasted,
  • and often you don't want it to be easy to "refresh" the same transaction.

How can I create numbered map markers in Google Maps V3?

I don't have enough reputation to comment on answers but wanted to note that the Google Chart API has been deprecated.

From the API homepage:

The Infographics portion of Google Chart Tools has been officially deprecated as of April 20, 2012.

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

How do I add a placeholder on a CharField in Django?

It's undesirable to have to know how to instantiate a widget when you just want to override its placeholder.

    q = forms.CharField(label='search')
    ...
    q.widget.attrs['placeholder'] = "Search"

How to split a string into an array in Bash?

Use this:

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe

Check if value exists in column in VBA

try this:

If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If

jQuery remove all list items from an unordered list

   var ul = document.getElementById("yourElementId");

     while (ul.firstChild)
         ul.removeChild(ul.firstChild);

How can I convert a char to int in Java?

If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class char_to_int
{
  public static void main(String args[])
  {
       char myChar = 'a';
       int  i = (int) myChar; // cast from a char to an int
       System.out.println ("ASCII value - " + i);
  }

In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.

How to verify if nginx is running or not?

This is probably system-dependent, but this is the simplest way I've found.

if [ -e /var/run/nginx.pid ]; then echo "nginx is running"; fi

That's the best solution for scripting.

How to store a dataframe using Pandas

Pandas DataFrames have the to_pickle function which is useful for saving a DataFrame:

import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Convert Dictionary<string,string> to semicolon separated string in c#

Another option is to use the Aggregate extension rather than Join:

String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);

Handling identity columns in an "Insert Into TABLE Values()" statement?

set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)

where 'customer' is table name

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

Scroll to the top of the page after render in react.js

This code will cause a smooth behavior on the scroll:

<div onClick={() => {
   ReactDOM.findDOMNode(this.headerRef)
      .scrollIntoView({behavior: "smooth"});
                }} 
  className='go-up-button' >
</div>

You can pass other parameters inside the scrollIntoView() Following syntax can be used:

element.scrollIntoView();
element.scrollIntoView(alignToTop); // Boolean parameter
element.scrollIntoView(scrollIntoViewOptions); // Object parameter

alignToTop Optional Is a Boolean value:

If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value.
If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}.

scrollIntoViewOptions Optional Is an Object with the following properties:

*behavior* Optional
    Defines the transition animation.
    One of "auto", "instant", or "smooth". Defaults to "auto".
*block* Optional
    One of "start", "center", "end", or "nearest". Defaults to "center".
*inline* Optional
    One of "start", "center", "end", or "nearest". Defaults to "nearest".

More details can be found here: MDN docs

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE [TableName] ADD CONSTRAINT  [constraintName] UNIQUE ([columns])

Key Listeners in python?

Although I like using the keyboard module to capture keyboard events, I don't like its record() function because it returns an array like [KeyboardEvent("A"), KeyboardEvent("~")], which I find kind of hard to read. So, to record keyboard events, I like to use the keyboard module and the threading module simultaneously, like this:

import keyboard
import string
from threading import *


# I can't find a complete list of keyboard keys, so this will have to do:
keys = list(string.ascii_lowercase)
"""
Optional code(extra keys):

keys.append("space_bar")
keys.append("backspace")
keys.append("shift")
keys.append("esc")
"""
def listen(key):
    while True:
        keyboard.wait(key)
        print("[+] Pressed",key)
threads = [Thread(target=listen, kwargs={"key":key}) for key in keys]
for thread in threads:
    thread.start()

What is the default Jenkins password?

Before installing jenkins, create a user named jenkins and set password there. Then after installing jenkins you can use the password you created.

How to use string.substr() function?

Possible solution with string_view

void do_it_with_string_view( void )
{
    std::string a { "12345" };
    for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
        std::cout << v.substr( 0, 2 ) << " ";
    std::cout << std::endl;
}

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

According to Google Developers article, you can:

Spring Boot Multiple Datasource

Using two datasources you need their own transaction managers.

@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction

@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

Convert time.Time to string

package main                                                                                                                                                           

import (
    "fmt"
    "time"
)

// @link https://golang.org/pkg/time/

func main() {

    //caution : format string is `2006-01-02 15:04:05.000000000`
    current := time.Now()

    fmt.Println("origin : ", current.String())
    // origin :  2016-09-02 15:53:07.159994437 +0800 CST

    fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
    // mm-dd-yyyy :  09-02-2016

    fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
    // yyyy-mm-dd :  2016-09-02

    // separated by .
    fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
    // yyyy.mm.dd :  2016.09.02

    fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
    // yyyy-mm-dd HH:mm:ss :  2016-09-02 15:53:07

    // StampMicro
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994

    //StampNano
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994437
}    

Call one constructor from another

Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:

public class Sample
{
    public Sample(object inputToInt)
    {
        _intField = objectToInt(inputToInt);
    }

    public int IntProperty => _intField;

    private readonly int _intField;
}

public static int objectToInt(object inputToInt)
{
    switch (inputToInt)
        {
            case int inputInt:
                return inputInt;
            break;
            case string inputString:
            if (!int.TryParse(inputString, out int parsedInt))
            {
                throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
            }
            return parsedInt;

            default:
                throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
            break;
        }
}

How to run a function in jquery

You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:

jQuery.fn.doSomething = function () {
   this.css("position","absolute");
   return this;
}

And the way to call it:

$("#someRandomDiv").doSomething();

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

Line continue character in C#

You must use one of the following ways:

    string s = @"loooooooooooooooooooooooong loooooong
                  long long long";

string s = "loooooooooong loooong" +
           " long long" ;

Getting the .Text value from a TextBox

Use this instead:

string objTextBox = t.Text;

The object t is the TextBox. The object you call objTextBox is assigned the ID property of the TextBox.

So better code would be:

TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;

Client to send SOAP request and receive response

As an alternative, and pretty close to debiasej approach. Since a SOAP request is just a HTTP request, you can simply perform a GET or POST using with HTTP client, but it's not mandatory to build SOAP envelope.

Something like this:

using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HGF.Infraestructure.Communications
{
    public class SOAPSample
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILogger<DocumentProvider> _logger;

        public SOAPSample(ILogger<DocumentProvider> logger,
                          IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            _logger = logger;
        }

        public async Task<string> UsingGet(int value1, int value2)
        {
            try
            {
                var client = _clientFactory.CreateClient();
                var response = await client.GetAsync($"https://hostname.com/webservice.asmx/SampleMethod?value1={value1}&value2={value2}", HttpCompletionOption.ResponseHeadersRead);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }


        public async Task<string> UsingPost(int value1, int value2)
        {
            try
            {
                var content = new StringContent($"value1={value1}&value2={value2}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var client = _clientFactory.CreateClient();
                var response = await client.PostAsync("https://hostname.com/webservice.asmx/SampleMethod", content);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }
    }
}

Of course, it depends on your scenario. If the payload is too complex, then this won't work

clear data inside text file in c++

Deleting the file will also remove the content. See remove file.

How to run a Powershell script from the command line and pass a directory as a parameter

you are calling a script file not a command so you have to use -file eg :

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

for PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

Excel telling me my blank cells aren't blank

This works with numbers.

If your range is O8:O20, then in a nearby empty range (e.g. T8:T20) enter =O8/1 and fill down. This will give you a result of #VALUE for the 'empty' cells and your original number will remain as it was.

Then with the range T8:20 selected (CTL-* if it's not already) hit F5 and choose Special. From the Special dialogue, choose Errors and click OK. This will deselect your actual numbers leaving only the #VALUE cells selected. Delete them and you will have actual empty cells. Copy T8:T20 and paste back over O8:O20.

Essentially, since blank cells doesn't work, you need to convert the 'empty' cells into something that the Go To Special can latch on to. Any action that would convert into #VALUE would work, and other 'error' types should be supported as well.

Install apps silently, with granted INSTALL_PACKAGES permission

I checked all the answers, the conclusion seems to be you must have root access to the device first to make it work.

But then I found these articles very useful. Since I'm making "company-owned" devices.

How to Update Android App Silently Without User Interaction

Android Device Owner - Minimal App

Here is google's the documentation about "managed-device"

Fully managed device

Prevent jQuery UI dialog from setting focus to first textbox

jQuery UI 1.10.0 Changelog lists ticket 4731 as being fixed.

Looks like focusSelector was not implemented, but a cascading search for various elements was used instead. From the ticket:

Extend autofocus, starting with [autofocus], then :tabbable content, then buttonpane, then close button, then dialog

So, mark an element with the autofocus attribute and that is the element that should get the focus:

<input autofocus>

In the documentation, the focus logic is explained (just under the table of contents, under the title 'Focus'):

Upon opening a dialog, focus is automatically moved to the first item that matches the following:

  1. The first element within the dialog with the autofocus attribute
  2. The first :tabbable element within the dialog's content
  3. The first :tabbable element within the dialog's buttonpane
  4. The dialog's close button
  5. The dialog itself

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to write to Console.Out during execution of an MSTest test

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

What are the correct version numbers for C#?

The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

Python Selenium accessing HTML source

By using the page source you will get the whole HTML code.
So first decide the block of code or tag in which you require to retrieve the data or to click the element..

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

You can find the elements by name, XPath, id, link and CSS path.

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

Run a vbscript from another vbscript

You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others

To use Run (Simple Method)

Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn

ProgramPath is the full path to your script you want to run
ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)])
IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run Method
WaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.

NOTE: The Run method can return the exit code but you must set WaitOnReturn to True, and assign the 'WshShell.Run' to a variable. (EX: ExitCode=WshShell.Run (Command,intWindowStyle,True))

To Use EXEC (Advanced Method)

Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
    'Currently Waiting on the program to finish execution.
    WScript.Sleep 300
Loop

ProgramPath same as Run READ RUN'S DESCRIPTION
ProgramArgs DITTO
ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe". Note that in order to use stdin and stdout (we'll cover what these are a bit further down) you must choose "CScript.exe".
Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.

More Details about the members of Process Object

  1. ExitCode This is the exit code that is returned when the process terminates.
  2. ProcessID This is the ID that is assigned to the process, every process has an unique processID.
  3. Status This is a code number that indicates the status of the process, it get set to '-1' when the process terminates.
  4. StdErr This is the object that represents the Standard Error Stream
  5. StdIn This is the Object that represents the Standard Input Stream, use it to write additional parameters or anything you want to pass to the script you are calling. (Process.StdIn.WriteLine "Hello Other Worlds")
  6. StdOut This is the Object that represents the Standard Output Stream, It is READONLY so you can use Process.StdOut.ReadLine. This is the stream that the called script will receive any information sent by the calling script's stdin. If you used the stdin's example then StdOut.Readline will return "Hello Other Worlds". If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not Responding
    Note: you can use Read or ReadAll instead of ReadLine if you want. Use Read (X) if you want to read X amount of characters. Or ReadAll if you want the rest of the stream.
  7. Terminate Call this method to force terminate the process.

For more information about WshShell.Exec go to Exec Method Windows Scripting Host