Programs & Examples On #Rendertarget

Are HTTP cookies port specific?

According to RFC2965 3.3.1 (which might or might not be followed by browsers), unless the port is explicitly specified via the port parameter of the Set-Cookie header, cookies might or might not be sent to any port.

Google's Browser Security Handbook says: by default, cookie scope is limited to all URLs on the current host name - and not bound to port or protocol information. and some lines later There is no way to limit cookies to a single DNS name only [...] likewise, there is no way to limit them to a specific port. (Also, keep in mind, that IE does not factor port numbers into its same-origin policy at all.)

So it does not seem to be safe to rely on any well-defined behavior here.

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

Java GC (Allocation Failure)

When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.

 -Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps 

How to rsync only a specific list of files?

--files-from= parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:

rsync -av --files-from=/path/to/file / /tmp/

This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:

find /var/* -name *.log > file

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Stash just a single file

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

Unknown URL content://downloads/my_downloads

I have encountered the exception java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/7505 in getting the doucument from the downloads. This solution worked for me.

else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
            }

            String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                id = id.replaceFirst("raw:", "");
                File file = new File(id);
                if (file.exists())
                    return id;
            }

            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }

This the method used to get the filepath

   public static String getFilePath(Context context, Uri uri) {

    Cursor cursor = null;
    final String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

What is the size of column of int(11) in mysql in bytes?

In MySQL integer int(11) has size is 4 bytes which equals 32 bit.

Signed value is : -2^(32-1) to 0 to 2^(32-1)-1 = -2147483648 to 0 to 2147483647

Unsigned values is : 0 to 2^32-1 = 0 to 4294967295

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

How do you add PostgreSQL Driver as a dependency in Maven?

Updating for latest release:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.14</version>
</dependency>

Source

Hope it helps!

Difference between two dates in years, months, days in JavaScript

This code should give you desired results

//************************** Enter your dates here **********************//

var startDate = "10/05/2014";
var endDate = "11/3/2016"

//******* and press "Run", you will see the result in a popup *********//



var noofdays = 0;
var sdArr = startDate.split("/");
var startDateDay = parseInt(sdArr[0]);
var startDateMonth = parseInt(sdArr[1]);
var startDateYear = parseInt(sdArr[2]);
sdArr = endDate.split("/")
var endDateDay = parseInt(sdArr[0]);
var endDateMonth = parseInt(sdArr[1]);
var endDateYear = parseInt(sdArr[2]);

console.log(startDateDay+' '+startDateMonth+' '+startDateYear);
var yeardays = 365;
var monthArr = [31,,31,30,31,30,31,31,30,31,30,31];
var noofyears = 0
var noofmonths = 0;

if((startDateYear%4)==0) monthArr[1]=29;
else monthArr[1]=28;

if(startDateYear == endDateYear){

    noofyears = 0;
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);
   
}else{
    if(endDateMonth < startDateMonth){
        noofyears = (endDateYear - startDateYear)-1;  
    if(noofyears < 1) noofyears = 0;
  }else{
            noofyears = endDateYear - startDateYear;  
  }
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);   
}
 
 alert(noofyears+' year, '+ noofmonths+' months, '+ noofdays+' days'); 

function getDayDiff(startDate,endDate){ 
    if(endDateDay >=startDateDay){
      noofdays = 0;
      if(endDateDay > startDateDay) {
        noofdays = endDateDay - startDateDay;
       }
     }else{
            if((endDateYear%4)==0) {
            monthArr[1]=29;
        }else{
            monthArr[1] = 28;
        }
        
        if(endDateMonth != 1)
        noofdays = (monthArr[endDateMonth-2]-startDateDay) + endDateDay;
        else
        noofdays = (monthArr[11]-startDateDay) + endDateDay;
     }
    return noofdays;
}

function getMonthDiff(startDate,endDate){
        if(endDateMonth > startDateMonth){
        noofmonths = endDateMonth - startDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
      }else{
        noofmonths = (12-startDateMonth) + endDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
     }

return noofmonths;
}

https://jsfiddle.net/moremanishk/hk8c419f/

Object of class mysqli_result could not be converted to string in

mysqli:query() returns a mysqli_result object, which cannot be serialized into a string.

You need to fetch the results from the object. Here's how to do it.

If you need a single value.

Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

If you need multiple values.

Use foreach loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];
}

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

And that work form me!

I hope it could be useful for some body else!

How to obtain a Thread id in Python?

Using the logging module you can automatically add the current thread identifier in each log entry. Just use one of these LogRecord mapping keys in your logger format string:

%(thread)d : Thread ID (if available).

%(threadName)s : Thread name (if available).

and set up your default handler with it:

logging.basicConfig(format="%(threadName)s:%(message)s")

Visual Studio Code Automatic Imports

VS Code supports this out of the box now, but the feature sometimes works and sometimes doesn't, it seems. As far as I could find out, VS Code has to load data needed for auto imports, which happens more or less like this:

  • Load data for all exports from your local files
  • Load data for all exports from node_modules/@types
  • Load data for all exports from node_modules/{packageName} only if any of your local files is importing them

This is better described in this comment: https://github.com/microsoft/TypeScript/issues/31763#issuecomment-537226190.

Due to bugs either in VS Code or in specific packages' type declarations, the last two points don't always work. That was my case, I couldn't see react-bootstrap auto imports in a plain Create-React-App. What finally fixed it was manually copying the package folder from node_modules to node_modules/@types and leaving there only the type declaration files, e.g. Button.d.ts. This is not great because if you ever delete node_modules folder it will stop working again. But I prefer this from always having to manually type imports. This was my last resort after trying and failing with these methods:

  • Update VS Code (v. 1.45.1)
  • Install types for your package, e.g. npm install --save @types/react-bootstrap
  • Add jsconfig.json file and play with the settings as other people suggested
  • Try out all the plugins for automatic imports

I hope this helps someone!

Changing text color of menu item in navigation drawer

Use app:itemIconTint in your NavigationView, ej:

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:itemTextColor="@color/customColor"
    app:itemIconTint="@color/customColor"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_home"
    app:menu="@menu/activity_home_drawer" />

What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 

or

1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

Get and set position with jQuery .offset()

I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.

Here's one way to position your elements using the position feature:

var options = {
    "my": "top left",
    "at": "top left",
    "of": ".layer1"
};
$(".layer2").position(options);

How to play a sound in C#, .NET

For Windows Forms one way is to use the SoundPlayer

private void Button_Click(object sender, EventArgs e)
{
    using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav")) {
        soundPlayer.Play(); // can also use soundPlayer.PlaySync()
    }
}

MSDN page

This will also work with WPF, but you have other options like using MediaPlayer MSDN page

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.

How to squash all git commits into one?

To squash using grafts

Add a file .git/info/grafts, put there the commit hash you want to become your root

git log will now start from that commit

To make it 'real' run git filter-branch

How to get file_get_contents() to work with HTTPS?

Just add two lines in your php.ini file.

extension=php_openssl.dll

allow_url_include = On

its working for me.

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

What is the difference between UTF-8 and ISO-8859-1?

UTF-8 is a multibyte encoding that can represent any Unicode character. ISO 8859-1 is a single-byte encoding that can represent the first 256 Unicode characters. Both encode ASCII exactly the same way.

Declare variable in SQLite and use it

I appreciate that the other solutions do not depend on any other software tool, but why not just use another programming language that can interface to SQLite such as C#, C++, Go, Haskell, Java, Lua, Python, or Rust?

What does the @Valid annotation indicate in Spring?

@Valid in itself has nothing to do with Spring. It's part of Bean Validation specification(there are several of them, the latest one being JSR 380 as of second half of 2017), but @Valid is very old and derives all the way from JSR 303.

As we all know, Spring is very good at providing integration with all different JSRs and java libraries in general(think of JPA, JTA, Caching, etc.) and of course those guys took care of validation as well. One of the key components that facilitates this is MethodValidationPostProcessor.

Trying to answer your question - @Valid is very handy for so called validation cascading when you want to validate a complex graph and not just a top-level elements of an object. Every time you want to go deeper, you have to use @Valid. That's what JSR dictates. Spring will comply with that with some minor deviations(for example I tried putting @Validated instead of @Valid on RestController method and validation works, but the same will not apply for a regular "service" beans).

Clear the entire history stack and start a new activity on Android

Advanced Reuseable Kotlin:

You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If you plan to use this regularly, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

If you need the option to add additional flags in other situations, add an optional param to the extension function.

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

Checking if a collection is empty in Java: which is the best method?

I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

JavaScript: How do I print a message to the error console?

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

Binding multiple events to a listener (without JQuery)?

One way how to do it:

