Programs & Examples On #Citations

Compiling LaTex bib source

You need to compile the bibtex file.

Suppose you have article.tex and article.bib. You need to run:

  • latex article.tex (this will generate a document with question marks in place of unknown references)
  • bibtex article (this will parse all the .bib files that were included in the article and generate metainformation regarding references)
  • latex article.tex (this will generate document with all the references in the correct places)
  • latex article.tex (just in case if adding references broke page numbering somewhere)

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

Download files in laravel using Response::download

While using laravel 5 use this code as you don`t need headers.

return response()->download($pathToFile); .

If you are using Fileentry you can use below function for downloading.

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    $pathToFile=storage_path()."/app/".$entry->filename;
    return response()->download($pathToFile);           
}

CALL command vs. START with /WAIT option

There is a useful difference between call and start /wait when calling regsvr32.exe /s for example, also referenced by Gary in in his answer to how-do-i-get-the-application-exit-code-from-a-windows-command-line

call regsvr32.exe /s broken.dll
echo %errorlevel%

will always return 0 but

start /wait regsvr32.exe /s broken.dll
echo %errorlevel%

will return the error level from regsvr32.exe

How to check if an int is a null

An int is not null, it may be 0 if not initialized.

If you want an integer to be able to be null, you need to use Integer instead of int.

Integer id;
String name;

public Integer getId() { return id; }

Besides the statement if(person.equals(null)) can't be true, because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)

Convert a positive number to negative in C#

int myInt = - System.Math.Abs(-5);

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

How do you do a ‘Pause’ with PowerShell 2.0?

You may want to use FlushInputBuffer to discard any characters mistakenly typed into the console, especially for long running operations, before using ReadKey:

Write-Host -NoNewLine 'Press any key to continue...'
$Host.UI.RawUI.FlushInputBuffer()
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') | Out-Null

Entity Framework Timeouts

If you are using Entity Framework like me, you should define Time out on Startup class as follows:

 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), o => o.CommandTimeout(180)));

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

PHP: Best way to check if input is a valid number?

I use

if(is_numeric($value) && $value > 0 && $value == round($value, 0)){

to validate if a value is numeric, positive and integral

http://php.net/is_numeric

I don't really like ctype_digit as its not as readable as "is_numeric" and actually has less flaws when you really want to validate that a value is numeric.

Format bytes to kilobytes, megabytes, gigabytes

I know it's maybe a little late to answer this question but, more data is not going to kill someone. Here's a very fast function :

function format_filesize($B, $D=2){
    $S = 'BkMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F].'B';
}

EDIT: I updated my post to include the fix proposed by camomileCase:

function format_filesize($B, $D=2){
    $S = 'kMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F-1].'B';
}

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Easy way to write contents of a Java InputStream to an OutputStream

I use BufferedInputStream and BufferedOutputStream to remove the buffering semantics from the code

try (OutputStream out = new BufferedOutputStream(...);
     InputStream in   = new BufferedInputStream(...))) {
  int ch;
  while ((ch = in.read()) != -1) {
    out.write(ch);
  }
}

Replace negative values in an numpy array

And yet another possibility:

In [2]: a = array([1, 2, 3, -4, 5])

In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])

Wrap a text within only two lines inside div

I believe the CSS-only solution text-overflow: ellipsis applies to one line only, so you won't be able to go this route:

.yourdiv {

    line-height: 1.5em; /* Sets line height to 1.5 times text size */
    height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
    width: 100%; /* Use whatever width you want */
    white-space: normal; /* Wrap lines of text */
    overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
    text-overflow: ellipsis; /* Ellipses (cross-browser) */
    -o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}

Have you tried http://tpgblog.com/threedots/ for jQuery?

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case i simply removed CFBundleIcons~ipad key from the info.plist file which was blocking the use of AppIcon set for iPad.

The target of my project was iPhone and IOS 8. XCode version was 6.3. Setting CFBundleIcons~ipad probably come from an early version of XCode.

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

How can I get the active screen dimensions?

Add on to ffpf

Screen.FromControl(this).Bounds

HTML CSS Button Positioning

[type=submit]{
    margin-left: 121px;
    margin-top: 19px;
    width: 84px;
    height: 40px;   
    font-size:14px;
    font-weight:700;
}

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

Android Linear Layout - How to Keep Element At Bottom Of View?

Update: I still get upvotes on this question, which is still the accepted answer and which I think I answered poorly. In the spirit of making sure the best info is out there, I have decided to update this answer.

In modern Android I would use ConstraintLayout to do this. It is more performant and straightforward.

<ConstraintLayout>
   <View
      android:id="@+id/view1"
      ...other attributes elided... />
   <View
      android:id="@id/view2"        
      app:layout_constraintTop_toBottomOf="@id/view1" />
      ...other attributes elided... />

   ...etc for other views that should be aligned top to bottom...

   <TextView
    app:layout_constraintBottom_toBottomOf="parent" />

If you don't want to use a ConstraintLayout, using a LinearLayout with an expanding view is a straightforward and great way to handle taking up the extra space (see the answer by @Matthew Wills). If you don't want to expand the background of any of the Views above the bottom view, you can add an invisible View to take up the space.

The answer I originally gave works but is inefficient. Inefficiency may not be a big deal for a single top level layout, but it would be a terrible implementation in a ListView or RecyclerView, and there just isn't any reason to do it since there are better ways to do it that are roughly the same level of effort and complexity if not simpler.

Take the TextView out of the LinearLayout, then put the LinearLayout and the TextView inside a RelativeLayout. Add the attribute android:layout_alignParentBottom="true" to the TextView. With all the namespace and other attributes except for the above attribute elided:

<RelativeLayout>
  <LinearLayout>
    <!-- All your other elements in here -->
  </LinearLayout>
  <TextView
    android:layout_alignParentBottom="true" />
</RelativeLayout>

convert datetime to date format dd/mm/yyyy

DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:

 date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');

How to create and use resources in .NET

The above method works good.

Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.

To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).

To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

Import mysql DB with XAMPP in command LINE

here is my try to import database from cmd in xampp server the correct command for me is this you can change it with your requirements.and i also attached Errors that i face first time importing db from command line.you can see last command that i use and i paste it here also its working fro me.

mysql -h localhost -u root ovxsolut_windhs < C:\Users\eee\Downloads\ovxsolut_windhs.sql

d enter image description here

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.

Get current value when change select option - Angular2

In angular 4, this worked for me

template.html

<select (change)="filterChanged($event.target.value)">
  <option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
  </option>
</select>

component.ts

export class FilterComponent implements OnInit {

selectedFilter:string;
   public filterTypes = [
     { value: 'percentage', display: 'percentage' },
     { value: 'amount', display: 'amount' }
  ];

   constructor() { 
     this.selectedFilter = 'percentage';
   }

   filterChanged(selectedValue:string){
     console.log('value is ', selectedValue);
   }

  ngOnInit() {
  }
}

How to edit .csproj file

in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File" enter image description here

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

Java compiler level does not match the version of the installed Java project facet

TK Gospodinov answer is correct even for maven projects. Beware: I do use Maven. The pom was correct and still got this issue. I went to "Project Facets" and actually removed the Java selection which was pointing to 1.6 but my project is using 1.7. On the right in the "Runtimes" tab I had to check the jdk1.7 option. Nothing appeared on the left even after I hit "Apply". The issue went away though which is why I still think this answer is important of the specific "Project Facets" related issue. After you hit OK if you come back to "Project Facets" you will notice Java shows up as version 1.7 so you can now select it to make sure the project is "marked" as a Java project. I also needed to right click on the project and select Maven|Update Project.

Adding a JAR to an Eclipse Java library

As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.

Implement an input with a mask

A solution that responds to the input event instead of key events (like keyup) will give a smooth experience (no wiggles), and also works when changes are made without the keyboard (context menu, mouse drag, other device...).

The code below will look for input elements that have both a placeholder attribute and a data-slots attribute. The latter should define the character(s) in the placeholder that is/are intended as input slot, for example, "_". An optional data-accept attribute can be provided with a regular expression that defines which characters are allowed in such a slot. The default is \d, i.e. digits.

_x000D_
_x000D_
// This code empowers all input tags having a placeholder and data-slots attribute_x000D_
document.addEventListener('DOMContentLoaded', () => {_x000D_
    for (const el of document.querySelectorAll("[placeholder][data-slots]")) {_x000D_
        const pattern = el.getAttribute("placeholder"),_x000D_
            slots = new Set(el.dataset.slots || "_"),_x000D_
            prev = (j => Array.from(pattern, (c,i) => slots.has(c)? j=i+1: j))(0),_x000D_
            first = [...pattern].findIndex(c => slots.has(c)),_x000D_
            accept = new RegExp(el.dataset.accept || "\\d", "g"),_x000D_
            clean = input => {_x000D_
                input = input.match(accept) || [];_x000D_
                return Array.from(pattern, c =>_x000D_
                    input[0] === c || slots.has(c) ? input.shift() || c : c_x000D_
                );_x000D_
            },_x000D_
            format = () => {_x000D_
                const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {_x000D_
                    i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));_x000D_
                    return i<0? prev[prev.length-1]: back? prev[i-1] || first: i;_x000D_
                });_x000D_
                el.value = clean(el.value).join``;_x000D_
                el.setSelectionRange(i, j);_x000D_
                back = false;_x000D_
            };_x000D_
        let back = false;_x000D_
        el.addEventListener("keydown", (e) => back = e.key === "Backspace");_x000D_
        el.addEventListener("input", format);_x000D_
        el.addEventListener("focus", format);_x000D_
        el.addEventListener("blur", () => el.value === pattern && (el.value=""));_x000D_
    }_x000D_
});
_x000D_
[data-slots] { font-family: monospace }
_x000D_
<label>Date time: _x000D_
    <input placeholder="dd/mm/yyyy hh:mm" data-slots="dmyh">_x000D_
</label><br>_x000D_
<label>Telephone:_x000D_
    <input placeholder="+1 (___) ___-____" data-slots="_">_x000D_
</label><br>_x000D_
<label>MAC Address:_x000D_
    <input placeholder="XX:XX:XX:XX:XX:XX" data-slots="X" data-accept="[\dA-H]">_x000D_
</label><br>_x000D_
<label>Signed number (3 digits):_x000D_
    <input placeholder="±___" data-slots="±_" data-accept="^[+-]|(?!^)\d" size="4">_x000D_
</label><br>_x000D_
<label>Alphanumeric:_x000D_
    <input placeholder="__-__-__-____" data-slots="_" data-accept="\w" size="13">_x000D_
</label><br>
_x000D_
_x000D_
_x000D_

Combine Regexp?

If a string must not contain @, every character must be another character than @:

/^[^@]*$/

This will match any string of any length that does not contain @.

Another possible solution would be to invert the boolean result of /@/.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

How to render a PDF file in Android

There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.

build.Gradle

compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

dialog_pdf_viewer

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_pdf_viewer_close"
        style="@style/ExitButtonImageViewStyle"
        android:src="@drawable/popup_exit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"
        android:orientation="vertical">

        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <View style="@style/HorizontalLine" />

    <com.pozitron.commons.customviews.ButtonFont
        android:id="@+id/dialog_pdf_viewer_button"
        style="@style/ButtonPrimary2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/agreed" />

</LinearLayout>

DailogPDFViewer.java

public class DialogPdfViewer extends Dialog {
    PDFView pdfView;
    byte[] decodedString;

    public interface OnDialogPdfViewerListener {
        void onAgreeClick(DialogPdfViewer dialogFullEula);

        void onCloseClick(DialogPdfViewer dialogFullEula);
    }

    public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
        super(context);

        setContentView(R.layout.dialog_pdf_viewer);
        findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
            }
        });

        findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
            }
        });

        decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);

        pdfView = ((PDFView) findViewById(R.id.pdfView));
        pdfView.fromBytes(decodedString).load();

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
                return true;
            }
        });

    }
}

Trying to start a service on boot on Android

This is what I did

1. I made the Receiver class

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //whatever you want to do on boot
       Intent serviceIntent = new Intent(context, YourService.class);
       context.startService(serviceIntent);
    }
}

2.in the manifest

<manifest...>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application...>
        <receiver android:name=".BootReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    ...

3.and after ALL you NEED to "set" the receiver in your MainActivity, it may be inside the onCreate

...
 final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootReceiver.class.getName());
        if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
        getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
...

the final steap I have learned from ApiDemos

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

How to get first and last day of the current week in JavaScript

_x000D_
_x000D_
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
_x000D_
_x000D_
_x000D_

I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.

if i remove .toUTCString(). output which i receive is not as expected

SSIS Excel Import Forcing Incorrect Column Type

;IMEX=1; is not always working... Everything about mixed datatypes in Excel: Mixed data types in Excel column

enter image description here

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

Which HTML elements can receive focus?

Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:

  a[href]:not([tabindex='-1']),
  area[href]:not([tabindex='-1']),
  input:not([disabled]):not([tabindex='-1']),
  select:not([disabled]):not([tabindex='-1']),
  textarea:not([disabled]):not([tabindex='-1']),
  button:not([disabled]):not([tabindex='-1']),
  iframe:not([tabindex='-1']),
  [tabindex]:not([tabindex='-1']),
  [contentEditable=true]:not([tabindex='-1'])
  {
      /* your CSS for focusable elements goes here */
  }

or a little more beautiful in SASS:

a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
    &:not([tabindex='-1'])
    {
        /* your SCSS for focusable elements goes here */
    }
}

I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.

EDIT: There is one more selector, which is focusable:

[contentEditable=true]

However, this is used very rarely.

Get Today's date in Java at midnight time

Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=>  " + dateNow);

What is the reason for having '//' in Python?

// can be considered an alias to math.floor() for divisions with return value of type float. It operates as no-op for divisions with return value of type int.

import math
# let's examine `float` returns
# -------------------------------------
# divide
>>> 1.0 / 2
0.5
# divide and round down
>>> math.floor(1.0/2)
0.0
# divide and round down
>>> 1.0 // 2
0.0

# now let's examine `integer` returns
# -------------------------------------
>>> 1/2
0
>>> 1//2
0

Setting the value of checkbox to true or false with jQuery

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

--

$('#vehicleChkBox').change(function(){
    if(this.checked)
        $('#vehicleChkBox').val('TRUE');
   else
        $('#vehicleChkBox').val('False');
});

Hibernate Criteria Restrictions AND / OR combination

think works

Criteria criteria = getSession().createCriteria(clazz); 
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"), 
           Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), 
           Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));

Null pointer Exception on .setOnClickListener

Try giving your Button in your main.xml a more descriptive name such as:

<Button
                android:id="@+id/buttonXYZ"

(use lowercase in your xml files, at least, the first letter)

And then in your MainActivity class, declare it as:

Button buttonXYZ;

In your onCreate(Bundle savedInstanceState) method, define it as:

buttonXYZ = (Button) findViewById(R.id.buttonXYZ);

Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.

Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

Why doesn't list have safe "get" method like dictionary?

This guy worked for me:

list_get = lambda l, x: l[x:x+1] and l[x] or 0

lambdas are great for one liner helper functions like this

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

How to loop through all enum values in C#?

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    ...
}

Work with a time span in Javascript

a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat

some formatting examples

/** delta: 1234567890, @locale: 'en-US', @style: 'long' */

/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds

/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890

/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms

/* D,h:m:s.f */
14,06:56:07.890

/* D~, h:m:s.f */
14 days, 06:56:07.890

/* h~ m~ s~ */
342 hours 56 minutes 7 seconds

/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days

/* up D~, h:m */
up 14 days, 06:56

the code & test

_x000D_
_x000D_
/**
    Init locale formatter:
    
        timespan.locale(@locale, @style)
    
    Example:

        timespan.locale('en-US', 'long');
        timespan.locale('es', 'narrow');

    Format time delta:
    
        timespan.format(@pattern, @milliseconds)

        @pattern tokens:
            D: days, h: hours, m: minutes, s: seconds, f: millis

        @pattern token extension:
            h  => '0'-padded value, 
            h# => raw value,
            h~ => locale formatted value

    Example:

        timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
        
        output: 14 days 6 hours 56 minutes 7 seconds 890 millis

    NOTES:

    * milliseconds unit have no locale translation
    * may encounter declension issues for some locales
    * use quoted text for raw inserts
            
*/

const timespan = (() => {
    let rtf, tokensRtf;
    const
    tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
    map = [
        {t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
        {t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
        {t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
        {t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
        {t: [['f', 3], ['f#'], ['f~']], u: 1}
    ],
    locale = (value, style = 'long') => {
        try {
            rtf = new Intl.RelativeTimeFormat(value, {style});
        } catch (e) {
            if (rtf) throw e;
            return;
        }
        const h = rtf.format(1, 'hour').split(' ');
        tokensRtf = new Set(rtf.format(1, 'day').split(' ')
            .filter(t => t != 1 && h.indexOf(t) > -1));
        return true;
    },
    fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
    mapper = {
        number: (t, u) => (u + '').padStart(t.fmt, '0'),
        string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
            .filter(t => !tokensRtf.has(t)).join(' ')
            .trim().replace(/[+-]/g, '') : fallback(t, u),
    },
    replace = (out, t) => out[t] || t.slice(1, t.length - 1),
    format = (pattern, value) => {
        if (typeof pattern !== 'string')
            throw Error('invalid pattern');
        if (!Number.isFinite(value))
            throw Error('invalid value');
        if (!pattern)
            return '';
        const out = {};
        value = Math.abs(value);
        pattern.match(tokens)?.forEach(t => out[t] = null);
        map.forEach(m => {
            let u = null;
            m.t.forEach(t => {
                if (out[t.token] !== null)
                    return;
                if (u === null) {
                    u = Math.floor(value / m.u);
                    value %= m.u;
                }
                out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
            })
        });
        return pattern.replace(tokens, replace.bind(null, out));
    };
    map.forEach(m => m.t = m.t.map(t => ({
        token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
    })));
    locale('en');
    return {format, locale};
})();


/************************** test below *************************/

const
cfg = {
  locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
  style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
  try {
      const tv = new Date(td.value);
      if (isNaN(tv)) throw Error('invalid "datetime2" value');
      timespan.locale(loc.value || locale.value, style.value);
      const delta = fd.getTime() - tv.getTime();
      out.innerHTML = timespan.format(fmt.value, delta);
  } catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
  const elm = el(id);
  value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
_x000D_
_x000D_

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

jQuery issue in Internet Explorer 8

If you are using HTTPS on your site, you will need to load the jQuery library from Googles https server instead. Try this: https://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js (or the latest https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js)

Disabling tab focus on form elements

$('.tabDisable').on('keydown', function(e)
{ 
  if (e.keyCode == 9)  
  {
    e.preventDefault();
  }
});

Put .tabDisable to all tab disable DIVs Like

<div class='tabDisable'>First Div</div> <!-- Tab Disable Div -->
<div >Second Div</div> <!-- No Tab Disable Div -->
<div class='tabDisable'>Third Div</div> <!-- Tab Disable Div -->

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

How to check if IEnumerable is null or empty?

if (collection?.Any() == true){
    // if collection contains more than one item
}
if (collection?.Any() != true){
    // if collection is null
    // if collection does not contain any item
}

Pointer to a string in C?

The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.

Using the passwd command from within a shell script

Tested this on a CentOS VMWare image that I keep around for this sort of thing. Note that you probably want to avoid putting passwords as command-line arguments, because anybody on the entire machine can read them out of 'ps -ef'.

That said, this will work:

user="$1"
password="$2"
adduser $user
echo $password | passwd --stdin $user

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlTest"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />
</Window>

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

Unix shell script find out which directory the script file resides?

In Bash, you should get what you need like this:

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

How do I ignore all files in a folder with a Git repository in Sourcetree?

In Sourcetree: Just ignore a file in specified folder. Sourcetree will ask if you like to ignore all files in that folder. It's perfect!

How do I call an Angular.js filter with multiple arguments?

If you need two or more dealings with the filter, is possible to chain them:

{{ value | decimalRound: 2 | currencySimbol: 'U$' }} 
// 11.1111 becomes U$ 11.11

Connecting to TCP Socket from browser using javascript

ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s schematic diagram

enter image description here

code sample:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

ReactJS: Warning: setState(...): Cannot update during an existing state transition

The problem is certainly the this binding while rending the button with onClick handler. The solution is to use arrow function while calling action handler while rendering. Like this: onClick={ () => this.handleButtonChange(false) }

Create timestamp variable in bash script

You can use

timestamp=`date --rfc-3339=seconds`

This delivers in the format 2014-02-01 15:12:35-05:00

The back-tick (`) characters will cause what is between them to be evaluated and have the result included in the line. date --help has other options.

Making custom right-click context menus for my web-app

I know that this is rather old also. I recently had a need to create a context menu that I inject into other sites that have different properties based n the element clicked.

It's rather rough, and there are probable better ways to achieve this. It uses the jQuery Context menu Library Located Here

I enjoyed creating it and though that you guys might have some use out of it.

Here is the fiddle. I hope that it can hopefully help someone out there.

$(function() {
  function createSomeMenu() {
    var all_array = '{';
    var x = event.clientX,
      y = event.clientY,
      elementMouseIsOver = document.elementFromPoint(x, y);
    if (elementMouseIsOver.closest('a')) {
      all_array += '"Link-Fold": {"name": "Link", "icon": "fa-external-link", "items": {"fold2-key1": {"name": "Open Site in New Tab"}, "fold2-key2": {"name": "Open Site in Split Tab"}, "fold2-key3": {"name": "Copy URL"}}},';
    }
    if (elementMouseIsOver.closest('img')) {
      all_array += '"Image-Fold": {"name": "Image","icon": "fa-picture-o","items": {"fold1-key1": {"name":"Download Image"},"fold1-key2": {"name": "Copy Image Location"},"fold1-key3": {"name": "Go To Image"}}},';
    }
    all_array += '"copy": {"name": "Copy","icon": "copy"},"paste": {"name": "Paste","icon": "paste"},"edit": {"name": "Edit HTML","icon": "fa-code"}}';
    return JSON.parse(all_array);
  }

  // setup context menu
  $.contextMenu({
    selector: 'body',
    build: function($trigger, e) {
      return {
        callback: function(key, options) {
          var m = "clicked: " + key;
          console.log(m);
        },
        items: createSomeMenu()
      };
    }
  });
});

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