_x000D_
_x000D_
const troll = document.getElementById('troll');_x000D_
_x000D_
['mousedown', 'mouseup'].forEach(type => {_x000D_
 if (type === 'mousedown') {_x000D_
  troll.addEventListener(type, () => console.log('Mouse is down'));_x000D_
 }_x000D_
        else if (type === 'mouseup') {_x000D_
                troll.addEventListener(type, () => console.log('Mouse is up'));_x000D_
        }_x000D_
});
_x000D_
img {_x000D_
  width: 100px;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<div id="troll">_x000D_
  <img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">_x000D_
</div>
_x000D_
_x000D_
_x000D_

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

What I did to solve was simply:

  1. Run docker ps -a
  2. Check for the command of the container (mine started with /bin/sh)
  3. Run docker-compose exec < name_of_service > /bin/sh (if that is what started your command

This is for solving when using docker compose

Unable to generate an explicit migration in entity framework

I had the same problem. Apparently entity framework generates this error when it's unable to connect to the database. So make sure that you're able to access it before searching for other problems.

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

<uses-permission android:name="android.permission.INTERNET" />

What is the time complexity of indexing, inserting and removing from common data structures?

Information on this topic is now available on Wikipedia at: Search data structure

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

 * The cost to add or delete an element into a known location in the list 
   (i.e. if you have an iterator to the location) is O(1). If you don't 
   know the location, then you need to traverse the list to the location
   of deletion/insertion, which takes O(n) time. 

** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
   arbitrary element.

Closing Application with Exit button

try this for close app

Activity.finish();
System.exit(0);

How to set up Automapper in ASP.NET Core

I solved it this way (similar to above but I feel like it's a cleaner solution) Works with .NET Core 3.x

Create MappingProfile.cs class and populate constructor with Maps (I plan on using a single class to hold all my mappings)

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Source, Dest>().ReverseMap();
        }
    }

In Startup.cs, add below to add to DI (the assembly arg is for the class that holds your mapping configs, in my case, it's the MappingProfile class).

//add automapper DI
services.AddAutoMapper(typeof(MappingProfile));

In Controller, use it like you would any other DI object

    [Route("api/[controller]")]
    [ApiController]
    public class AnyController : ControllerBase
    {
        private readonly IMapper _mapper;

        public AnyController(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        public IActionResult Get(int id)
        {
            var entity = repository.Get(id);
            var dto = _mapper.Map<Dest>(entity);
            
            return Ok(dto);
        }
    }


SoapFault exception: Could not connect to host

I finally found the reason,its becuse of the library can't find a CA bundle on your system. PHP >= v5.6 automatically sets verify_peer to true by default. However, not all systems have a known CA bundle on disk .

You can try one of these procedures:

1.If you have a CA file on your system, set openssl.cafile or curl.cainfo in your php.ini to the path of your CA file.

2.Manually specify your SSL CA file location

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);  
curl_setopt($cHandler, CURLOPT_CAINFO, $path-of-your-ca-file);

3.disabled verify_peer

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

How do you change the server header returned by nginx?

It’s very simple: Add these lines to server section:

server_tokens off;
more_set_headers 'Server: My Very Own Server';

how to convert 2d list to 2d numpy array?

np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:

aArray=np.array([1,1,1])

bArray=np.array([2,2,2])

aList=[aArray, bArray]

xArray=np.array(aList)

xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

How to disable text selection using jQuery?

This is actually very simple. To disable text selection (and also click+drag-ing text (e.g a link in Chrome)), just use the following jQuery code:

$('body, html').mousedown(function(event) {
    event.preventDefault();
});

All this does is prevent the default from happening when you click with your mouse (mousedown()) in the body and html tags. You can very easily change the element just by changing the text in-between the two quotes (e.g change $('body, html') to $('#myUnselectableDiv') to make the myUnselectableDiv div to be, well, unselectable.

A quick snippet to show/prove this to you:

_x000D_
_x000D_
$('#no-select').mousedown(function(event) {_x000D_
  event.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>_x000D_
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
_x000D_
_x000D_
_x000D_

Please note that this effect is not perfect, and performs the best while making the whole window not selectable. You might also want to add

the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

as well, by using that section of Vladimir's answer above. (get to his post here)

finding and replacing elements in a list

You can simply use list comprehension in python:

def replace_element(YOUR_LIST, set_to=NEW_VALUE):
    return [i
            if SOME_CONDITION
            else NEW_VALUE
            for i in YOUR_LIST]

for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:

def replace_element(YOUR_LIST, set_to=10):
    return [i
            if i != 1  # keeps all elements not equal to one
            else set_to  # replaces 1 with 10
            for i in YOUR_LIST]

Jquery selector input[type=text]')

Using a normal css selector:

$('.sys input[type=text], .sys select').each(function() {...})

If you don't like the repetition:

$('.sys').find('input[type=text],select').each(function() {...})

Or more concisely, pass in the context argument:

$('input[type=text],select', '.sys').each(function() {...})

Note: Internally jQuery will convert the above to find() equivalent

http://api.jquery.com/jQuery/

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

I personally find the first alternative to be the most readable :), your take though

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes, the order of elements in a python list is persistent.

Is 'bool' a basic datatype in C++?

bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like

enum bool {
    false, true
};

So did the Windows API. Starting with C99, we have _Bool as a basic data type. Including stdbool.h will typedef #define that to bool and provide the constants true and false. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.

Difference between partition key, composite key and clustering key in Cassandra?

Worth to note, you will probably use those lots more than in similar concepts in relational world (composite keys).

Example - suppose you have to find last N users who recently joined user group X. How would you do this efficiently given reads are predominant in this case? Like that (from offical Cassandra guide):

CREATE TABLE group_join_dates (
    groupname text,
    joined timeuuid,
    join_date text,
    username text,
    email text,
    age int,
    PRIMARY KEY ((groupname, join_date), joined)
) WITH CLUSTERING ORDER BY (joined DESC)

Here, partitioning key is compound itself and the clustering key is a joined date. The reason why a clustering key is a join date is that results are already sorted (and stored, which makes lookups fast). But why do we use a compound key for partitioning key? Because we always want to read as few partitions as possible. How putting join_date in there helps? Now users from the same group and the same join date will reside in a single partition! This means we will always read as few partitions as possible (first start with the newest, then move to older and so on, rather than jumping between them).

In fact, in extreme cases you would also need to use the hash of a join_date rather than a join_date alone - so that if you query for last 3 days often those share the same hash and therefore are available from same partition!

trying to animate a constraint in swift

SWIFT 4.x :

self.mConstraint.constant = 100.0
UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
}

Example with completion:

self.mConstraint.constant = 100
UIView.animate(withDuration: 0.3, animations: {
        self.view.layoutIfNeeded()
    }, completion: {res in
        //Do something
})

Bootstrap with jQuery Validation Plugin

This makes up the fields

 $("#form_questionario").validate({
                debug: false,
                errorElement: "span",
                errorClass: "help-block",
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('.form-group').addClass('has-error');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('.form-group').removeClass('has-error');
                },
                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length || element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
                        error.insertBefore(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                },
                // Specify the validation rules
                rules: {
                        'campo1[]': 'required',
                        'campo2[]': 'required',
                        'campo3[]': 'required',
                        'campo4[]': 'required',
                        'campo5[]': 'required'
                        },

                submitHandler: function (form) {
                    form.submit();
                }
            });

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

INNER JOIN vs LEFT JOIN performance in SQL Server

I found something interesting in SQL server when checking if inner joins are faster than left joins.

If you dont include the items of the left joined table, in the select statement, the left join will be faster than the same query with inner join.

If you do include the left joined table in the select statement, the inner join with the same query was equal or faster than the left join.

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

How can I count the rows with data in an Excel sheet?

You should use the sumif function in Excel:

=SUMIF(A5:C10;"Text_to_find";C5:C10)

This function takes a range like this square A5:C10 then you have some text to find this text can be in A or B then it will add the number from the C-row.

Calling Java from Python

I've been integrating a lot of stuff into Python lately, including Java. The most robust method I've found is to use IKVM and a C# wrapper.

IKVM has a neat little application that allows you to take any Java JAR, and convert it directly to .Net DLL. It simply translates the JVM bytecode to CLR bytecode. See http://sourceforge.net/p/ikvm/wiki/Ikvmc/ for details.

The converted library behaves just like a native C# library, and you can use it without needing the JVM. You can then create a C# DLL wrapper project, and add a reference to the converted DLL.

You can now create some wrapper stubs that call the methods that you want to expose, and mark those methods as DllEport. See https://stackoverflow.com/a/29854281/1977538 for details.

The wrapper DLL acts just like a native C library, with the exported methods looking just like exported C methods. You can connect to them using ctype as usual.

I've tried it with Python 2.7, but it should work with 3.0 as well. Works on Windows and the Linuxes

If you happen to use C#, then this is probably the best approach to try when integrating almost anything into python.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Alright, this is probably the easiest way to do it:

  1. First of all, you will have to install GAPPS.
  2. Next, open the virtual box and wait for the home screen to show up on Genymotion.
  3. Drag and drop the GAPPS folder that you had downloaded earlier on into Genymotion.
  4. You would get a prompt. Click OK. You would see a lot of errors, but just ignore them and wait for the successful prompt to come up. Click OK again and restart the virtual device.
  5. A Google account screen should show up. Open up the playstore app if it doesn't show up. Sign into your account. Again ignore the errors.
  6. The playstore should open now and should be fully functional.

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Laravel migration table field's type change

all other answers are Correct But Before you run

php artisan migrate

make sure you run this code first

composer require doctrine/dbal

to avoid this error

RuntimeException : Changing columns for table "items" requires Doctrine DBAL; install "doctrine/dbal".

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

QUERY syntax using cell reference

Copied from Web Applications:

=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")

What is the difference between encrypting and signing in asymmetric encryption?

Yeah think of signing data as giving it your own wax stamp that nobody else has. It is done to achieve integrity and non-repudiation. Encryption is so no-one else can see the data. This is done to achieve confidentiality. See wikipedia http://en.wikipedia.org/wiki/Information_security#Key_concepts

A signature is a hash of your message signed using your private key.

How to hide/show more text within a certain length (like youtube)

I know this question is a little old (and has had it's answer selected already) but for those wanting another option that're coming across this question through Google (like I did), I found this dynamic text shortener:

Dynamically shortened Text with “Show More” link using jQuery

I found it was better because you could set the character limit, rather than extra spans in the code, or setting a specific height to a container.
Hope it helps someone else out!

Adding data attribute to DOM

in Jquery "data" doesn't refresh by default :

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());

You'd use "attr" instead for live update:

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());

Python: 'break' outside loop

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like

for item in some_iterable:
    ...
    if break_condition():
        break 

The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.

Fastest way to serialize and deserialize .NET objects

The binary serializer included with .net should be faster that the XmlSerializer. Or another serializer for protobuf, json, ...

But for some of them you need to add Attributes, or some other way to add metadata. For example ProtoBuf uses numeric property IDs internally, and the mapping needs to be somehow conserved by a different mechanism. Versioning isn't trivial with any serializer.

Role/Purpose of ContextLoaderListener in Spring?

Root and child contexts Before reading further, please understand that –

Spring can have multiple contexts at a time. One of them will be root context, and all other contexts will be child contexts.

All child contexts can access the beans defined in root context; but opposite is not true. Root context cannot access child contexts beans.

ApplicationContext :

applicationContext.xml is the root context configuration for every web application. Spring loads applicationContext.xml file and creates the ApplicationContext for the whole application. There will be only one application context per web application. If you are not explicitly declaring the context configuration file name in web.xml using the contextConfigLocation param, Spring will search for the applicationContext.xml under WEB-INF folder and throw FileNotFoundException if it could not find this file.

ContextLoaderListener Performs the actual initialization work for the root application context. Reads a “contextConfigLocation” context-param and passes its value to the context instance, parsing it into potentially multiple file paths which can be separated by any number of commas and spaces, e.g. “WEB-INF/applicationContext1.xml, WEB-INF/applicationContext2.xml”. ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener, just a basic minimum web.xml with DispatcherServlet.

DispatcherServlet DispatcherServlet is essentially a Servlet (it extends HttpServlet) whose primary purpose is to handle incoming web requests matching the configured URL pattern. It take an incoming URI and find the right combination of controller and view. So it is the front controller.

When you define a DispatcherServlet in spring configuration, you provide an XML file with entries of controller classes, views mappings etc. using contextConfigLocation attribute.

WebApplicationContext Apart from ApplicationContext, there can be multiple WebApplicationContext in a single web application. In simple words, each DispatcherServlet associated with single WebApplicationContext. xxx-servlet.xml file is specific to the DispatcherServlet and a web application can have more than one DispatcherServlet configured to handle the requests. In such scenarios, each DispatcherServlet would have a separate xxx-servlet.xml configured. But, applicationContext.xml will be common for all the servlet configuration files. Spring will by default load file named “xxx-servlet.xml” from your webapps WEB-INF folder where xxx is the servlet name in web.xml. If you want to change the name of that file name or change the location, add initi-param with contextConfigLocation as param name.

Comparison and relation between them :

ContextLoaderListener vs DispatcherServlet

ContextLoaderListener creates root application context. DispatcherServlet entries create one child application context per servlet entry. Child contexts can access beans defined in root context. Beans in root context cannot access beans in child contexts (directly). All contexts are added to ServletContext. You can access root context using WebApplicationContextUtils class.

After reading the Spring documentation, following is the understanding:

a) Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here.

b) ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).

c) DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.

d) When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. Refer documentation here.

When we are working with Spring MVC and are also using Spring in the services layer, we provide two application-contexts. The first one is configured using ContextLoaderListener and the other with DispatcherServlet

Generally, you will define all MVC related beans (controller and views etc) in DispatcherServlet context, and all cross-cutting beans such as security, transaction, services etc. at root context by ContextLoaderListener.

Refer this for more details : https://siddharthnawani.blogspot.com/2019/10/contextloaderlistener-vs.html

How to set proper codeigniter base url?

this is for server nd live site i apply in hostinger.com and its working fine

1st : $config['base_url'] = 'http://yoursitename.com'; (in confing.php)

2) : src="<?=base_url()?>assest/js/wow.min.js" (in view file )

3) : href="<?php echo base_url()?>index.php/Mycontroller/Method" (for url link or method calling )

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

Looping through a hash, or using an array in PowerShell

Here is another quick way, just using the key as an index into the hash table to get the value:

$hash = @{
    'a' = 1;
    'b' = 2;
    'c' = 3
};

foreach($key in $hash.keys) {
    Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to convert signed to unsigned integer in python

You could use the struct Python built-in library:

Encode:

import struct

i = -6884376
print('{0:b}'.format(i))

packed = struct.pack('>l', i)  # Packing a long number.
unpacked = struct.unpack('>L', packed)[0]  # Unpacking a packed long number to unsigned long
print(unpacked)
print('{0:b}'.format(unpacked))

Out:

-11010010000110000011000
4288082920
11111111100101101111001111101000

Decode:

dec_pack = struct.pack('>L', unpacked)  # Packing an unsigned long number.
dec_unpack = struct.unpack('>l', dec_pack)[0]  # Unpacking a packed unsigned long number to long (revert action).
print(dec_unpack)

Out:

-6884376

[NOTE]:

  • > is BigEndian operation.
  • l is long.
  • L is unsigned long.
  • In amd64 architecture int and long are 32bit, So you could use i and I instead of l and L respectively.

Plotting time-series with Date labels on x-axis

I like using the ggplot2 for this sort of thing:

df$Date <- as.Date( df$Date, '%m/%d/%Y')
require(ggplot2)
ggplot( data = df, aes( Date, Visits )) + geom_line() 

enter image description here

Capitalize words in string

I like to go with easy process. First Change string into Array for easy iterating, then using map function change each word as you want it to be.

function capitalizeCase(str) {
    var arr = str.split(' ');
    var t;
    var newt;
    var newarr = arr.map(function(d){
        t = d.split('');
        newt = t.map(function(d, i){
                  if(i === 0) {
                     return d.toUpperCase();
                    }
                 return d.toLowerCase();
               });
        return newt.join('');
      });
    var s = newarr.join(' ');
    return s;
  }

Difference between Git and GitHub

What is Git:

"Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency"

Git is a distributed peer-peer version control system. Each node in the network is a peer, storing entire repositories which can also act as a multi-node distributed back-ups. There is no specific concept of a central server although nodes can be head-less or 'bare', taking on a role similar to the central server in centralised version control systems.

What is GitHub:

"GitHub is a web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features."

Github provides access control and several collaboration features such as wikis, task management, and bug tracking and feature requests for every project.

You do not need GitHub to use Git.

GitHub (and any other local, remote or hosted system) can all be peers in the same distributed versioned repositories within a single project.

Github allows you to:

  • Share your repositories with others.
  • Access other user's repositories.
  • Store remote copies of your repositories (github servers) as backup of your local copies.

How to pop an alert message box using PHP?

PHP renders HTML and Javascript to send to the client's browser. PHP is a server-side language. This is what allows it do things like INSERT something into a database on the server.

But an alert is rendered by the browser of the client. You would have to work through javascript to get an alert.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:

long startDateLong = <...>

LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

Angular - Use pipes in services and components

Other answers don't work in angular 5?

I got an error because DatePipe is not a provider, so it cannot be injected. One solution is to put it as a provider in your app module but my preferred solution was to instantiate it.

Instantiate it where needed:

I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174

I wanted to use it within a pipe, so my example is within another pipe:

    import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
    import { DatePipe } from '@angular/common';

    @Pipe({
        name: 'when',
    })
    export class WhenPipe implements PipeTransform {
        static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));
        datePipe: DatePipe;

        constructor(@Inject(LOCALE_ID) private locale: string) {
            this.datePipe = new DatePipe(locale);
        }
        transform(value: string | Date): string {
            if (typeof(value) === 'string')
                value = new Date(value);

            return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')
        }
    }

The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly.

Make DatePipe a provider

In your app module you could also add DatePipe to your providers array like this:

    import { DatePipe } from '@angular/common';

    @NgModule({
        providers: [
            DatePipe
        ]
    })

Now you can just have it injected in your constructor where needed (like in cexbrayat's answer).

Summary:

Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself.

how to save and read array of array in NSUserdefaults in swift?

Here is:

var array : [String] = ["One", "Two", "Three"]
let userDefault = UserDefaults.standard
// set
userDefault.set(array, forKey: "array")
// retrieve 
if let fetchArray = userDefault.array(forKey: "array") as? [String] {
    // code 
}

How can I suppress the newline after a print statement?

Code for Python 3.6.1

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

Output

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

100% Min Height CSS layout

Probably the shortest solution (works only in modern browsers)

This small piece of CSS makes "the middle content part fill 100% of the space in between with the footer fixed to the bottom":

html, body { height: 100%; }
your_container { min-height: calc(100% - height_of_your_footer); }

the only requirement is that you need to have a fixed height footer.

For example for this layout:

    <html><head></head><body>
      <main> your main content </main>
      </footer> your footer content </footer>
    </body></html>

you need this CSS:

    html, body { height: 100%; }
    main { min-height: calc(100% - 2em); }
    footer { height: 2em; }

Java and SQLite

Typo: java -cp .:sqlitejdbc-v056.jar Test

should be: java -cp .:sqlitejdbc-v056.jar; Test

notice the semicolon after ".jar" i hope that helps people, could cause a lot of hassle

'LIKE ('%this%' OR '%that%') and something=else' not working

Break out the LIKE clauses into 2 separate statements, i.e.:

(fieldname1 LIKE '%this%' or fieldname1 LIKE '%that%' ) and something=else

string.split - by multiple character delimiter

To show both string.Split and Regex usage:

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Negate if condition in bash script

Better

if ! wget -q --spider --tries=10 --timeout=20 google.com
then
  echo 'Sorry you are Offline'
  exit 1
fi

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

How to set value of input text using jQuery

this is for classes

$('.nameofdiv').val('we are developers');

for ids

$('#nameofdiv').val('we are developers');

now if u have an iput in a form u can use

$("#form li.name input.name_val").val('we are awsome developers');

<> And Not In VB.NET

Is is not the same as = -- Is compares the references, whilst = will compare the values.

If you're using v2 of the .Net Framework (or later), there is the IsNot operator which will do the right thing, and read more naturally.

Best way to load module/class from lib folder in Rails 3?

I had the same problem. Here is how I solved it. The solution loads the lib directory and all the subdirectories (not only the direct). Of course you can use this for all directories.

# application.rb
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

What does 'public static void' mean in Java?

  • public means you can access the class from anywhere in the class/object or outside of the package or class
  • static means constant in which block of statement used only 1 time
  • void means no return type

How do I use Join-Path to combine more than two strings into a file path?

Join-Path is not exactly what you are looking for. It has multiple uses but not the one you are looking for. An example from Partying with Join-Path:

Join-Path C:\hello,d:\goodbye,e:\hola,f:\adios world
C:\hello\world
d:\goodbye\world
e:\hola\world
f:\adios\world

You see that it accepts an array of strings, and it concatenates the child string to each creating full paths. In your example, $path = join-path C: "Program Files" "Microsoft Office". You are getting the error since you are passing three positional arguments and join-path only accepts two. What you are looking for is a -join, and I could see this being a misunderstanding. Consider instead this with your example:

"C:","Program Files","Microsoft Office" -join "\"

-Join takes the array of items and concatenates them with \ into a single string.

C:\Program Files\Microsoft Office

Minor attempt at a salvage

Yes, I will agree that this answer is better, but mine could still work. Comments suggest there could be an issue with slashes, so to keep with my concatenation approach you could do this as well.

"C:","\\Program Files\","Microsoft Office\" -join "\" -replace "(?!^\\)\\{2,}","\"

So if there are issues with extra slashes it could be handled as long as they are not in the beginning of the string (allows UNC paths). [io.path]::combine('c:\', 'foo', '\bar\') would not work as expected and mine would account for that. Both require proper strings for input as you cannot account for all scenarios. Consider both approaches, but, yes, the other higher-rated answer is more terse, and I didn't even know it existed.

Also, would like to point out, my answer explains how what the OP doing was wrong on top of providing a suggestion to address the core problem.

Getting the ID of the element that fired an event

$(".classobj").click(function(e){
    console.log(e.currentTarget.id);
})

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

How do I use a custom Serializer with Jackson?

In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="serializers">
                        <array>
                            <bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
                        </array>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

was in unexplained way overwritten back to default by something.

This worked for me:

CustomObject.java

@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {

    private Long value;

    public Long getValue() {
        return value;
    }

    public void setValue(Long value) {
        this.value = value;
    }
}

CustomObjectSerializer.java

public class CustomObjectSerializer extends JsonSerializer<CustomObject> {

    @Override
    public void serialize(CustomObject value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("y", value.getValue());
        jgen.writeEndObject();
    }

    @Override
    public Class<CustomObject> handledType() {
        return CustomObject.class;
    }
}

No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

Android BroadcastReceiver within Activity

What do I do wrong?

The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.

Instead you probably want to startActivity ToastDisplay from the first activity?

BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).

There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.

Checkout another branch when there are uncommitted changes on the current branch

If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.

Example:

$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"

$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
     # experiment now contains changes that master doesn't have
     # any future changes to this file will keep you from changing branches
     # until the changes are stashed or committed

$ echo "and we're back" >> file.txt  # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

This goes for untracked files as well as tracked files. Here's an example for an untracked file.

Example:

$ git checkout -b experimental  # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"

$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
    file.txt
Please move or remove them before you can switch branches.
Aborting

A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...

$ echo 'experimental change' >> file.txt # change to existing tracked file
   # I want to save these, but not on master

$ git checkout -b experiment
M       file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"

Only variables should be passed by reference

save the array from explode() to a variable, and then call end() on this variable:

$tmp = explode('.', $file_name);
$file_extension = end($tmp);

btw: I use this code to get the file extension:

$ext = substr( strrchr($file_name, '.'), 1);

where strrchr extracts the string after the last . and substr cuts off the .

How do I install the yaml package for Python?

For me, installing development version of libyaml did it.

yum install libyaml-devel         #centos
apt-get install libyaml-dev       # ubuntu

android EditText - finished typing event

I ended her with the same problem and I could not use the the solution with onEditorAction or onFocusChange and did not want to try the timer. A timer is too dangerous for may taste, because of all the threads and too unpredictable, as you do not know when you code is executed.

The onEditorAction do not catch when the user leave without using a button and if you use it please notice that KeyEvent can be null. The focus is unreliable at both ends the user can get focus and leave without enter any text or selecting the field and the user do not need to leave the last EditText field.

My solution use onFocusChange and a flag set when the user starts editing text and a function to get the text from the last focused view, which I call when need.

I just clear the focus on all my text fields to tricker the leave text view code, The clearFocus code is only executed if the field has focus. I call the function in onSaveInstanceState so I do not have to save the flag (mEditing) as a state of the EditText view and when important buttons is clicked and when the activity is closed.

Be careful with TexWatcher as it is call often I use the condition on focus to not react when the onRestoreInstanceState code entering text. I

final EditText mEditTextView = (EditText) getView();

    mEditTextView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!mEditing && mEditTextView.hasFocus()) {
                mEditing = true;
            }
        }
    });
    mEditTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus && mEditing) {
                mEditing = false;
                ///Do the thing
            }
        }
    });
protected void saveLastOpenField(){
    for (EditText view:getFields()){
            view.clearFocus();
    }
}

min and max value of data type in C

To get the maximum value of an unsigned integer type t whose width is at least the one of unsigned int (otherwise one gets problems with integer promotions): ~(t) 0. If one wants to also support shorter types, one can add another cast: (t) ~(t) 0.

If the integer type t is signed, assuming that there are no padding bits, one can use:

((((t) 1 << (sizeof(t) * CHAR_BIT - 2)) - 1) * 2 + 1)

The advantage of this formula is that it is not based on some unsigned version of t (or a larger type), which may be unknown or unavailable (even uintmax_t may not be sufficient with non-standard extensions). Example with 6 bits (not possible in practice, just for readability):

010000  (t) 1 << (sizeof(t) * CHAR_BIT - 2)
001111  - 1
011110  * 2
011111  + 1

In two's complement, the minimum value is the opposite of the maximum value, minus 1 (in the other integer representations allowed by the ISO C standard, this is just the opposite of the maximum value).

Note: To detect signedness in order to decide which version to use: (t) -1 < 0 will work with any integer representation, giving 1 (true) for signed integer types and 0 (false) for unsigned integer types. Thus one can use:

(t) -1 < 0 ? ((((t) 1 << (sizeof(t) * CHAR_BIT - 2)) - 1) * 2 + 1) : (t) ~(t) 0

Can someone explain the dollar sign in Javascript?

Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934

According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:

The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6

Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

A useful shortcut from inside Sublime Text:

cmd-shift-P --> Browse Packages Now open user folder.

Ubuntu: Using curl to download an image