For Kotlin Users

You just need to add ? with Intent in onActivityResult as the data can be null if user cancels the transaction or anything goes wrong. So we need to define data as nullable in onActivityResult

Just replace onActivityResult signature of SampleActivity with below:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

Could not find main class HelloWorld

I have also faced same problem....

Actually this problem is raised due to the fact that your program .class files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.

If you observe carefully your .class file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))

jQuery hover and class selector

On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

C++ queue - simple example

std::queue<myclass*> that's it

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

How to get the Display Name Attribute of an Enum member via MVC Razor code?

If you are using MVC 5.1 or upper there is simplier and clearer way: just use data annotation (from System.ComponentModel.DataAnnotations namespace) like below:

public enum Color
{
    [Display(Name = "Dark red")]
    DarkRed,
    [Display(Name = "Very dark red")]
    VeryDarkRed,
    [Display(Name = "Red or just black?")]
    ReallyDarkRed
}

And in view, just put it into proper html helper:

@Html.EnumDropDownListFor(model => model.Color)

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

Best way to parseDouble with comma as decimal separator?

This would do the job:

Double.parseDouble(p.replace(',','.')); 

Iterate a list with indexes in Python

python enumerate function will be satisfied your requirements

result = list(enumerate([1,3,7,12]))
print result

output

[(0, 1), (1, 3), (2, 7),(3,12)]

Error Code: 2013. Lost connection to MySQL server during query

I know its old but on mac

1. Control-click your connection and choose Connection Properties.
2. Under Advanced tab, set the Socket Timeout (sec) to a larger value.

Listing all extras of an Intent

The get(String key) method of Bundle returns an Object. Your best bet is to spin over the key set calling get(String) on each key and using toString() on the Object to output them. This will work best for primitives, but you may run into issues with Objects that do not implement a toString().

Asynchronous vs synchronous execution, what does it really mean?

Synchronous basically means that you can only execute one thing at a time. Asynchronous means that you can execute multiple things at a time and you don't have to finish executing the current thing in order to move on to next one.

Javascript - Track mouse position

If just want to track the mouse movement visually:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
</head>_x000D_
<style type="text/css">_x000D_
* { margin: 0; padding: 0; }_x000D_
html, body { width: 100%; height: 100%; overflow: hidden; }_x000D_
</style>_x000D_
<body>_x000D_
<canvas></canvas>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var_x000D_
canvas    = document.querySelector('canvas'),_x000D_
ctx       = canvas.getContext('2d'),_x000D_
beginPath = false;_x000D_
_x000D_
canvas.width  = window.innerWidth;_x000D_
canvas.height = window.innerHeight;_x000D_
_x000D_
document.body.addEventListener('mousemove', function (event) {_x000D_
 var x = event.clientX, y = event.clientY;_x000D_
_x000D_
 if (beginPath) {_x000D_
  ctx.lineTo(x, y);_x000D_
  ctx.stroke();_x000D_
 } else {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(x, y);_x000D_
  beginPath = true;_x000D_
 }_x000D_
}, false);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

jQuery textbox change event

I have found that this works:

$(document).ready(function(){
    $('textarea').bind('input propertychange', function() {
        //do your update here
    }

})

how to redirect to home page

document.location.href="/";

or

 window.location.href = "/";

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/Window/#window-location

(Note: I copied the difference explanation above, from this question.)

How to solve "Fatal error: Class 'MySQLi' not found"?

Sounds like you just need to install MySQLi.

If you think you've done that and still have a problem, please post your operating system and anything else that might help diagnose it further.

findViewByID returns null

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

This would be wrong

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

This is correct

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

How to modify a text file?

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

This is an operating system thing, not a Python thing. It is the same in all languages.

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

How does JavaScript .prototype work?

prototype allows you to make classes. if you do not use prototype then it becomes a static.

Here is a short example.

var obj = new Object();
obj.test = function() { alert('Hello?'); };

In the above case, you have static funcation call test. This function can be accessed only by obj.test where you can imagine obj to be a class.

where as in the below code

function obj()
{
}

obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();

The obj has become a class which can now be instantiated. Multiple instances of obj can exist and they all have the test function.

The above is my understanding. I am making it a community wiki, so people can correct me if I am wrong.

Singleton design pattern vs Singleton beans in Spring container

A singleton bean in Spring and the singleton pattern are quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.

The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

Even though the default scope is singleton, you can change the scope of bean by specifying the scope attribute of <bean ../> element.

<bean id=".." class=".." scope="prototype" />

Exit a while loop in VBS/VBA

I know this is old as dirt but it ranked pretty high in google.

The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks

In the example given

num = 0
While num < 10
  If status = "Fail" Then
    num = 10
  End If
  num = num + 1
Wend

After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.

Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:

num = 0
While num < 10
  If folder = "System32" Then
    num = 10
  End If
  RecursiveDeleteFunction folder
  num = num + 1
Wend

Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

Symbolicating iPhone App Crash Reports

I had to do a lot of hacking of the symbolicatecrash script to get it to run properly.

As far as I can tell, symbolicatecrash right now requires the .app to be in the same directory as the .dsym. It will use the .dsym to locate the .app, but it won't use the dsym to find the symbols.

You should make a copy of your symbolicatecrash before attempting these patches which will make it look in the dsym:

Around line 212 in the getSymbolPathFor_dsymUuid function

212     my @executablePath = grep { -e && ! -d } glob("$dsymdir" . "/Contents/Resources/DWARF/" . $executable);

Around line 265 in the matchesUUID function

265             return 1;

Using GSON to parse a JSON array

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

Getting value from table cell in JavaScript...not jQuery

A few problems:

  • The loop conditional in your for statements is an assignment, not a loop check, so it might infinite loop

  • You should use the item() function on those rows/cells collections, not sure if array index works on those (not actually JS arrays)

  • You should declare the row/col objects to ensure their scope is correct.

Here is an updated example:

var refTab=document.getElementById("ddReferences") 
var  ttl; 
// Loop through all rows and columns of the table and popup alert with the value 
// /content of each cell. 
for ( var i = 0; i<refTab.rows.length; i++ ) { 
  var row = refTab.rows.item(i); 
  for ( var j = 0; j<row.cells.length; j++ ) { 
    var col = row.cells.item(j);
    alert(col.firstChild.innerText); 
  } 
}

Replace innerText with innerHTML if you want HTML, not the text contents.

How to make HTML element resizable using pure Javascript?

_x000D_
_x000D_
var resizeHandle = document.getElementById('resizable');_x000D_
var box = document.getElementById('resize');_x000D_
resizeHandle.addEventListener('mousedown', initialiseResize, false);_x000D_
_x000D_
function initialiseResize(e) {_x000D_
  window.addEventListener('mousemove', startResizing, false);_x000D_
  window.addEventListener('mouseup', stopResizing, false);_x000D_
}_x000D_
_x000D_
function stopResizing(e) {_x000D_
  window.removeEventListener('mousemove', startResizing, false);_x000D_
  window.removeEventListener('mouseup', stopResizing, false);_x000D_
}_x000D_
_x000D_
function startResizing(e) {_x000D_
  box.style.width = (e.clientX) + 'px';_x000D_
  box.style.height = (e.clientY) + 'px';_x000D_
}_x000D_
_x000D_
function startResizing(e) {_x000D_
  box.style.width = (e.clientX - box.offsetLeft) + 'px';_x000D_
  box.style.height = (e.clientY - box.offsetTop) + 'px';_x000D_
}
_x000D_
#resize {_x000D_
  position: relative;_x000D_
  width: 130px;_x000D_
  height: 130px;_x000D_
  border: 2px solid blue;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#resizable {_x000D_
  background-color: white;_x000D_
  width: 10px;_x000D_
  height: 10px;_x000D_
  cursor: se-resize;_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}