For those who don't have nor want to install wget, curl -O (capital "o", not a zero) will do the same thing as wget. E.g. my old netbook doesn't have wget, and is a 2.68 MB install that I don't need.

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

Tooltips with Twitter Bootstrap

The easiest way to use this is

put this in the header:

<script>
    $(function ($) {
        $("a").tooltip()
    });
</script>

and then

<a href="#" rel="tooltip" data-placement="bottom" title="My Tooltip Text">
    My link text
</a>

so with that js code if you have tag any where in your page with rel="tooltip" get the bootstrap tooltip.

good luck.

Cannot call getSupportFragmentManager() from activity

Your activity doesn't extend FragmentActivity from the support library, therefore the method is not present in the superclass

If you are targeting api 11 or above, you could use Activity.getFragmentManager instead.

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I was able to solve this problem by executing this statement

sudo dpkg-reconfigure mysql-server-5.5

Which will change the root password.

How can I verify if an AD account is locked?

If you want to check via command line , then use command "net user username /DOMAIN"

enter image description here

How to run crontab job every week on Sunday

@weekly work better for me! example,add the fellowing crontab -e ,it will work in every sunday 0:00 AM @weekly /root/fd/databasebackup/week.sh >> ~/test.txt

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Main was missing in the entry point configuration. enter image description here

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

We can solve Q2 by summing both the numbers themselves, and the squares of the numbers.

We can then reduce the problem to

k1 + k2 = x
k1^2 + k2^2 = y

Where x and y are how far the sums are below the expected values.

Substituting gives us:

(x-k2)^2 + k2^2 = y

Which we can then solve to determine our missing numbers.

MySQL: #126 - Incorrect key file for table

I got this error when I set ft_min_word_len = 2 in my.cnf, which lowers the minimum word length in a full text index to 2, from the default of 4.

Repairing the table fixed the problem.

Absolute vs relative URLs

Assume we are creating a subsite whose files are in the folder http://site.ru/shop.

1. Absolute URL

Link to home page
href="http://sites.ru/shop/"

Link to the product page
href="http://sites.ru/shop/t-shirts/t-shirt-life-is-good/"

2. Relative URL

Link from home page to product page
href="t-shirts/t-shirt-life-is-good/"

Link from product page to home page
href="../../"

Although relative URL look shorter than absolute one, but the absolute URLs are more preferable, since a link can be used unchanged on any page of site.

Intermediate cases

We have considered two extreme cases: "absolutely" absolute and "absolutely" relative URLs. But everything is relative in this world. This also applies to URLs. Every time you say about absolute URL, you should always specify relative to what.

3. Protocol-relative URL

Link to home page
href="//sites.ru/shop/"

Link to product page
href="//sites.ru/shop/t-shirts/t-shirt-life-is-good/"

Google recommends such URL. Now, however, it is generally considered that http:// and https:// are different sites.

4. Root-relative URL

I.e. relative to the root folder of the domain.

Link to home page
href="/shop/"

Link to product page
href="/shop/t-shirts/t-shirt-life-is-good/"

It is a good choice if all pages are within the same domain. When you move your site to another domain, you don't have to do a mass replacements of the domain name in the URLs.

5. Base-relative URL (home-page-relative)

The tag <base> specifies the base URL, which is automatically added to all relative links and anchors. The base tag does not affect absolute links. As a base URL we'll specify the home page: <base href="http://sites.ru/shop/">.

Link to home page
href=""

Link to product page
href="t-shirts/t-shirt-life-is-good/"

Now you can move your site not only to any domain, but in any subfolder. Just keep in mind that, although URLs look like relative, in fact they are absolute. Especially pay attention to anchors. To navigate within the current page we have to write href="t-shirts/t-shirt-life-is-good/#comments" not href="#comments". The latter will throw on home page.

Conclusion

For internal links I use base-relative URLs (5). For external links and newsletters I use absolute URLs (1).

How to add a second x-axis in matplotlib

Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?" Yes, it is.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)

ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")

ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])

plt.show()

You'll get: enter image description here

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Remove the standard.jar. It's apparently of old JSTL 1.0 version when the TLD URIs were without the /jsp path. With JSTL 1.2 as available here you don't need a standard.jar at all. Just the jstl-1.2.jar in /WEB-INF/lib is sufficient.

See also:

Base64 Encoding Image

Check the following example:

// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'

Get Last Part of URL PHP

If you are looking for a robust version that can deal with any form of URLs, this should do nicely:

<?php

$url = "http://foobar.com/foo/bar/1?baz=qux#fragment/foo";
$lastSegment = basename(parse_url($url, PHP_URL_PATH));

Finding Number of Cores in Java

If you want to get number of physical cores you can run cmd and terminal command and then to parse the output to get info you need.Below is shown function that returns number of physical cores .