_x000D_
<div id="resize">_x000D_
_x000D_
  <div id="resizable">_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Installing Python 3 on RHEL

Use the SCL repos.

sudo sh -c 'wget -qO- http://people.redhat.com/bkabrda/scl_python33.repo >> /etc/yum.repos.d/scl.repo'
sudo yum install python33
scl enable python27

(This last command will have to be run each time you want to use python27 rather than the system default.)

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

After reading almost every single line here and testing the various solutions, this is, thanks to all who shared their solutions, what I came up with, tested and working for me on iPhone 7 iOS 10.x :

@media screen and (-webkit-min-device-pixel-ratio:0) {
    input[type="email"]:hover,
    input[type="number"]:hover,
    input[type="search"]:hover,
    input[type="text"]:hover,
    input[type="tel"]:hover,
    input[type="url"]:hover,
    input[type="password"]:hover,
    textarea:hover,
    select:hover{font-size: initial;}
}
@media (min-width: 768px) {
    input[type="email"]:hover,
    input[type="number"]:hover,
    input[type="search"]:hover,
    input[type="text"]:hover,
    input[type="tel"]:hover,
    input[type="url"]:hover,
    input[type="password"]:hover,
    textarea:hover,
    select:hover{font-size: inherit;}
}

It has some cons, though, noticeably a "jump" as result of the quick font size change occuring between the "hover"ed and "focus"ed states - and the redraw impact on performance

Visual Studio 2017: Display method references

For anyone who is looking to enable this on the Mac version, it is not available. Developers of Visual Studio stated they will include in their roadmap.

How to grep (search) committed code in the Git history

For anyone else trying to do this in Sourcetree, there is no direct command in the UI for it (as of version 1.6.21.0). However, you can use the commands specified in the accepted answer by opening Terminal window (button available in the main toolbar) and copy/pasting them therein.

Note: Sourcetree's Search view can partially do text searching for you. Press Ctrl + 3 to go to Search view (or click Search tab available at the bottom). From far right, set Search type to File Changes and then type the string you want to search. This method has the following limitations compared to the above command:

  1. Sourcetree only shows the commits that contain the search word in one of the changed files. Finding the exact file that contains the search text is again a manual task.
  2. RegEx is not supported.

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

How to check empty object in angular 2 template using *ngIf

Above answers are okay. But I have found a really nice option to use following in the view:

{{previous_info?.title}}

probably duplicated question Angular2 - error if don't check if {{object.field}} exists

how to destroy an object in java?

Short Answer - E

Answer isE given that the rest are plainly wrong, but ..

Long Answer - It isn't that simple; it depends ...

Simple fact is, the garbage collector may never decide to garbage collection every single object that is a viable candidate for collection, not unless memory pressure is extremely high. And then there is the fact that Java is just as susceptible to memory leaks as any other language, they are just harder to cause, and thus harder to find when you do cause them!

The following article has many good details on how memory management works and doesn't work and what gets take up by what. How generational Garbage Collectors work and Thanks for the Memory ( Understanding How the JVM uses Native Memory on Windows and Linux )

If you read the links, I think you will get the idea that memory management in Java isn't as simple as a multiple choice question.

How to Join to first row

SELECT   Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM     Orders
JOIN     LineItems
ON       LineItems.LineItemGUID =
         (
         SELECT  TOP 1 LineItemGUID 
         FROM    LineItems
         WHERE   OrderID = Orders.OrderID
         )

In SQL Server 2005 and above, you could just replace INNER JOIN with CROSS APPLY:

SELECT  Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description
FROM    Orders
CROSS APPLY
        (
        SELECT  TOP 1 LineItems.Quantity, LineItems.Description
        FROM    LineItems
        WHERE   LineItems.OrderID = Orders.OrderID
        ) LineItems2

Please note that TOP 1 without ORDER BY is not deterministic: this query you will get you one line item per order, but it is not defined which one will it be.

Multiple invocations of the query can give you different line items for the same order, even if the underlying did not change.

If you want deterministic order, you should add an ORDER BY clause to the innermost query.

Example sqlfiddle

Difference between "char" and "String" in Java

In layman's term, char is a letter, while String is a collection of letter (or a word). The distinction of ' and " is important, as 'Test' is illegal in Java.

char is a primitive type, String is a class

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Faced myself and seen several times in comments for similar questions - that even after installing "latest" Google Play Services and Google Repository still having the same issue.

The thing is that they may be latest for your current revision of Android SDK Tools, but not that latest your app build requires.

In such case make sure to install latest version of Android SDK Tools first, and probably Android SDK Platform-tools (both under Tools branch). Also please note you may need to go through this several times if you haven't updated for a long time (i.e. install latest Android SDK Tools and Android SDK Platform-tools, then restart Android SDK Manager, then repeat), since the updates seem to be going through some critical mandatory milestones and you cannot install the very latest if you currently have the revision which is pretty "old".

Android SDK Manager - Tools and Platform-tools

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Surely it's a little extreme to say

...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)

?

It is worth highlighting the section in the Douglas Crockford extract

...The second form should be used with objects...

If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};.

In this case myAssocArray.length will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.

Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Algorithm/Data Structure Design Interview Questions

I like to go over a code the person actually wrote and have them explain it to me.

Why Git is not allowing me to commit even after configuration?

That’s a typo. You’ve accidently set user.mail with no e. Fix it by setting user.email in the global configuration with

git config --global user.email "[email protected]"

"ImportError: No module named" when trying to run Python script

This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it's better to specify which version to use. For example use

python3 .....

instead of

python

In oracle, how do I change my session to display UTF8?

The character set is part of the locale, which is determined by the value of NLS_LANG. As the documentation makes clear this is an operating system variable:

NLS_LANG is set as an environment variable on UNIX platforms. NLS_LANG is set in the registry on Windows platforms.

Now we can use ALTER SESSION to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I have had this issue before.

client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

do this against your wcf proxy before making the call.

Fetch the row which has the Max value for a column

I don't have Oracle to test it, but the most efficient solution is to use analytic queries. It should look something like this:

SELECT DISTINCT
    UserId
  , MaxValue
FROM (
    SELECT UserId
      , FIRST (Value) Over (
          PARTITION BY UserId
          ORDER BY Date DESC
        ) MaxValue
    FROM SomeTable
  )

I suspect that you can get rid of the outer query and put distinct on the inner, but I'm not sure. In the meantime I know this one works.

If you want to learn about analytic queries, I'd suggest reading http://www.orafaq.com/node/55 and http://www.akadia.com/services/ora_analytic_functions.html. Here is the short summary.

Under the hood analytic queries sort the whole dataset, then process it sequentially. As you process it you partition the dataset according to certain criteria, and then for each row looks at some window (defaults to the first value in the partition to the current row - that default is also the most efficient) and can compute values using a number of analytic functions (the list of which is very similar to the aggregate functions).

In this case here is what the inner query does. The whole dataset is sorted by UserId then Date DESC. Then it processes it in one pass. For each row you return the UserId and the first Date seen for that UserId (since dates are sorted DESC, that's the max date). This gives you your answer with duplicated rows. Then the outer DISTINCT squashes duplicates.

This is not a particularly spectacular example of analytic queries. For a much bigger win consider taking a table of financial receipts and calculating for each user and receipt, a running total of what they paid. Analytic queries solve that efficiently. Other solutions are less efficient. Which is why they are part of the 2003 SQL standard. (Unfortunately Postgres doesn't have them yet. Grrr...)

How to reload/refresh jQuery dataTable?

Very Simple answer

$("#table_name").DataTable().ajax.reload(null, false); 

Could not load file or assembly ... The parameter is incorrect

You can either clean, build or rebuild your application or simply delete Temporary ASP.NET Files at C:\Users\YOUR USERNAME\AppData\Local\Temp

This works like magic. In my case i had an assembly binding issue saying Could not load file bla bla bla

you can also see solution 2 as http://www.codeproject.com/Articles/663453/Understanding-Clean-Build-and-Rebuild-in-Visual-St

Set Background cell color in PHPExcel

This code should work for you:

 $PHPExcel->getActiveSheet()
        ->getStyle('A1')
        ->getFill()
        ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
        ->getStartColor()
        ->setRGB('FF0000')

But if you bother using this over and over again, I recommend using applyFromArray.

How to output (to a log) a multi-level array in a format that is human-readable?

If you need to log an error to Apache error log you can try this:

error_log( print_r($multidimensionalarray, TRUE) );

How to make Python script run as service?

My non pythonic approach would be using & suffix. That is:

python flashpolicyd.py &

To stop the script

killall flashpolicyd.py

also piping & suffix with disown would put the process under superparent (upper):

python flashpolicyd.pi & disown

How do I right align div elements?

If you don't have to support IE9 and below you can use flexbox to solve this: codepen

There's also a few bugs with IE10 and 11 (flexbox support), but they are not present in this example

You can vertically align the <button> and the <form> by wrapping them in a container with flex-direction: column. The source order of the elements will be the order in which they're displayed from top to bottom so I reordered them.

You can then horizontally align the form & button container with the canvas by wrapping them in a container with flex-direction: row. Again the source order of the elements will be the order in which they're displayed from left to right so I reordered them.

Also, this would require that you remove all position and float style rules from the code linked in the question.

Here's a trimmed down version of the HTML in the codepen linked above.

<div id="mainContainer">
  <div>
    <canvas></canvas>
  </div>
  <div id="formContainer">
    <div id="addEventForm"> 
      <form></form>
    </div>
    <div id="button">
      <button></button>
    </div>
  </div>
</div>

And here is the relevant CSS

#mainContainer {
  display: flex;
  flex-direction: row;
} 

#formContainer {
  display: flex;
  flex-direction: column;
}

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

Execute Python script via crontab

Put your script in a file foo.py starting with

#!/usr/bin/python

Then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang.

Reusing a PreparedStatement multiple times

The second way is a tad more efficient, but a much better way is to execute them in batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
        }

        statement.executeBatch();
    }
}

You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.

If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);

        try (PreparedStatement statement = connection.prepareStatement(SQL)) {
            // ...

            try {
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }
}

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

How does one create an InputStream from a String?

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

How to scroll up or down the page to an anchor using jQuery?

You may want to add offsetTop and scrollTop value in case You are animating not the whole page , but rather some nested content.

e.g :

var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop

this.manage_list_wrap.animate({
  scrollTop: y
}, 1000);

How to convert all tables from MyISAM into InnoDB?

<?php

  // connect your database here first

  mysql_connect('host', 'user', 'pass');

  $databases = mysql_query('SHOW databases');

  while($db = mysql_fetch_array($databases)) {
    echo "database => {$db[0]}\n";
    mysql_select_db($db[0]);

    $tables = mysql_query('SHOW tables');

    while($tbl = mysql_fetch_array($tables)) {
      echo "table => {$tbl[0]}\n";
      mysql_query("ALTER TABLE {$tbl[0]} ENGINE=InnoDB");
    }
  }

Can I add extension methods to an existing static class?

Nope. Extension method definitions require an instance of the type you're extending. It's unfortunate; I'm not sure why it's required...

Computational complexity of Fibonacci Sequence

There's a very nice discussion of this specific problem over at MIT. On page 5, they make the point that, if you assume that an addition takes one computational unit, the time required to compute Fib(N) is very closely related to the result of Fib(N).

As a result, you can skip directly to the very close approximation of the Fibonacci series:

Fib(N) = (1/sqrt(5)) * 1.618^(N+1) (approximately)

and say, therefore, that the worst case performance of the naive algorithm is

O((1/sqrt(5)) * 1.618^(N+1)) = O(1.618^(N+1))

PS: There is a discussion of the closed form expression of the Nth Fibonacci number over at Wikipedia if you'd like more information.

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

Why should Java 8's Optional not be used in arguments

Let's make something perfectly clear: in other languages, there is no general recommendation against the use of a Maybe type as a field type, a constructor parameter type, a method parameter type, or a function parameter type.

So if you "shouldn't" use Optional as a parameter type in Java, the reason is specific to Optional, to Java, or to both.

Reasoning that might apply to other Maybe types, or other languages, is probably not valid here.

Per Brian Goetz,

[W]e did have a clear intention when adding [Optional], and it was not to be a general purpose Maybe type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.

For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list. You should almost never use it as a field of something or a method parameter.

So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.

That said, in practice, I've rarely found using Optional as a field type or a parameter type to be an issue. If Optional, despite its limitations, works as a parameter type or a field type for your use case, use it.

Why am I getting Unknown error in line 1 of pom.xml?

I updated spring tool suits by going help > check for update.

Reading numbers from a text file into an array in C

for (i = 0; i < 16; i++)
{
    fscanf(myFile, "%d", &numberArray[i]);
}

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...

DNS problem, nslookup works, ping doesn't