private int getNumberOfCPUCores() {
    OSValidator osValidator = new OSValidator();
    String command = "";
    if(osValidator.isMac()){
        command = "sysctl -n machdep.cpu.core_count";
    }else if(osValidator.isUnix()){
        command = "lscpu";
    }else if(osValidator.isWindows()){
        command = "cmd /C WMIC CPU Get /Format:List";
    }
    Process process = null;
    int numberOfCores = 0;
    int sockets = 0;
    try {
        if(osValidator.isMac()){
            String[] cmd = { "/bin/sh", "-c", command};
            process = Runtime.getRuntime().exec(cmd);
        }else{
            process = Runtime.getRuntime().exec(command);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    String line;

    try {
        while ((line = reader.readLine()) != null) {
            if(osValidator.isMac()){
                numberOfCores = line.length() > 0 ? Integer.parseInt(line) : 0;
            }else if (osValidator.isUnix()) {
                if (line.contains("Core(s) per socket:")) {
                    numberOfCores = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
                }
                if(line.contains("Socket(s):")){
                    sockets = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
                }
            } else if (osValidator.isWindows()) {
                if (line.contains("NumberOfCores")) {
                    numberOfCores = Integer.parseInt(line.split("=")[1]);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(osValidator.isUnix()){
        return numberOfCores * sockets;
    }
    return numberOfCores;
}

OSValidator class:

public class OSValidator {

private static String OS = System.getProperty("os.name").toLowerCase();

public static void main(String[] args) {

    System.out.println(OS);

    if (isWindows()) {
        System.out.println("This is Windows");
    } else if (isMac()) {
        System.out.println("This is Mac");
    } else if (isUnix()) {
        System.out.println("This is Unix or Linux");
    } else if (isSolaris()) {
        System.out.println("This is Solaris");
    } else {
        System.out.println("Your OS is not support!!");
    }
}

public static boolean isWindows() {
    return (OS.indexOf("win") >= 0);
}

public static boolean isMac() {
    return (OS.indexOf("mac") >= 0);
}

public static boolean isUnix() {
    return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
}

public static boolean isSolaris() {
    return (OS.indexOf("sunos") >= 0);
}
public static String getOS(){
    if (isWindows()) {
        return "win";
    } else if (isMac()) {
        return "osx";
    } else if (isUnix()) {
        return "uni";
    } else if (isSolaris()) {
        return "sol";
    } else {
        return "err";
    }
}

}

How do I jump out of a foreach loop in C#?

foreach (var item in listOfItems) {
  if (condition_is_met)
    // Any processing you may need to complete here...
    break; // return true; also works if you're looking to
           // completely exit this function.
}

Should do the trick. The break statement will just end the execution of the loop, while the return statement will obviously terminate the entire function. Judging from your question you may want to use the return true; statement.

Run class in Jar file

This is the right way to execute a .jar, and whatever one class in that .jar should have main() and the following are the parameters to it :

java -DLB="uk" -DType="CLIENT_IND" -jar com.fbi.rrm.rrm-batchy-1.5.jar

Pad a number with leading zeros in JavaScript

This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.

function ZeroPadNumber ( nValue )
{
    if ( nValue < 10 )
    {
        return ( '000' + nValue.toString () );
    }
    else if ( nValue < 100 )
    {
        return ( '00' + nValue.toString () );
    }
    else if ( nValue < 1000 )
    {
        return ( '0' + nValue.toString () );
    }
    else
    {
        return ( nValue );
    }
}

This function is also hardcoded to your particular need (4 digit padding), so it's not generic.

Difference between size and length methods?

length is constant which is used to find out the array storing capacity not the number of elements in the array

Example:

int[] a = new int[5]

a.length always returns 5, which is called the capacity of an array. But

number of elements in the array is called size

Example:

int[] a = new int[5]
a[0] = 10

Here the size would be 1, but a.length is still 5. Mind that there is no actual property or method called size on an array so you can't just call a.size or a.size() to get the value 1.

The size() method is available for collections, length works with arrays in Java.

How to export non-exportable private key from store

You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable. But if you patch (in memory) normal APIs, you can use the normal way to export :)

There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)

  1. download (and launch with administrative privileges) : http://blog.gentilkiwi.com/mimikatz (trunk version or last version)

Run it and enter the following commands in its prompt:

  1. privilege::debug (unless you already have it or target only CryptoApi)
  2. crypto::patchcng (nt 6) and/or crypto::patchcapi (nt 5 & 6)
  3. crypto::exportCertificates and/or crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE

The exported .pfx files are password protected with the password "mimikatz"

how to pass parameter from @Url.Action to controller function

Need To Two Or More Parameters Passing Throw view To Controller Use This Syntax... Try.. It.

var id=0,Num=254;var str='Sample';    
var Url = '@Url.Action("ViewNameAtController", "Controller", new RouteValueDictionary(new { id= "id", Num= "Num", Str= "str" }))'.replace("id", encodeURIComponent(id));
    Url = Url.replace("Num", encodeURIComponent(Num));
    Url = Url.replace("Str", encodeURIComponent(str));
    Url = Url.replace(/&amp;/g, "&");
window.location.href = Url;

ADB.exe is obsolete and has serious performance problems

I faced the same issue, and I tried following things, which didn't work:

  1. Deleting the existing AVD and creating a new one.

  2. Uninstall latest-existing and older versions (if you have) of SDK-Tools and SDK-Build-Tools and installing new ones.

What worked for me was uninstalling and re-installing latest PLATFORM-TOOLS, where adb actually resides.

Best way to store password in database

In your scenario, you can have a look at asp.net membership, it is good practice to store user's password as hashed string in the database. you can authenticate the user by comparing the hashed incoming password with the one stored in the database.

Everything has been built for this purposes, check out asp.net membership

window.close and self.close do not close the window in Chrome

If you can't close windows that aren't opened by the script, then you can destroy your page using this code:

 document.getElementsByTagName ('html') [0] .remove ();

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

How to set a value for a selectize.js input?

just ran into the same problem and solved it with the following line of code:

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

On mac the answers above unfortunately didn't work causing a ERROR 1045 (28000): Access denied for user 'root'@'localhost'

Doing the following worked for me:

sudo su
mysql -uroot
set password = password("password");

Took me embarassingly long to figure out hope it helps someone else.

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

If you have a dictionary you can turn it into a pandas data frame with the following line of code:

pd.DataFrame({"key": d.keys(), "value": d.values()})

How to Call a Function inside a Render in React/Jsx

The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,

First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.

So we use that variable to invoke the function by adding parentheses () at the end.

One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().

Bootstrap 3 navbar active li not changing background-color

In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:

<body data-spy="scroll" data-target="Id or class of the element you want to track">

In most cases I usually track active elements on my navbar, so I do the following:

<body data-spy="scroll" data-target=".navbar-fixed-top" >

Now in your CSS you can target .navbar-fixed-top .active a:

.navbar-fixed-top .active a { 
    // Put in some styling 
}

This should work if you are tracking active li elements in your top fixed navigation bar.

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

SecurityException: Permission denied (missing INTERNET permission?)

Be sure that the place where you adding

<uses-permission android:name="android.permission.INTERNET"/>

is right.

You should write it like that in AndroidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.project"> 
<uses-permission android:name="android.permission.INTERNET"/>

Dont make my mistakes :)

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

def norm(vector):
    return sqrt(sum(x * x for x in vector))    

def cosine_similarity(vec_a, vec_b):
        norm_a = norm(vec_a)
        norm_b = norm(vec_b)
        dot = sum(a * b for a, b in zip(vec_a, vec_b))
        return dot / (norm_a * norm_b)

This method seems to be somewhat faster than using sklearn's implementation if you pass in one pair of vectors at a time.

How do I activate a virtualenv inside PyCharm's terminal?

On Mac it's PyCharm => Preferences... => Tools => Terminal => Activate virtualenv, which should be enabled by default.

Capture screenshot of active window?

A little tweak to method static void ImageSave() will grant you the option where to save it. Credit goes to Microsoft (http://msdn.microsoft.com/en-us/library/sfezx97z.aspx)

static void ImageSave(string filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1)
    { 
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
        saveFileDialog1.Title = "Enregistrer un image";
        saveFileDialog1.ShowDialog();

        // If the file name is not an empty string open it for saving.
        if (saveFileDialog1.FileName != "")
        {
            // Saves the Image via a FileStream created by the OpenFile method.
            System.IO.FileStream fs =
               (System.IO.FileStream)saveFileDialog1.OpenFile();
            // Saves the Image in the appropriate ImageFormat based upon the
            // File type selected in the dialog box.
            // NOTE that the FilterIndex property is one-based.
            switch (saveFileDialog1.FilterIndex)
            {
                case 1:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case 2:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case 3:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Gif);
                    break;
            }

            fs.Close();
        }



    }

Your button_click event should be coded something like this...

private void btnScreenShot_Click(object sender, EventArgs e)
    {

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();


        ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1);

    }//

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Firstly you can find duplicate rows and find count of rows is used how many times and order it by number like this;

_x000D_
_x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

after that create a table and insert result to it.

_x000D_
_x000D_
create table CopyTable _x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

Finally, delete dublicate rows.No is start 0. Except fist number of each group delete all dublicate rows.

_x000D_
_x000D_
delete from  CopyTable where No!= 0;
_x000D_
_x000D_
_x000D_

Understanding the Gemfile.lock file

I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.

You'll find the following headings in a lockfile generated by Bundler 1.x:

GEM (optional but very common)

These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:

  • remote: one or more lines specifying the location of the Rubygems index(es)
  • specs: a list of dependencies, with their version number, and the constraints on any subdependencies

GIT (optional)

These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:

  • remote: the git remote. E.g., [email protected]:rails/rails
  • revision: the commit reference the Gemfile.lock is locked to
  • tag: (optional) the tag specified in the Gemfile
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PATH (optional)

These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:

  • remote: the path. E.g., plugins/vendored-dependency
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PLATFORMS

The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).

DEPENDENCIES

A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there.

Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).

RUBY VERSION (optional)

The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).

BUNDLED WITH (Bundler >= v1.10.x)

The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.

PLUGIN SOURCE (optional and very rare)

In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!


  1. https://dependabot.com
  2. https://github.com/bundler/bundler/issues/4631
  3. http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/

Detecting scroll direction

  1. Initialize an oldValue
  2. Get the newValue by listening to the event
  3. Subtract the two
  4. Conclude from the result
  5. Update oldValue with the newValue

// Initialization

let oldValue = 0;

//Listening on the event

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

To prevent this, make sure every BEGIN TRANSACTION has COMMIT

The following will say successful but will leave uncommitted transactions:

BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT

Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.

Triggering change detection manually in Angular

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

Capitalize only first character of string and leave others alone? (Rails)

Edit 2

I can't seem to replicate your trouble. Go ahead and run this native Ruby script. It generates the exact output your looking for, and Rails supports all of these methods. What sort of inputs are you having trouble with?

#!/usr/bin/ruby
def fixlistname(title)
  title = title.lstrip
  title += '...' unless title =~ /\.{3}$/
  title[0] = title[0].capitalize
  raise 'Title must start with "You know you..."' unless title =~ /^You know you/
  title
end

DATA.each do |title|
  puts fixlistname(title)
end

__END__
you know you something WITH dots ...
you know you something WITHOUT the dots
  you know you something with LEADING whitespace...
  you know you something with whitespace BUT NO DOTS
this generates error because it doesn't start with you know you

output

You know you something WITH dots ...
You know you something WITHOUT the dots...
You know you something with LEADING whitespace...
You know you something with whitespace BUT NO DOTS...
RuntimeError: Title must start with "You know you..."

Edit

Based on your edit, you can try something like this.

def fixlistname!
  self.title = title.lstrip
  self.title += '...' unless title.ends_with?('...')
  self.title[0] = title[0].capitalize
  errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end

Original

This will do the trick

s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York

When trying to use String#capitalize on the whole string, you were seeing I'm from new york because the method:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

How to resolve "Server Error in '/' Application" error?

You may get this error when trying to browse an ASP.NET application.

The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."

However, this error occurs primarily out of two scenarios.

  1. When you create an new web application using Visual Studio .NET, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

  1. When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly, we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).

jQuery if statement, syntax

It depends on what you mean by stop. If it's in a function that can return void then:

if(a && b) {
    // do something
}else{
    // "stop"
    return;
}

Read .doc file with python

Prerequisites :

install antiword : sudo apt-get install antiword

install docx : pip install docx

from subprocess import Popen, PIPE

from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
    cmd = ['antiword', file_path]
    p = Popen(cmd, stdout=PIPE)
    stdout, stderr = p.communicate()
    return stdout.decode('ascii', 'ignore')

print document_to_text('your_file_name','your_file_path')

Notice – New versions of python-docx removed this function. Make sure to pip install docx and not the new python-docx

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

Is there a way to collapse all code blocks in Eclipse?

There is a hotkey, mapped by default to Ctrl+Shift+NUM_KEYPAD_DIVIDE.

You can change it to something else via Window -> Preferences, search for "Keys", then for "Collapse All".

To open all code blocks the shortcut is Ctrl+Shift+NUM_KEYPAD_MULTIPLY.

In the Eclipse extension PyDev, close all code blocks is Ctrl + 9

To open all blocks, is Ctrl + 0

Cannot connect to Database server (mysql workbench)

My problem was that the MySQL server wasn't actually installed. I had run the MySQL Installer, but it didn't install the MySQL server.

I reran the installer, click "Add", and then added MySQL server to the list. Now it works fine.

How do you round UP a number in Python?

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Possible Duplicate Question

<@include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.

  • Only one servlet is executed at run time.
  • Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
  • The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
  • One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
  • A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.

<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.

  • Each included page is executed as a separate servlet at run time.
  • Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
  • The values of scriptlet variables need to be explicitly passed to the include page.
  • The included page must be able to be run on its own.
  • You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.

Depending on your needs, you may either use <@include> or <jsp:include>

nodemon not found in npm

for linux try

sudo npm install -g nodemon

for windows open powershell or cmd as administration

npm install -g nodemon

What is the difference between T(n) and O(n)?

one is Big "O"

one is Big Theta

http://en.wikipedia.org/wiki/Big_O_notation

Big O means your algorithm will execute in no more steps than in given expression(n^2)

Big Omega means your algorithm will execute in no fewer steps than in the given expression(n^2)

When both condition are true for the same expression, you can use the big theta notation....

Encoding as Base64 in Java

To convert this, you need an encoder & decoder which you will get from Base64Coder - an open-source Base64 encoder/decoder in Java. It is file Base64Coder.java you will need.

Now to access this class as per your requirement you will need the class below:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64 {

    public static void main(String args[]) throws IOException {
        /*
         * if (args.length != 2) {
         *     System.out.println(
         *         "Command line parameters: inputFileName outputFileName");
         *     System.exit(9);
         * } encodeFile(args[0], args[1]);
         */
        File sourceImage = new File("back3.png");
        File sourceImage64 = new File("back3.txt");
        File destImage = new File("back4.png");
        encodeFile(sourceImage, sourceImage64);
        decodeFile(sourceImage64, destImage);
    }

    private static void encodeFile(File inputFile, File outputFile) throws IOException {
        BufferedInputStream in = null;
        BufferedWriter out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(inputFile));
            out = new BufferedWriter(new FileWriter(outputFile));
            encodeStream(in, out);
            out.flush();
        }
        finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    private static void encodeStream(InputStream in, BufferedWriter out) throws IOException {
        int lineLength = 72;
        byte[] buf = new byte[lineLength / 4 * 3];
        while (true) {
            int len = in.read(buf);
            if (len <= 0)
                break;
            out.write(Base64Coder.encode(buf, 0, len));
            out.newLine();
        }
    }

    static String encodeArray(byte[] in) throws IOException {
        StringBuffer out = new StringBuffer();
        out.append(Base64Coder.encode(in, 0, in.length));
        return out.toString();
    }

    static byte[] decodeArray(String in) throws IOException {
        byte[] buf = Base64Coder.decodeLines(in);
        return buf;
    }

    private static void decodeFile(File inputFile, File outputFile) throws IOException {
        BufferedReader in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedReader(new FileReader(inputFile));
            out = new BufferedOutputStream(new FileOutputStream(outputFile));
            decodeStream(in, out);
            out.flush();
        }
        finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    private static void decodeStream(BufferedReader in, OutputStream out) throws IOException {
        while (true) {
            String s = in.readLine();
            if (s == null)
                break;
            byte[] buf = Base64Coder.decodeLines(s);
            out.write(buf);
        }
    }
}

In Android you can convert your bitmap to Base64 for Uploading to a server or web service.

Bitmap bmImage = //Data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
String encodedImage = Base64.encodeArray(imageData);

This “encodedImage” is text representation of your image. You can use this for either uploading purpose or for diplaying directly into an HTML page as below (reference):

<img alt="" src="data:image/png;base64,<?php echo $encodedImage; ?>" width="100px" />
<img alt="" src="data:image/png;base64,/9j/4AAQ...........1f/9k=" width="100px" />

Documentation: http://dwij.co.in/java-base64-image-encoder

Default argument values in JavaScript functions

I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:

 function(a, b) {
      if (typeof a == "undefined") {
        a = 10;
      }

      if (typeof b == "undefined") {
        a = 20;
      }

      alert("a: " + a + " b: " + b);
    }

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Get specific object by id from array of objects in AngularJS

If you want the list of items like city on the basis of state id then use

var state_Id = 5;
var items = ($filter('filter')(citylist, {stateId: state_Id }));

Resize image in the wiki of GitHub using Markdown

GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:

Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.

http://kramdown.gettalong.org/syntax.html#images

I haven't tested it on GitHub wiki though.

Classes cannot be accessed from outside package

Let me guess