Try ipconfig /displaydns and look for weddinglist. If it's cached as "name does not exist" (possibly because of a previous intermittent failed lookup), you can flush the cache with ipconfig /flushdns.

nslookup doesn't use the cache, but rather queries the DNS server directly.

It worked for me..

from https://superuser.com/a/507892

Use awk to find average of a column

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'

Add the numbers in $2 (second column) in sum (variables are auto-initialized to zero by awk) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'

If you want to use the shebang notation, you could write:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

You can also control the format of the average with printf() and a suitable format ("%13.6e\n", for example).

You can also generalize the code to average the Nth column (with N=2 in this sample) using:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

Removing body margin in CSS

I would recommend you to reset all the HTML elements before writing your css with:

* {
    margin: 0;
    padding: 0;
} 

After that, you can write your custom css, without any problems.

What is recursion and when should I use it?

Recursion is an expression directly or indirectly referencing itself.

Consider recursive acronyms as a simple example:

  • GNU stands for GNU's Not Unix
  • PHP stands for PHP: Hypertext Preprocessor
  • YAML stands for YAML Ain't Markup Language
  • WINE stands for Wine Is Not an Emulator
  • VISA stands for Visa International Service Association

More examples on Wikipedia

AngularJS 1.2 $injector:modulerr

A noob error can be forgetting to include the module js

<script src="app/modules/myModule.js"></script>

files in the index.html at all

Git merge with force overwrite

This merge approach will add one commit on top of master which pastes in whatever is in feature, without complaining about conflicts or other crap.

enter image description here

Before you touch anything

git stash
git status # if anything shows up here, move it to your desktop

Now prepare master

git checkout master
git pull # if there is a problem in this step, it is outside the scope of this answer

Get feature all dressed up

git checkout feature
git merge --strategy=ours master

Go for the kill

git checkout master
git merge --no-ff feature

Floating Point Exception C++ Why and what is it?

Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

Single quotes vs. double quotes in C or C++

In C, single-quotes such as 'a' indicate character constants whereas "a" is an array of characters, always terminated with the \0 character

How to write ternary operator condition in jQuery?

I would go with such code:

var oBox = $("#blackbox");
var curClass = oBox.attr("class");
var newClass = (curClass == "bg_black") ? "bg_pink" : "bg_black";
oBox.removeClass().addClass(newClass);

To have it working, you first have to change your CSS and remove the background from the #blackbox declaration, add those two classes:

.bg_black { background-color: #000; }
.bg_pink { background-color: pink; }

And assign the class bg_black to the blackbox element initially.

Updated jsFiddle: http://jsfiddle.net/6nar4/17/

In my opinion it's more readable than the other answers but it's up to you to choose of course.

how to change the dist-folder path in angular-cli after 'ng build'

Caution: Angular 6 and above!


For readers with an angular.json (not angular-cli.json) the key correct key is outputPath. I guess the angular configuration changed to angular.json in Angular 6, so if you are using version 6 or above you most likely have a angular.json file.

To change the output path you have to change outputPath und the build options.

example angular.json

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "projects": {
        "angular-app": {
            "projectType": "application",
            [...]
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist/angular-app",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        [...]

I could not find any official docs on this (not included in https://angular.io/guide/workspace-config as I would have expected), maybe someone can link an official resource on this.

How to display activity indicator in middle of the iphone screen?

I found a way to display activity Indicator with minimum code:

first of all import your UI Kit

import UIKit;

Then you have to initiate activity indicator

let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView();

Then just copy paste this functions below which are self explainatory and call them whereever you need them:

func startLoading(){
    activityIndicator.center = self.view.center;
    activityIndicator.hidesWhenStopped = true;
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray;
    view.addSubview(activityIndicator);

    activityIndicator.startAnimating();
    UIApplication.shared.beginIgnoringInteractionEvents();

}

func stopLoading(){ 

    activityIndicator.stopAnimating();
    UIApplication.shared.endIgnoringInteractionEvents();

}

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

Install a Windows service using a Windows command prompt?

  1. start up the command prompt (CMD) with administrator rights.
  2. Type c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe [your windows service path to exe]
  3. Press return

What should my Objective-C singleton look like?

Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.

All the implementations of initialize I've read in other answers share a common error.

+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}

+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}

The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:

[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]

Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize.

You may think that you should implicitly check for duplicate initialization in your init block as such:

- (id) init { <----- Wrong!
   if (_instance != nil) {
      // Some hack
   }
   else {
      // Do stuff
   }
  return self;
}

But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.

- (id) init { <----- Correct!
   NSAssert(_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self){
      // Do stuff
   }
   return self;
}

TL;DR, here's my implementation

@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
   if (self == [MySingletonClass class]){
      _instance = [[MySingletonClass alloc] init];
   }
}

- (id) init {
   ZAssert (_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self) {
      // Initialization
   }
   return self;
}

+ (id) getInstance {
   return _instance;
}
@end

(Replace ZAssert with our own assertion macro; or just NSAssert.)

Get index of a key/value pair in a C# dictionary based on the value

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).

Obviously you can get the key from a KeyValuePair just by using the Key property, so that will let you use the indexer of the dictionary:

var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);

You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:

var key = dictionary.Where(pair => pair.Value == desiredValue)
                    .Select(pair => pair.Key)
                    .FirstOrDefault();

key will be null if the entry doesn't exist.

This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.

Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

What exactly does stringstream do?

Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream is similar to the usage of iostream, so it is not a burden to learn.

Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.

The basic member functions of stringstream class are

  • str(), which returns the contents of its buffer in string type.

  • str(string), which set the contents of the buffer to the string argument.

Here is an example of how to use string streams.

ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;

The result is dec: 15 hex: f.

istringstream is of more or less the same usage.

To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.

FYI, the inheritance relationships between the classes are:

string stream classes

The 'packages' element is not declared

Taken from this answer.

  1. Close your packages.config file.
  2. Build
  3. Warning is gone!

This is the first time I see ignoring a problem actually makes it go away...

Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

Using a .php file to generate a MySQL dump

_x000D_
_x000D_
global $wpdb;_x000D_
$export_posts = $wpdb->prefix . 'export_posts';_x000D_
$backupFile = $_GET['targetDir'].'export-gallery.sql';_x000D_
$dbhost=DB_HOST;_x000D_
$dbuser=DB_USER;_x000D_
$dbpass=DB_PASSWORD;_x000D_
$db=DB_NAME;_x000D_
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";_x000D_
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";_x000D_
exec($query);_x000D_
echo $query;
_x000D_
_x000D_
_x000D_

Gunicorn worker timeout error

I had very similar problem, I also tried using "runserver" to see if I could find anything but all I had was a message Killed

So I thought it could be resource problem, and I went ahead to give more RAM to the instance, and it worked.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

[For IntelliJ IDEA 2016.2]

I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:

You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.

I believe that (at least in 2016.2): checking out different commits in git resets these to 1.5.

Per-module bytecode version

Regex pattern for checking if a string starts with a certain substring?

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

SQL Server ON DELETE Trigger

I would suggest the use of exists instead of in because in some scenarios that implies null values the behavior is different, so

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2 childTable
    WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO

Is it possible to make input fields read-only through CSS?

With CSS only? This is sort of possible on text inputs by using user-select:none:

.print {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;          
}

JSFiddle example.

It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select property. The readonly property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.