Your initial declaration of class PUBLICClass was not public, then you made it `Public', can you try to clean and rebuild your project ?

Search in lists of lists by given index

I think using nested list comprehensions is the most elegant way to solve this, because the intermediate result is the position where the element is. An implementation would be:

list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'c'
any([ (list.index(x),x.index(y)) for x in list for y in x if y == search ] )

How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

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

What is Activity.finish() method doing exactly?

When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

What does set -e mean in a bash script?

I found this post while trying to figure out what the exit status was for a script that was aborted due to a set -e. The answer didn't appear obvious to me; hence this answer. Basically, set -e aborts the execution of a command (e.g. a shell script) and returns the exit status code of the command that failed (i.e. the inner script, not the outer script).

For example, suppose I have the shell script outer-test.sh:

#!/bin/sh
set -e
./inner-test.sh
exit 62;

The code for inner-test.sh is:

#!/bin/sh
exit 26;

When I run outer-script.sh from the command line, my outer script terminates with the exit code of the inner script:

$ ./outer-test.sh
$ echo $?
26

Google Authenticator available as a public service?

Not LAMP but if you use C# this is the code I use:

Code originally from:

https://github.com/kspearrin/Otp.NET

The Base32Encoding class is from this answer:

https://stackoverflow.com/a/7135008/3850405

Example program:

class Program
{
    static void Main(string[] args)
    {
        var bytes = Base32Encoding.ToBytes("JBSWY3DPEHPK3PXP");

        var totp = new Totp(bytes);

        var result = totp.ComputeTotp();
        var remainingTime = totp.RemainingSeconds();
    }
}

Totp:

public class Totp
{
    const long unixEpochTicks = 621355968000000000L;

    const long ticksToSeconds = 10000000L;

    private const int step = 30;

    private const int totpSize = 6;

    private byte[] key;

    public Totp(byte[] secretKey)
    {
        key = secretKey;
    }

    public string ComputeTotp()
    {
        var window = CalculateTimeStepFromTimestamp(DateTime.UtcNow);

        var data = GetBigEndianBytes(window);

        var hmac = new HMACSHA1();
        hmac.Key = key;
        var hmacComputedHash = hmac.ComputeHash(data);

        int offset = hmacComputedHash[hmacComputedHash.Length - 1] & 0x0F;
        var otp = (hmacComputedHash[offset] & 0x7f) << 24
               | (hmacComputedHash[offset + 1] & 0xff) << 16
               | (hmacComputedHash[offset + 2] & 0xff) << 8
               | (hmacComputedHash[offset + 3] & 0xff) % 1000000;

        var result = Digits(otp, totpSize);

        return result;
    }

    public int RemainingSeconds()
    {
        return step - (int)(((DateTime.UtcNow.Ticks - unixEpochTicks) / ticksToSeconds) % step);
    }

    private byte[] GetBigEndianBytes(long input)
    {
        // Since .net uses little endian numbers, we need to reverse the byte order to get big endian.
        var data = BitConverter.GetBytes(input);
        Array.Reverse(data);
        return data;
    }

    private long CalculateTimeStepFromTimestamp(DateTime timestamp)
    {
        var unixTimestamp = (timestamp.Ticks - unixEpochTicks) / ticksToSeconds;
        var window = unixTimestamp / (long)step;
        return window;
    }

    private string Digits(long input, int digitCount)
    {
        var truncatedValue = ((int)input % (int)Math.Pow(10, digitCount));
        return truncatedValue.ToString().PadLeft(digitCount, '0');
    }

}

Base32Encoding:

public static class Base32Encoding
{
    public static byte[] ToBytes(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ArgumentNullException("input");
        }

        input = input.TrimEnd('='); //remove padding characters
        int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
        byte[] returnArray = new byte[byteCount];

        byte curByte = 0, bitsRemaining = 8;
        int mask = 0, arrayIndex = 0;

        foreach (char c in input)
        {
            int cValue = CharToValue(c);

            if (bitsRemaining > 5)
            {
                mask = cValue << (bitsRemaining - 5);
                curByte = (byte)(curByte | mask);
                bitsRemaining -= 5;
            }
            else
            {
                mask = cValue >> (5 - bitsRemaining);
                curByte = (byte)(curByte | mask);
                returnArray[arrayIndex++] = curByte;
                curByte = (byte)(cValue << (3 + bitsRemaining));
                bitsRemaining += 3;
            }
        }

        //if we didn't end with a full byte
        if (arrayIndex != byteCount)
        {
            returnArray[arrayIndex] = curByte;
        }

        return returnArray;
    }

    public static string ToString(byte[] input)
    {
        if (input == null || input.Length == 0)
        {
            throw new ArgumentNullException("input");
        }

        int charCount = (int)Math.Ceiling(input.Length / 5d) * 8;
        char[] returnArray = new char[charCount];

        byte nextChar = 0, bitsRemaining = 5;
        int arrayIndex = 0;

        foreach (byte b in input)
        {
            nextChar = (byte)(nextChar | (b >> (8 - bitsRemaining)));
            returnArray[arrayIndex++] = ValueToChar(nextChar);

            if (bitsRemaining < 4)
            {
                nextChar = (byte)((b >> (3 - bitsRemaining)) & 31);
                returnArray[arrayIndex++] = ValueToChar(nextChar);
                bitsRemaining += 5;
            }

            bitsRemaining -= 3;
            nextChar = (byte)((b << bitsRemaining) & 31);
        }

        //if we didn't end with a full char
        if (arrayIndex != charCount)
        {
            returnArray[arrayIndex++] = ValueToChar(nextChar);
            while (arrayIndex != charCount) returnArray[arrayIndex++] = '='; //padding
        }

        return new string(returnArray);
    }

    private static int CharToValue(char c)
    {
        int value = (int)c;

        //65-90 == uppercase letters
        if (value < 91 && value > 64)
        {
            return value - 65;
        }
        //50-55 == numbers 2-7
        if (value < 56 && value > 49)
        {
            return value - 24;
        }
        //97-122 == lowercase letters
        if (value < 123 && value > 96)
        {
            return value - 97;
        }

        throw new ArgumentException("Character is not a Base32 character.", "c");
    }

    private static char ValueToChar(byte b)
    {
        if (b < 26)
        {
            return (char)(b + 65);
        }

        if (b < 32)
        {
            return (char)(b + 24);
        }

        throw new ArgumentException("Byte is not a value Base32 value.", "b");
    }

}

Trim string in JavaScript?

For IE9+ and other browsers

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

Node.js client for a socket.io server

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

How to initialize an array in Kotlin with values?

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

But In Kotlin an array initialized many way such as:

Any generic type of array you can use arrayOf() function :

val arr = arrayOf(10, 20, 30, 40, 50)

val genericArray = arrayOf(10, "Stack", 30.00, 40, "Fifty")

Using utility functions of Kotlin an array can be initialized

val intArray = intArrayOf(10, 20, 30, 40, 50)

How do I set the time zone of MySQL?

Set MYSQL timezone on server by logging to mysql server there set timezone value as required. For IST

SET SESSION time_zone = '+5:30';

Then run SELECT NOW();

Get time in milliseconds using C#

long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

This is actually how the various Unix conversion methods are implemented in the DateTimeOffset class (.NET Framework 4.6+, .NET Standard 1.3+):

long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

Do subclasses inherit private fields?

No, private fields are not inherited. The only reason is that subclass can not access them directly.

Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

What is PostgreSQL equivalent of SYSDATE from Oracle?

SYSDATE is an Oracle only function.

The ANSI standard defines current_date or current_timestamp which is supported by Postgres and documented in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

(Btw: Oracle supports CURRENT_TIMESTAMP as well)

You should pay attention to the difference between current_timestamp, statement_timestamp() and clock_timestamp() (which is explained in the manual, see the above link)


This statement:

select up_time from exam where up_time like sysdate

Does not make any sense at all. Neither in Oracle nor in Postgres. If you want to get rows from "today", you need something like:

select up_time 
from exam 
where up_time = current_date

Note that in Oracle you would probably want trunc(up_time) = trunc(sysdate) to get rid of the time part that is always included in Oracle.

Set margins in a LinearLayout programmatically

Due to variation in device screen pixel densities its good to always use DIP unit to set margin programmatically. Like below_

//get resources
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

//get layout params...
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.setMargins(Math.round(pxLeftMargin), Math.round(pxTopMargin), Math.round(pxRightMargin), Math.round(pxBottomMargin));

//set margin...
yourLayoutTOsetMargin.setLayoutParams(params); 

Hope this will help.

HTML to PDF with Node.js

In addition to @Jozzhart Answer, you can make a local html; serve it with express; and use phantom to make PDF from it; something like this:

const exp = require('express');
const app = exp();
const pth = require("path");
const phantom = require('phantom');
const ip = require("ip");

const PORT = 3000;
const PDF_SOURCE = "index"; //index.html
const PDF_OUTPUT = "out"; //out.pdf

const source = pth.join(__dirname, "", `${PDF_SOURCE}.html`);
const output = pth.join(__dirname, "", `${PDF_OUTPUT}.pdf`);

app.use("/" + PDF_SOURCE, exp.static(source));
app.use("/" + PDF_OUTPUT, exp.static(output));

app.listen(PORT);

let makePDF = async (fn) => {
    let local = `http://${ip.address()}:${PORT}/${PDF_SOURCE}`;
    phantom.create().then((ph) => {
        ph.createPage().then((page) => {
            page.open(local).then(() =>
                page.render(output).then(() => { ph.exit(); fn() })
            );
        });
    });
}

makePDF(() => {
    console.log("PDF Created From Local File");
    console.log("PDF is downloadable from link:");
    console.log(`http://${ip.address()}:${PORT}/${PDF_OUTPUT}`);
});

and index.html can be anything:

<h1>PDF HEAD</h1>
<a href="#">LINK</a>

result:

enter image description here

Strange "java.lang.NoClassDefFoundError" in Eclipse

As mentioned above, "java.lang.ClassNotFoundException means CLASSPATH issues."

In my setup, I am running Maven to build (instead of Ant) and using Eclipse (instead of Netbeans).

Usually, to build and setup the project, I will run 'mvn clean', 'mvn compile', 'mvn eclipse:eclipse' from the Windows command prompt. The last command 'mvn eclipse:eclipse' updates the project configuration creating .classpath and .project files.

To fix the problem, I deleted the two files (.classpath and .project) then re-ran the three commands.

So depending on your configuration, try to find the classpath/project files (make a backup) and delete them. You can also try deleting the target/release/build folder (whatever is created from the build command) as well. Then try to build/package/configure your project again.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The basic premise of the question and the answers are wrong. Every Select in a union can have a where clause. It's the ORDER BY in the first query that's giving yo the error.

How to get the screen width and height in iOS?

How can one get the dimensions of the screen in iOS?

The problem with the code that you posted is that you're counting on the view size to match that of the screen, and as you've seen that's not always the case. If you need the screen size, you should look at the object that represents the screen itself, like this:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

Update for split view: In comments, Dmitry asked:

How can I get the size of the screen in the split view?

The code given above reports the size of the screen, even in split screen mode. When you use split screen mode, your app's window changes. If the code above doesn't give you the information you expect, then like the OP, you're looking at the wrong object. In this case, though, you should look at the window instead of the screen, like this:

CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;

Swift 4.2

let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height

// split screen            
let windowRect = self.view.window?.frame
let windowWidth = windowRect?.size.width
let windowHeight = windowRect?.size.height

How to clear/remove observable bindings in Knockout.js?

Have you thought about this:

try {
    ko.applyBindings(PersonListViewModel);
}
catch (err) {
    console.log(err.message);
}

I came up with this because in Knockout, i found this code

    var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
    if (!sourceBindings) {
        if (alreadyBound) {
            throw Error("You cannot apply bindings multiple times to the same element.");
        }
        ko.utils.domData.set(node, boundElementDomDataKey, true);
    }

So to me its not really an issue that its already bound, its that the error was not caught and dealt with...

How to add a line to a multiline TextBox?

Above methods did not work for me. I got the following exception:

Exception : 'System.InvalidOperationException' in System.Windows.Forms.dll

Turns out I needed to call Invoke on my controls first. See answer here.

base_url() function not working in codeigniter

Question -I wanted to load my css file but it was not working even though i autoload and manual laod why ? i found the solution => here is my solution : application>config>config.php $config['base_url'] = 'http://localhost/CodeIgniter/'; //paste the link to base url

question explanation:

" > i had my bootstrap.min.css file inside assets/css folder where assets is root directory which i was created.But it was not working even though when i loaded ? 1. $autoload['helper'] = array('url'); 2. $this->load->helper('url'); in my controllar then i go to my

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

Javascript callback when IFRAME is finished loading?

I've had exactly the same problem in the past and the only way I found to fix it was to add the callback into the iframe page. Of course that only works when you have control over the iframe content.

How to set a background image in Xcode using swift?

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

Access an arbitrary element in a dictionary in Python

Subclassing dict is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]], otherwise access the dictionary as expected:

class mydict(dict):
    def __getitem__(self, value):
        if isinstance(value, int):
            return self.get(list(self)[value])
        else:
            return self.get(value)

d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
            'e': 'test', 'f': 'dictionary', 'g': 'testing'})

d[0]    # 'hello'
d[1]    # 'this'
d['c']  # 'is'