With JavaScript:

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select property now appears to be ignored on input elements.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

In Alpine linux you should do:

apk add curl-dev python3-dev libressl-dev

How to convert an array to object in PHP?

function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

function array_to_object($data)
{
    if (is_array($data) || is_object($data))
    {
        $result= new stdClass();
        foreach ($data as $key => $value)
        {
            $result->$key = array_to_object($value);
        }
        return $result;
    }
    return $data;
}

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

How to read large text file on windows?

if you can code, write a console app. here is the c# equivalent of what you're after. you can do what you want with the results (split, execute etc):

SqlCommand command = null;
try
{
    using (var connection = new SqlConnection("XXXX"))
    {
        command = new SqlCommand();
        command.Connection = connection;
        if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader("C:\\test.txt"))
        {
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
                command.CommandText = line;
                command.ExecuteNonQuery();
                Console.Write(" - DONE");
            }
        }
    }
}
catch (Exception e)
{
    // Let the user know what went wrong.
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
finally
{
    if (command.Connection.State == ConnectionState.Open) command.Connection.Close();
}

What is the best alternative IDE to Visual Studio

If you are looking to try Java, I believe NetBeans is a very, very good IDE. However, for .NET, sure there are alternative IDEs but I don't think it makes much sense to use them unless you are developing on an Open Source platform, in which case SharpDevelop is a good choice and is reasonably mature.

Printing newlines with print() in R

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))

How can I profile C++ code running on Linux?

These are the two methods I use for speeding up my code:

For CPU bound applications:

  1. Use a profiler in DEBUG mode to identify questionable parts of your code
  2. Then switch to RELEASE mode and comment out the questionable sections of your code (stub it with nothing) until you see changes in performance.

For I/O bound applications:

  1. Use a profiler in RELEASE mode to identify questionable parts of your code.

N.B.

If you don't have a profiler, use the poor man's profiler. Hit pause while debugging your application. Most developer suites will break into assembly with commented line numbers. You're statistically likely to land in a region that is eating most of your CPU cycles.

For CPU, the reason for profiling in DEBUG mode is because if your tried profiling in RELEASE mode, the compiler is going to reduce math, vectorize loops, and inline functions which tends to glob your code into an un-mappable mess when it's assembled. An un-mappable mess means your profiler will not be able to clearly identify what is taking so long because the assembly may not correspond to the source code under optimization. If you need the performance (e.g. timing sensitive) of RELEASE mode, disable debugger features as needed to keep a usable performance.

For I/O-bound, the profiler can still identify I/O operations in RELEASE mode because I/O operations are either externally linked to a shared library (most of the time) or in the worst case, will result in a sys-call interrupt vector (which is also easily identifiable by the profiler).

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

Edit a specific Line of a Text File in C#

I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps

using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
        {
            var destinationReader = StreamReader(fs);
            var writer = StreamWriter(fs);
            while ((line = reader.ReadLine()) != null)
            {
              if (line_number == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    destinationReader .ReadLine();
                }
                line_number++;
            }
        }

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

This happened to me when I was already using @Transactional(value=...) and was using multiple transaction managers.

My forms were sending back data that already had @JsonIgnore on them, so the data being sent back from forms was incomplete.

Originally I used the anti pattern solution, but found it was incredibly slow. I disabled this by setting it to false.

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=false

The fix was to ensure that any objects that had lazy-loaded data that weren't loading were retrieved from the database first.

Optional<Object> objectDBOpt = objectRepository.findById(object.getId());

if (objectDBOpt.isEmpty()) {
    // Throw error
} else {
    Object objectFromDB = objectDBOpt.get();
}

In short, if you've tried all of the other answers, just make sure you look back to check you're loading from the database first if you haven't provided all the @JsonIgnore properties and are using them in your database query.

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

How to find numbers from a string?

I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.

Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer

controlval = "A1B2C3D4"

For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i

resultval = 1234

What is the most efficient way to check if a value exists in a NumPy array?

To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():

import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)

index = np.searchsorted(data, values)
print data[index] == values

Differences between "java -cp" and "java -jar"?

With the -cp argument you provide the classpath i.e. path(s) to additional classes or libraries that your program may require when being compiled or run. With -jar you specify the executable JAR file that you want to run.

You can't specify them both. If you try to run java -cp folder/myexternallibrary.jar -jar myprogram.jar then it won't really work. The classpath for that JAR should be specified in its Manifest, not as a -cp argument.

You can find more about this here and here.

PS: -cp and -classpath are synonyms.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

Hidden Columns in jqGrid

It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.

Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.

  function showHideColumns() {
        $('#jqGrid').jqGrid('columnChooser', {
            width: 250,
            dialog_opts: {
                modal: true,
                minWidth: 250,
                height: 300,
                show: 'blind',
                hide: 'explode',
                dividerLocation: 0.5
            } });

How do I remove duplicates from a C# array?

Removing duplicate and ignore case sensitive using Distinct & StringComparer.InvariantCultureIgnoreCase

string[] array = new string[] { "A", "a", "b", "B", "a", "C", "c", "C", "A", "1" };
var r = array.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
Console.WriteLine(r.Count); // return 4 items

How to disable submit button once it has been clicked?

You should first submit your form and then change the value of your submit:

onClick="this.form.submit(); this.disabled=true; this.value='Sending…'; "

Loop inside React JSX

An ES2015 / Babel possibility is using a generator function to create an array of JSX:

function* jsxLoop(times, callback)
{
    for(var i = 0; i < times; ++i)
        yield callback(i);
}

...

<tbody>
    {[...jsxLoop(numrows, i =>
        <ObjectRow key={i}/>
    )]}
</tbody>

Output Django queryset as JSON

It didn't work, because QuerySets are not JSON serializable.

1) In case of json.dumps you have to explicitely convert your QuerySet to JSON serializable objects:

class Model(model.Model):
    def as_dict(self):
        return {
            "id": self.id,
            # other stuff
        }

And the serialization:

dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')

2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:

serializers.serialize("json", self.get_queryset())

Read more about it here:

https://docs.djangoproject.com/en/dev/topics/serialization/

Insert a background image in CSS (Twitter Bootstrap)

isn't the problem the following line is incorrect as the statement for background-repeat isn't closed before the next statement for display...

background-repeat:no-repeatdisplay: compact;

Shouldn't this be

background-repeat:no-repeat;
display: compact;

adding or removing quotes (in my experience) makes no difference if the URL is correct. Is the path to the image correct? If you give a relative path to a resource in a CSS it's relative to the CSS file, not the file including the CSS.

How does "make" app know default target to build if no target is specified?

By default, it begins by processing the first target that does not begin with a . aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.

The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.

What is EOF in the C programming language?

EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.

Edit:

I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Visual Studio Community 2015 expiration date

In my case, even after sign up to Visual Studio account, I cant sign in and the license still expired.

Solution from across the internet: Download iso version of the installer. Then run installer, select repair. That would solve the problem for most case.

In my case, I got an iso version of ms Visual Studio 2013. Installed it and I can successfully sign in and its forever free.

React Native Border Radius with background color

You should add overflow: hidden to your styles:

Js:

<Button style={styles.submit}>Submit</Button>

Styles:

submit {
   backgroundColor: '#68a0cf';
   overflow: 'hidden';
}