Programs & Examples On #Treeviewitem

A tree view item is an element or node of a tree view.

Are string.Equals() and == operator really same?

In addition to Jon Skeet's answer, I'd like to explain why most of the time when using == you actually get the answer true on different string instances with the same value:

string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);

As you can see, a and b must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a and b reference the same string in memory. The == operator for objects checks reference, and since both a and b reference the same instance, the result is true. When you change either one of them, a new string instance is created, which is why string interning is possible.

By the way, Jon Skeet's answer is not complete. Indeed, x == y is false but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y, it will return true again. So strings have their ==-operator overloaded, which calls String.Equals underneath.

Escaping Double Quotes in Batch Script

For example for Unreal engine Automation tool run from batch file - this worked for me

eg: -cmdline=" -Messaging" -device=device -addcmdline="-SessionId=session -SessionOwner='owner' -SessionName='Build' -dataProviderMode=local -LogCmds='LogCommodity OFF' -execcmds='automation list; runtests tests+separated+by+T1+T2; quit' " -run

Hope this helps someone, worked for me.

The ScriptManager must appear before any controls that need it

You can add your Script Manager tags just below the <Form> tag of your page. Here is how you can place your Script Manager tag.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.

WPF Binding StringFormat Short Date String

Just use:

<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />

How to truncate string using SQL server

You can also use the Cast() operation :

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name

MySQL - How to select rows where value is in array?

If the array element is not integer you can use something like below :

$skus  = array('LDRES10','LDRES12','LDRES11');   //sample data

if(!empty($skus)){     
    $sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "      
}

Is it possible to run selenium (Firefox) web driver without a GUI?

If you want headless browser support then there is another approach you might adopt.

https://github.com/detro/ghostdriver

It was announced during Selenium Conference and it is still in development. It uses PhantomJS as the browser and is much better than HTMLUnitDriver, there are no screenshots yet, but as it is still in active development.

Android - styling seek bar

Google have made this easier in SDK 21. Now we have attributes for specifying the thumb tint colors:

android:thumbTint
android:thumbTintMode
android:progressTint

http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTint http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTintMode

Sort & uniq in Linux shell

Beware! While it's true that "sort -u" and "sort|uniq" are equivalent, any additional options to sort can break the equivalence. Here's an example from the coreutils manual:

For example, 'sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas 'sort -n | uniq' inspects the entire line.

Similarly, if you sort on key fields, the uniqueness test used by sort won't necessarily look at the entire line anymore. After being bitten by that bug in the past, these days I tend to use "sort|uniq" when writing Bash scripts. I'd rather have higher I/O overhead than run the risk that someone else in the shop won't know about that particular pitfall when they modify my code to add additional sort parameters.

How to watch for form changes in Angular

If you are using FormBuilder, see @dfsq's answer.

If you are not using FormBuilder, there are two ways to be notified of changes.

Method 1

As discussed in the comments on the question, use an event binding on each input element. Add to your template:

<input type="text" class="form-control" required [ngModel]="model.first_name"
         (ngModelChange)="doSomething($event)">

Then in your component:

doSomething(newValue) {
  model.first_name = newValue;
  console.log(newValue)
}

The Forms page has some additional information about ngModel that is relevant here:

The ngModelChange is not an <input> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.

The other oddity is the template expression, model.name = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires..

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.

In your case, I suppose you want to do something special.

Method 2

Define a local template variable and set it to ngForm.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  ....
  <input type="text" ngControl="firstName" class="form-control" 
   required [(ngModel)]="model.first_name">
  ...
  <input type="text" ngControl="lastName" class="form-control" 
   required [(ngModel)]="model.last_name">

class MyForm {
  @ViewChild('myForm') form;
  ...
  ngAfterViewInit() {
    console.log(this.form)
    this.form.control.valueChanges
      .subscribe(values => this.doSomething(values));
  }
  doSomething(values) {
    console.log(values);
  }
}

plunker

For more information on Method 2, see Savkin's video.

See also @Thierry's answer for more information on what you can do with the valueChanges observable (such as debouncing/waiting a bit before processing changes).

Creating a Facebook share button with customized url, title and image

Unfortunately, it appears that we can't post shares for individual topics or articles within a page. It appears Facebook just wants us to share entire pages (based on url only).

There's also their new share dialog, but even though they claim it can do all of what the old sharer.php could do, that doesn't appear to be true.

And here's Facebooks 'best practices' for sharing.

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This is ridiculous but I just have rebooted my machine (mac) and the problem was gone like it has never happened. I hate to sound like a support guy...

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

How can I undo a `git commit` locally and on a remote after `git push`

You can do an interactive rebase:

git rebase -i <commit>

This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.

You will, of course, need access to the remote repository to apply this change there too.

See this question: Git: removing selected commits from repository

What is a Subclass

Subclass is to Class as Java is to Programming Language.

Spring MVC - HttpMediaTypeNotAcceptableException

Just something important to keep in mind: Spring versions prior to 3.1.2 are compatible with JACKSON 1.x and NOT with JACKSON 2.x. This is because going from JACKSON 1.x to 2.x the classes's package names were changed. In JACKSON 1.x classes are under org.codehaus.jackson while in JACKSON 2.x they are under com.fasterxml.jackson.

To address this issue, starting with Spring 3.1.2 they added a new MappingJackson2HttpMessageConverter to replace MappingJacksonHttpMessageConverter.

You could find more details regarding compatibility issues in this link: Jackson annotations being ignored in Spring

How do you list volumes in docker containers?

For Docker 1.8, I use:

$ docker inspect -f "{{ .Config.Volumes }}" 957d2dd1d4e8
map[/xmount/dvol.01:{}]
$ 

Determine if an element has a CSS class with jQuery

In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.

simple example :

 <!--element html-->
 <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

 <!--jQuery "is"-->
 $('#menu').is('.cbp-spmenu-open');

advanced example :

 <!--element html-->
    <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

   <!--jQuery "is"-->
    if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
       $("#menu").show();
    }

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

This answer is quite similar to the accepted answer, but doesn't override the Date prototype, and only uses one function call to check if Daylight Savings Time is in effect, rather than two.


The idea is that, since no country observes DST that lasts for 7 months[1], in an area that observes DST the offset from UTC time in January will be different to the one in July.

While Daylight Savings Time moves clocks forwards, JavaScript always returns a greater value during Standard Time. Therefore, getting the minimum offset between January and July will get the timezone offset during DST.

We then check if the dates timezone is equal to that minimum value. If it is, then we are in DST; otherwise we are not.

The following function uses this algorithm. It takes a date object, d, and returns true if daylight savings time is in effect for that date, and false if it is not:

function isDST(d) {
    let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
    let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
    return Math.max(jan, jul) != d.getTimezoneOffset(); 
}

Can I set state inside a useEffect hook

For future purposes, this may help too:

It's ok to use setState in useEffect you just need to have attention as described already to not create a loop.

But it's not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a and prop.b so the value of {...state} when you do setState are exactly the same in both useEffect because they are in the same context. When you run the second setState it will replace the first setState.

DO THIS INSTEAD

The solution for this problem is basically call setState like this:

useEffect(() => {
  setState(state => ({ ...state, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(state => ({ ...state, b: props.b }));
}, [props.b]);

Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

Now, you always receive the most updated and correct value of the state when you proceed with the setState.

I hope this helps someone!

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.

The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.

Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:

var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
    ...
    if(ajax.responseType === 'blob'){
        // Convert the blob to a string
        var reader = new window.FileReader();
        reader.addEventListener('loadend', function() {
           // For ISO-8859-1 there's no further conversion required
           Promise.resolve(reader.result);
        });
        reader.readAsBinaryString(ajax.response);
    }
}

Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.

Center a H1 tag inside a DIV

On the hX tag

width: 100px;
margin-left: auto;
margin-right: auto;

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Git 'fatal: Unable to write new index file'

The error message fatal: Unable to write new index file means that we could not write the new content to the git index file .git\index (See here for more information about git index). After reviewing all the answers to this question, I summarize the following root causes:

  • The size of new content exceeds the disk available capacity. (Solution: Clean the disk spaces)
  • Users do not have access right to this file. (Solution: Grant the permission)
  • Users have permission but .git\index is locked by other users or processes. (Solution: Unlock the file)

The link Find out which process is locking a file or folder in Windows specifies the following approach to find out the process which is locking a specific file:

SysInternals Process Explorer - Go to Find > Find Handle or DLL. In the "Handle or DLL substring:" text box, type the path to the file (e.g. "C:\path\to\file.txt") and click "Search". All processes which have an open handle to that file should be listed.

Use the above approach to find which process locked .git\index and then stop the locking executable. This unlocks .git\index.

For example, Process Explorer Search shows that .git\index is locked by vmware-vmx.exe. Suspending the VMWare Player virtual machine (which accessed the git repo via a shared folder) solved the issue.

Change icon-bar (?) color in bootstrap

In bootstrap 4.3.1 I can change the background color of the toggler icon to white via the css code.

.navbar-toggler{
  background-color:white;
  }

And in my opinion the so changed icon looks fine as well on light as on dark background.

How to retrieve unique count of a field using Kibana + Elastic Search

Unique counts of field values are achieved by using facets. See ES documentation for the full story, but the gist is that you will create a query and then ask ES to prepare facets on the results for counting values found in fields. It's up to you to customize the fields used and even describe how you want the values returned. The most basic of facet types is just to group by terms, which would be like an IP address above. You can get pretty complex with these, even requiring a query within your facet!

{
    "query": {
        "match_all": {}
    },
    "facets": {
        "terms": {
            "field": "ip_address"
        }
    }
}

Angular 2: How to style host element of the component?

In your Component you can add .class to your host element if you would have some general styles that you want to apply.

export class MyComponent{
     @HostBinding('class') classes = 'classA classB';

Node.js getaddrinfo ENOTFOUND

If still you are facing checkout for proxy setting, for me it was the proxy setting which were missing and was not able to make the request as direct http/https are blocked. So i configured the proxy from my organization while making the request.

npm install https-proxy-agent 
or 
npm install http-proxy-agent

const httpsProxyAgent = require('https-proxy-agent');
const agent = new httpsProxyAgent("http://yourorganzation.proxy.url:8080");
const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  agent: agent
};

belongs_to through associations

It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.

Is this what you are after?

I would model something like that along these lines:

class User
  has_many :questions
end

class Question
  belongs_to :user
  has_many   :answers
  has_one    :choice, :class_name => "Answer"

  validates_inclusion_of :choice, :in => lambda { answers }
end

class Answer
  belongs_to :question
end

How can I convert a Word document to PDF?

Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.

  1. Download JACOB archive (the latest version is 1.19);
  2. Add jacob.jar to your project classpath;
  3. Add jacob-1.19-x32.dll or jacob-1.19-x64.dll (depends on your jdk version) to ...\Java\jdk1.x.x_xxx\jre\bin
  4. Using JACOB API call Office Word to convert doc/docx to pdf.

    public void convertDocx2pdf(String docxFilePath) {
    File docxFile = new File(docxFilePath);
    String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
    
    if (docxFile.exists()) {
        if (!docxFile.isDirectory()) { 
            ActiveXComponent app = null;
    
            long start = System.currentTimeMillis();
            try {
                ComThread.InitMTA(true); 
                app = new ActiveXComponent("Word.Application");
                Dispatch documents = app.getProperty("Documents").toDispatch();
                Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
                File target = new File(pdfFile);
                if (target.exists()) {
                    target.delete();
                }
                Dispatch.call(document, "SaveAs", pdfFile, 17);
                Dispatch.call(document, "Close", false);
                long end = System.currentTimeMillis();
                logger.info("============Convert Finished:" + (end - start) + "ms");
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                throw new RuntimeException("pdf convert failed.");
            } finally {
                if (app != null) {
                    app.invoke("Quit", new Variant[] {});
                }
                ComThread.Release();
            }
        }
    }
    

    }

What jar should I include to use javax.persistence package in a hibernate based application?

If you are using maven, adding below dependency should work

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

expected assignment or function call: no-unused-expressions ReactJS

In my case the error happened because the new line after the return statement.

Error : Expected an assignment or function call and instead saw an expression

return
(
    <ul>
        {
            props.numbers.map(number => <li key={number.toString()}>number</li>)
        }
    </ul>
);

Working OK. No Error

return (
    <ul>
        {
            props.numbers.map(number => <li key={number.toString()}>number</li>)
        }
    </ul>
);

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

How to rename HTML "browse" button of an input type=file?

You can also use Uploadify, which is a great jQuery upload plugin, it let's you upload multiple files, and also style the file fields easily. http://www.uploadify.com

Downloading a file from spring controllers

If it helps anyone. You can do what the accepted answer by Infeligo has suggested but just put this extra bit in the code for a forced download.

response.setContentType("application/force-download");

Closing a file after File.Create

File.Create returns a FileStream object that you can call Close() on.

How to write one new line in Bitbucket markdown?

I was facing the same issue in bitbucket, and this worked for me:

line1
##<2 white spaces><enter>
line2

Enabling SSL with XAMPP

I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.

  1. Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.

  2. Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone

  3. Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.

  4. Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.

  5. Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:

<VirtualHost *:443>
    DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
    ServerName yourwebsitedomainnamee.hopto.org 
    <Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "G:/xampp/apache/logs/error.log"
    CustomLog "G:/xampp/apache/logs/access.log" common
    SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>  
     
  1. Then navigated to G:\xampp\apache\conf\extra\httpd-ssl.conf and did as was advised above. I missed this important step for days until I read this post. Thank you! I.e. entered
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>  

Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.

What does <T> (angle brackets) mean in Java?

<> is used to indicate generics in Java.

T is a type parameter in this example. And no: instantiating is one of the few things that you can't do with T.

Apart from the tutorial linked above Angelika Langers Generics FAQ is a great resource on the topic.

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Laravel 5.4 Specific Table Migration

You need to put the file(s) into a new directory (ex:selected) and then apply

php artisan migrate  --path=/database/migrations/selected

if you need rollback:

php artisan migrate:rollback  --path=/database/migrations/selected

Note:

php artisan migrate:refresh

this will rollback and then migrate all the migrations files in the default directory (/database/migrations)

How to increment variable under DOS?

I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.

Your code contained the line

set /A COUNTER=%COUNTER%+1

and the syntax that would work is simply...

set /A COUNTER=COUNTER+1

See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.

Check if a JavaScript string is a URL

I think using the native URL API is better than a complex regex patterns as @pavlo suggested. It has some drawbacks though which we can fix by some extra code. This approach fails for the following valid url.

//cdn.google.com/script.js

We can add the missing protocol beforehand to avoid that. It also fails to detect following invalid url.

http://w
http://..

So why check the whole url? we can just check the domain. I borrowed the regex to verify domain from here.

function isValidUrl(string) {
    if (string && string.length > 1 && string.slice(0, 2) == '//') {
        string = 'http:' + string; //dummy protocol so that URL works
    }
    try {
        var url = new URL(string);
        return url.hostname && url.hostname.match(/^([a-z0-9])(([a-z0-9-]{1,61})?[a-z0-9]{1})?(\.[a-z0-9](([a-z0-9-]{1,61})?[a-z0-9]{1})?)?(\.[a-zA-Z]{2,4})+$/) ? true : false;
    } catch (_) {
        return false;
    }
}

The hostname attribute is empty string for javascript:void(0), so it works for that too, and you can also add IP address verifier too. I'd like to stick to native API's most, and hope it starts to support everything in near future.

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

Http Basic Authentication in Java using HttpClient?

A small update - hopefully useful for somebody - it works for me in my project:

  • I use the nice Public Domain class Base64.java from Robert Harder (Thanks Robert - Code availble here: Base64 - download and put it in your package).

  • and make a download of a file (image, doc, etc.) with authentication and write to local disk

Example:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpBasicAuth {

public static void downloadFileWithAuth(String urlStr, String user, String pass, String outFilePath) {
    try {
        // URL url = new URL ("http://ip:port/download_url");
        URL url = new URL(urlStr);
        String authStr = user + ":" + pass;
        String authEncoded = Base64.encodeBytes(authStr.getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);

        File file = new File(outFilePath);
        InputStream in = (InputStream) connection.getInputStream();
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        for (int b; (b = in.read()) != -1;) {
            out.write(b);
        }
        out.close();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
}

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

How do I make a C++ macro behave like a function?

Create a block using

 #define MACRO(...) do { ... } while(false)

Do not add a ; after the while(false)

Routing for custom ASP.NET MVC 404 Error page

I will talk about some specific cases,

if you are using 'PageNotFound method' in HomeController like below

[Route("~/404")]
public ActionResult PageNotFound()
{
  return MyView();
}

it wouldn't work this. But you must clear Route tags like below,

//[Route("~/404")]
public ActionResult PageNotFound()
{
  return MyView();
}

And if you change it as method Name in web.config it works. However don't forget to do code like below in web.config

<customErrors mode="On">
  <error statusCode="404" redirect="~/PageNotFound" /> 
 *// it is not "~/404" because it is not accepted url in Route Tag like [Route("404")]*
</customErrors>

Android - SMS Broadcast receiver

The Updated code is :

 private class SMSReceiver extends BroadcastReceiver {
                private Bundle bundle;
                private SmsMessage currentSMS;
                private String message;

                @Override
                public void onReceive(Context context, Intent intent) {

                    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
                        bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdu_Objects = (Object[]) bundle.get("pdus");
                            if (pdu_Objects != null) {

                                for (Object aObject : pdu_Objects) {

                                    currentSMS = getIncomingMessage(aObject, bundle);

                                    String senderNo = currentSMS.getDisplayOriginatingAddress();

                                    message = currentSMS.getDisplayMessageBody();
                                    Toast.makeText(OtpActivity.this, "senderNum: " + senderNo + " :\n message: " + message, Toast.LENGTH_LONG).show();
                                }
                                this.abortBroadcast();
                                // End of loop
                            }
                        }
                    } // bundle null
                }
            }

        private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
            SmsMessage currentSMS;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = bundle.getString("format");
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
            } else {
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
            }
    return currentSMS;
}

older code was :

Object [] pdus = (Object[]) myBundle.get("pdus");

    messages = new SmsMessage[pdus.length];

    for (int i = 0; i < messages.length; i++)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String format = myBundle.getString("format");
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
        }
        else {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        strMessage += "SMS From: " + messages[i].getOriginatingAddress();
        strMessage += " : ";
        strMessage += messages[i].getMessageBody();
        strMessage += "\n";
    } 

The simple SYntax of code is :

private class SMSReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
            SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            for (SmsMessage message : smsMessages) {
                // Do whatever you want to do with SMS.
            }
        }
    }
}

C pointer to array/array of pointers disambiguation

Here's an interesting website that explains how to read complex types in C: http://www.unixwiz.net/techtips/reading-cdecl.html

How to find the Target *.exe file of *.appref-ms

I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".

I couldn't seem to find the location in the application reference file in my case...

Datetime in C# add days

Its because the AddDays() method returns a new DateTime, that you are not assigning or using anywhere.

Example of use:

DateTime newDate = endDate.AddDays(2);

Basic Authentication Using JavaScript

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

Reading a column from CSV file using JAVA

Splitting by comma doesn't work all the time for instance if you have csv file like

"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"

So, I would recommend using the Apache Commons CSV API:

    Reader in = new FileReader("input1.csv");
    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
    for (CSVRecord record : records) {
      System.out.println(record.get(0));
    }

What does enumerate() mean?

It's a builtin function that returns an object that can be iterated over. See the documentation.

In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

for item in enumerate(["a", "b", "c"]):
    print item

prints

(0, "a")
(1, "b")
(2, "c")

It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.

Android basics: running code in the UI thread

use Handler

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

How do I get list of methods in a Python class?

To produce a list of methods put the name of the method in a list without the usual parenthesis. Remove the name and attach the parenthesis and that calls the method.

    def methodA():
        print("@ MethodA")

    def methodB():
        print("@ methodB")

    a = []
    a.append(methodA)
    a.append(methodB)
    for item in a:
        item()

Where is SQLite database stored on disk?

SQLite is created in your python directory where you installed the python.

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

How to read line by line of a text area HTML tag

This works without needing jQuery:

var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line

Appending the same string to a list of strings in Python

map seems like the right tool for the job to me.

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = list(map(lambda orig_string: orig_string + string, my_list))

See this section on functional programming tools for more examples of map.

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

How to send a PUT/DELETE request in jQuery?

ajax()

look for param type

Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Set size of HTML page and browser window

<html>
<head >
<title>Welcome</title>    
<style type="text/css">
#maincontainer 
{   
top:0px;
padding-top:0;
margin:auto; position:relative;
width:950px;
height:100%;
}
  </style>
  </head>
<body>
 <div id="maincontainer ">
 </div>
</body>
</html>

Capture HTML Canvas as gif/jpg/png/pdf?

You can use jspdf to capture a canvas into an image or pdf like this:

var imgData = canvas.toDataURL('image/png');              
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');

More info: https://github.com/MrRio/jsPDF

Why do I have to "git push --set-upstream origin <branch>"?

The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:

git push -u origin <your-local-branch-name>

So if your local branch name is coffee

git push -u origin coffee

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

Getting current device language in iOS?

Even there's a better way to get current device language. Let's try it by below code -

NSLog(@"Current Language - %@", [[NSLocale preferredLanguages] firstObject]);

Suggested by Abizern on here

Is there 'byte' data type in C++?

Using C++11 there is a nice version for a manually defined byte type:

enum class byte : std::uint8_t {};

That's at least what the GSL does.

Starting with C++17 (almost) this very version is defined in the standard as std::byte (thanks Neil Macintosh for both).

Select option padding not working in chrome

This simple hack will indent the text. Works well.

select {
  text-indent: 5px;
}

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

Set cursor position on contentEditable <div>

You can leverage selectNodeContents which is supported by modern browsers.

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

JSP tricks to make templating easier?

As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.

Let's take your simple example.

Put the following in WEB-INF/tags/wrapper.tag

<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
  <jsp:doBody/>
</body></html>

Now in your example.jsp page:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>
    <h1>Welcome</h1>
</t:wrapper>

That does exactly what you think it does.


So, lets expand upon that to something a bit more general. WEB-INF/tags/genericpage.tag

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
  <body>
    <div id="pageheader">
      <jsp:invoke fragment="header"/>
    </div>
    <div id="body">
      <jsp:doBody/>
    </div>
    <div id="pagefooter">
      <jsp:invoke fragment="footer"/>
    </div>
  </body>
</html>

To use this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <p>Hi I'm the heart of the message</p>
    </jsp:body>
</t:genericpage>

What does that buy you? A lot really, but it gets even better...


WEB-INF/tags/userpage.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome ${userName}</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <jsp:doBody/>
    </jsp:body>
</t:genericpage>

To use this: (assume we have a user variable in the request)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    First Name: ${user.firstName} <br/>
    Last Name: ${user.lastName} <br/>
    Phone: ${user.phone}<br/>
  </p>
</t:userpage>

But it turns you like to use that user detail block in other places. So, we'll refactor it. WEB-INF/tags/userdetail.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>

First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>

Now the previous example becomes:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    <t:userdetail user="${user}"/>
  </p>
</t:userpage>

The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.

JSP Tag Files have pretty much usurped things like Tiles etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).

Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:

<t:table items="${actionBean.customerList}" var="obj" css_class="display">
  <t:col css_class="checkboxcol">
    <s:checkbox name="customerIds" value="${obj.customerId}"
                onclick="handleCheckboxRangeSelection(this, event);"/>
  </t:col>
  <t:col name="customerId" title="ID"/>
  <t:col name="firstName" title="First Name"/>
  <t:col name="lastName" title="Last Name"/>
  <t:col>
    <s:link href="/Customer.action" event="preEdit">
      Edit
      <s:param name="customer.customerId" value="${obj.customerId}"/>
      <s:param name="page" value="${actionBean.page}"/>
    </s:link>
  </t:col>
</t:table>

Of course the tags work with the JSTL tags (like c:if, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.

So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.

At a higher level, you can do sophisticated things like this table tag I have here.

Woocommerce, get current product id

your can query woocommerce programatically you can even add a product to your shopping cart. I'm sure you can figure out how to interact with woocommerce cart once you read the code. how to interact with woocommerce cart programatically

====================================

<?php

add_action('wp_loaded', 'add_product_to_cart');
function add_product_to_cart()
{
    global $wpdb;

    if (!is_admin()) {


        $product_id = wc_get_product_id_by_sku('L3-670115');

        $found = false;

        if (is_user_logged_in()) {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->get_id() == $product_id)
                        WC()->cart->remove_cart_item($cart_item_key);
                }
            }
        } else {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->id == $product_id)
                        $found = true;
                }
                // if product not found, add it
                if (!$found)
                    WC()->cart->add_to_cart($product_id);
            } else {
                // if no products in cart, add it
                WC()->cart->add_to_cart($product_id);
            }
        }
    }
}

How do I deploy Node.js applications as a single executable file?

You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common

You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

#!/bin/sh
#clone git repo
git clone your-repo.git

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How can I create an editable combo box in HTML/Javascript?

Here is a script for that: Demo, Source

Or another one which works slightly differently: link removed (site no longer exists)

What does it mean to write to stdout in C?

stdout stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin and stderr.

What they point to (or from) can be anything, actually the stream just provides your program an object that can be used as an interface to send or retrieve data. By default it is usually the terminal but it can be redirected wherever you want: a file, to a pipe goint to another process and so on.

Updating GUI (WPF) using a different thread

You can use Dispatcher.Invoke to update your GUI from a secondary thread.

Here is an example:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        new Thread(DoSomething).Start();
    }
    public void DoSomething()
    {
        for (int i = 0; i < 100000000; i++)
        {
               this.Dispatcher.Invoke(()=>{
               textbox.Text=i.ToString();
               });    
        } 
    }

What are allowed characters in cookies?

There are 2 versions of cookies specifications
1. Version 0 cookies aka Netscape cookies,
2. Version 1 aka RFC 2965 cookies
In version 0 The name and value part of cookies are sequences of characters, excluding the semicolon, comma, equals sign, and whitespace, if not used with double quotes
version 1 is a lot more complicated you can check it here
In this version specs for name value part is almost same except name can not start with $ sign

Extracting text OpenCV

You can try this method that is developed by Chucai Yi and Yingli Tian.

They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:

Note: to make the result more robust, you can further merge adjacent boxes together.


Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.

With this, you can get recognized texts like:

Best way to make WPF ListView/GridView sort on column-header clicking?

Just wanted to add another simple way someone can sort the the WPF ListView

void SortListView(ListView listView)
{
    IEnumerable listView_items = listView.Items.SourceCollection;
    List<MY_ITEM_CLASS> listView_items_to_list = listView_items.Cast<MY_ITEM_CLASS>().ToList();

    Comparer<MY_ITEM_CLASS> scoreComparer = Comparer<MY_ITEM_CLASS>.Create((first, second) => first.COLUMN_NAME.CompareTo(second.COLUMN_NAME));

    listView_items_to_list.Sort(scoreComparer);
    listView.ItemsSource = null;
    listView.Items.Clear();
    listView.ItemsSource = listView_items_to_list;
}

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

Get the current date and time

Try this one:

System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

What is the maximum float in Python?

sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.

How to export and import environment variables in windows?

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

Unity Scripts edited in Visual studio don't provide autocomplete

Try this,

  1. In Unity Editor Go to Menu, Click on Edit -> Preferences -> External Tools -> External Script Editor. Set it to Visual Studio (your installed version of VS).

  2. Now in Menubar go to Edit -> Project Settings -> Player Settings -> Other Settings -> Under Configuration -> Check API Compatibility Level -> Change it to your installed .Net version. In my case I set it to .Net 4.x

Now if Visual Studio is running already go to Visual Studio, it will ask to reload project. Reload the project. Check if it works, if not close Visual Studio. Now Open cs file from Unity Editor, and now it should work.

Default values in a C Struct

How about something like:

struct foo bar;
update(init_id(42, init_dont_care(&bar)));

with:

struct foo* init_dont_care(struct foo* bar) {
  bar->id = dont_care;
  bar->route = dont_care;
  bar->backup_route = dont_care;
  bar->current_route = dont_care;
  return bar;
}

and:

struct foo* init_id(int id, struct foo* bar) {
  bar->id = id;
  return bar;
}

and correspondingly:

struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);

In C++, a similar pattern has a name which I don't remember just now.

EDIT: It's called the Named Parameter Idiom.

Android change SDK version in Eclipse? Unable to resolve target android-x

I faced the same issue and got it working.

I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.

The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.

Celery Received unregistered task of type (run example)

I've found that one of our programmers added the following line to one of the imports:

os.chdir(<path_to_a_local_folder>)

This caused the Celery worker to change its working directory from the projects' default working directory (where it could find the tasks) to a different directory (where it couldn't find the tasks).

After removing this line of code, all tasks were found and registered.

How to retrieve Jenkins build parameters using the Groovy API?

I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:

def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
  def pA = actionList.get(0)
  paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

How do I get NuGet to install/update all the packages in the packages.config?

If you Nuget 2.8 install, check the checkbox

Tools >> Nuget Manager >> Package Manager Settings >> Automatically check for missing packages during build

in Visual Studio. If it is checked, then simply rebuild the project will restore all your reference libraries.

Which terminal command to get just IP address and nothing else?

The IPv4 address for the default route:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"

The IPv6 address for the default route:

ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet6 )[^ /]+"

These only require commands ip and grep with support for -P and -o. The head -1 is required because ip route may show multiple default routes when system has complex enough network setup.

If you don't mind which IP is which, you can just do

ip route | grep -Po '(?<=src )[^ ]+'

or

hostname --all-ip-addresses

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

TypeError: Router.use() requires middleware function but got a Object

I was getting the same error message but had a different issue. Posting for others that are stuck on same.

I ported the get, post, put, delete functions to new router file while refactoring, and forgot to edit the paths. Example:

Incorrect:

//server.js
app.use('/blog-posts', blogPostsRouter);

//routers/blogPostsRouter.js
router.get('/blog-posts', (req, res) => {
  res.json(BlogPosts.get());
});

Correct:

//server.js
app.use('/blog-posts', blogPostsRouter);

//routers/blogPostsRouter.js
router.get('/', (req, res) => {
  res.json(BlogPosts.get());
});

Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

What is the difference between JavaScript and jQuery?

jQuery is a JavaScript library.

Read

wiki-jQuery, github, jQuery vs. javascript?


Source

What is JQuery?

Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:

JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.


JavaScript vs JQuery

Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.


JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.

See here.

Why does ASP.NET webforms need the Runat="Server" attribute?

Not all controls that can be included in a page must be run at the server. For example:

<INPUT type="submit" runat=server />

This is essentially the same as:

<asp:Button runat=server />

Remove the runat=server tag from the first one and you have a standard HTML button that runs in the browser. There are reasons for and against running a particular control at the server, and there is no way for ASP.NET to "assume" what you want based on the HTML markup you include. It might be possible to "infer" the runat=server for the <asp:XXX /> family of controls, but my guess is that Microsoft would consider that a hack to the markup syntax and ASP.NET engine.

Verilog generate/genvar in an always block

To put it simply, you don't use generate inside an always process, you use generate to create a parametrized process or instantiate particular modules, where you can combine if-else or case. So you can move this generate and crea a particular process or an instantiation e.g.,

module #(
parameter XLEN = 64,
parameter USEIP = 0
)
(
 input clk,
input rstn,
input [XLEN-1:0] opA,
input [XLEN-1:0] opB,
input [XLEN-1:0] opR,
input en
);

generate 
case(USEIP)
0:begin
always @(posedge clk or negedge rstn)
begin
if(!rstn)
begin
 opR <= '{default:0};
end
else
begin
if(en)
 opR <= opA+opB;
else
opR <= '{default:0};
end
end
end
1:begin
  superAdder #(.XLEN(XLEN)) _adder(.clk(clk),.rstm(rstn), .opA(opA), .opB(opB), .opR(opR), .en(en));
end
endcase

endmodule

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

MVC 4 Razor adding input type date

The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
    get { return lastStartDate; }
    set { lastStartDate = value; }
}

with

@Html.TextBoxFor(model => model.LastStartDate, 
    new { type = "date" })

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

Unlink of file Failed. Should I try again?

I solved this problem by restarting PHPStorm (insert your programm instead) as administrator

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Looks like you are using pandas dataframe (from the name df2).

You could also do the following:

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, 5].to_frame(), df2.iloc[1:1000, 2].to_frame())

NOTE: I have removed "values" as that converts the pandas Series to numpy.ndarray and numpy.ndarray does not have attribute to_frame().

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

Styling twitter bootstrap buttons

For Bootstrap (at least for version 3.1.1) and LESS, you can use this:

.btn-my-custom {
    .button-variant(@color; @background; @border)
}

This is defined in bootstrap/less/buttons.less.

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

How do I get the path and name of the file that is currently executing?

Most of these answers were written in Python version 2.x or earlier. In Python 3.x the syntax for the print function has changed to require parentheses, i.e. print().

So, this earlier high score answer from user13993 in Python 2.x:

import inspect, os
print inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory

Becomes in Python 3.x:

import inspect, os
print(inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) ) # script directory

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

1)check the package name is the same in google-services.json file

2)make sure that no other project exist with same package name

3)make sure that there is internet access

4)try syncing project and running it again

How to stop default link click behavior with jQuery

You can use e.preventDefault(); instead of e.stopPropagation();

Using Camera in the Android emulator

In your AVD advanced settings, you should be able to set front and back cameras to Webcam() or Emulated.

enter image description here

How to import other Python files?

There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py

    testString= "A string literal to import and test with"


Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.

    #!usr/bin/env python3
    Data=open('data.txt','r+').read()

Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile

    class ImportedFile:

And put this into it (with the appropriate indentation):

    exec(data)


And finally, re-assign data like so:

    data=ImportedFile()

And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.

Hope this helps:)
-Benji

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

Wamp Server not goes to green color

The above answers are very reasonable but my solution was simply to run the installer as administrator.

This is clearly stated here on the wampserver forum (2nd tip).

There are 20 other suggestions as well.

jQuery: Setting select list 'selected' based on text, failing strangely

I usually use:

$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;

MySQL JOIN with LIMIT 1 on joined table

Assuming you want product with MIN()imial value in sort column, it would look something like this.

SELECT 
  c.id, c.title, p.id AS product_id, p.title
FROM 
  categories AS c
INNER JOIN (
  SELECT
    p.id, p.category_id, p.title
  FROM
    products AS p
  CROSS JOIN (
    SELECT p.category_id, MIN(sort) AS sort
    FROM products
    GROUP BY category_id
  ) AS sq USING (category_id)
) AS p ON c.id = p.category_id

How can I hide an HTML table row <tr> so that it takes up no space?

position: absolute will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

How to save a PNG image server-side, from a base64 data string

PHP has already a fair treatment base64 -> file transform

I use to get it done using this way:

$blob=$_POST['blob']; // base64 coming from an url, for example
$blob=file_get_contents($blob);
$fh=fopen("myfile.png",'w'); // be aware, it'll overwrite!
fwrite($fh,$blob);
fclose($fh);
echo '<img src=myfile.png>'; // just for the check

Cloning a private Github repo

I needed a non-interactive method for cloning a private repo.

Inspired by this issue: https://github.com/github/hub/issues/1644

Step 1.

Create a personal access token in the github developer settings: https://github.com/settings/tokens

Step 2.

git clone https://$token:[email protected]/$username/$repo.git

Can I edit an iPad's host file?

I would imagine you could do it by setting up a transparent proxy, using something like charles and re-direct traffic that way

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

iPhone Debugging: How to resolve 'failed to get the task for process'?

Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe

Tomcat in Intellij Idea Community Edition

For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)

html select only one checkbox in a group

May this code helps you.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$('.slectOne').on('change', function() {_x000D_
   $('.slectOne').not(this).prop('checked', false);_x000D_
   $('#result').html($(this).data( "id" ));_x000D_
   if($(this).is(":checked"))_x000D_
    $('#result').html($(this).data( "id" ));_x000D_
   else_x000D_
    $('#result').html('Empty...!');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input type="checkbox" class="slectOne" data-id="1 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="2 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="3 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="4 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="5 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="6 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="7 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="8 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="9 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="10 selected"/>_x000D_
<span id="result"></span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Working link Click here

How to determine equality for two JavaScript objects?

Just wanted to contribute my version of objects comparison utilizing some es6 features. It doesn't take an order into account. After converting all if/else's to ternary I've came with following:

function areEqual(obj1, obj2) {

    return Object.keys(obj1).every(key => {

            return obj2.hasOwnProperty(key) ?
                typeof obj1[key] === 'object' ?
                    areEqual(obj1[key], obj2[key]) :
                obj1[key] === obj2[key] :
                false;

        }
    )
}

How to read a text file directly from Internet using Java?

Use this code to read an Internet resource into a String:

public static String readToString(String targetURL) throws IOException
{
    URL url = new URL(targetURL);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(url.openStream()));

    StringBuilder stringBuilder = new StringBuilder();

    String inputLine;
    while ((inputLine = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(inputLine);
        stringBuilder.append(System.lineSeparator());
    }

    bufferedReader.close();
    return stringBuilder.toString().trim();
}

This is based on here.

Convert digits into words with JavaScript

This is in response to @LordZardeck's comment to @naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.

Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.

function int_to_words(int) {
  if (int === 0) return 'zero';

  var ONES  = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
  var TENS  = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
  var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];

  // Return string of first three digits, padded with zeros if needed
  function get_first(str) {
    return ('000' + str).substr(-3);
  }

  // Return string of digits with first three digits chopped off
  function get_rest(str) {
    return str.substr(0, str.length - 3);
  }

  // Return string of triplet convereted to words
  function triplet_to_words(_3rd, _2nd, _1st) {
    return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
  }

  // Add to words, triplet words with scale word
  function add_to_words(words, triplet_words, scale_word) {
    return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
  }

  function iter(words, i, first, rest) {
    if (first == '000' && rest.length === 0) return words;
    return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
  }

  return iter('', 0, get_first(String(int)), get_rest(String(int)));
}

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

This did the trick for me:Just remove all the libraries and then compile and run. It would prompt their are errors in your project confirm. Rerun the project after applying the libraries.

imagecreatefromjpeg and similar functions are not working in PHP

sudo apt-get install phpx.x-gd 
sudo service apache2 restart

x.x is the versión php.

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

My Problem was that I was not in the correct git directory that I just cloned.

Convert a character digit to the corresponding integer in C

If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.

If you want to convert larger numbers then the following will do:

char *string = "24";

int value;

int assigned = sscanf(string, "%d", &value);

** don't forget to check the status (which should be 1 if it worked in the above case).

Paul.

Dynamically load a JavaScript file

I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:

document.write("<script src='https://www.google.com/recaptcha/api.js'></script>");

Angular directives - when and how to use compile, controller, pre-link and post-link

Compile function

Each directive's compile function is only called once, when Angular bootstraps.

Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.

Primarily, this is done for optimisation purposes; consider the following markup:

<tr ng-repeat="raw in raws">
    <my-raw></my-raw>
</tr>

The <my-raw> directive will render a particular set of DOM markup. So we can either:

  • Allow ng-repeat to duplicate the source template (<my-raw>), and then modify the markup of each instance template (outside the compile function).
  • Modify the source template to involve the desired markup (in the compile function), and then allow ng-repeat to duplicate it.

If there are 1000 items in the raws collection, the latter option may be faster than the former one.

Do:

  • Manipulate markup so it serves as a template to instances (clones).

Do not

  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

How to scroll HTML page to given anchor?

A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

demo: https://jsfiddle.net/jd7q25hg/12/

Set Culture in an ASP.Net MVC app

I would do it in the Initialize event of the controller like this...

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        const string culture = "en-US";
        CultureInfo ci = CultureInfo.GetCultureInfo(culture);

        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }

How to send and receive JSON data from a restful webservice using Jersey API

For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

java(Jax-rs) and Angular way

I hope it's helpful to someone using JAVA Rest and AngularJS like me.

@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
    JSONObject recoData = new JSONObject(data);
    //Do whatever with json object
}

Client side I used AngularJS

factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
        data= JSON.stringify(data);//Convert object to string
        var d = $q.defer();
        $http({
            method: 'POST',
            url: 'REST/webApp/update',
            headers: {'Content-Type': 'text/plain'},
            data:data
        })
        .success(function (response) {
            d.resolve(response);
        })
        .error(function (response) {
            d.reject(response);
        });

        return d.promise;
    };

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

How to symbolicate crash log Xcode?

From Apple's docs:

Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.

  • Connect an iOS device to your Mac
  • Choose "Devices" from the "Window" menu
  • Under the "DEVICES" section in the left column, choose a device
  • Click the "View Device Logs" button under the "Device Information" section on the right hand panel
  • Drag your crash report onto the left column of the presented panel
  • Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:

    1. The crashing application's binary and dSYM file.

    2. The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.

    3. Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.

If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.

What is the difference between angular-route and angular-ui-router?

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

https://github.com/angular-ui/ui-router

Transparent background on winforms?

I've tried the solutions above (and also) many other solutions from other posts.

In my case, I did it with the following setup:

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

As you can see, this is a mix of previously given answers.

How do I set the proxy to be used by the JVM

You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).

What is the largest possible heap size with a 64-bit JVM?

Windows imposes a memory limit per process, you can see what it is for each version here

See:

User-mode virtual address space for each 64-bit process; With IMAGE_FILE_LARGE_ADDRESS_AWARE set (default): x64: 8 TB Intel IPF: 7 TB 2 GB with IMAGE_FILE_LARGE_ADDRESS_AWARE cleared

How to get first N number of elements from an array

You can filter using index of array.

_x000D_
_x000D_
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
_x000D_
_x000D_

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

Posting parameters to a url using the POST method without using a form

it can be done with CURL or AJAX. The response is equally cryptic as the answer.

Origin <origin> is not allowed by Access-Control-Allow-Origin

Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"

    const express = require('express');
    const app = express();
    app.use(express.json());
    var cors = require('cors');
    app.use(cors());

How to commit a change with both "message" and "description" from the command line?

There is also another straight and more clear way

git commit -m "Title" -m "Description ..........";

How to write a stored procedure using phpmyadmin and how to use it through php?

On local server your following query will work

DELIMITER |

CREATE PROCEDURE sample_sp_with_params (IN empId INT UNSIGNED, OUT oldName VARCHAR(20), INOUT newName VARCHAR(20))

BEGIN

SELECT `first name` into oldName FROM emp where id = empId;

UPDATE emp SET `first name`= newName where id = empId;

END

|

DELIMITER ;

but on production server it might not work. depend on mysql version you are using. I had a same problem on powweb server, i removed delimiter and begin keywords, it works fine. have a look at following query

CREATE PROCEDURE adminsections( IN adminId INT UNSIGNED ) SELECT tbl_adminusersection.ads_name, tbl_adminusersection.ads_controller FROM tbl_adminusersectionright LEFT JOIN tbl_adminusersection ON ( tbl_adminusersectionright.adsr_ads_id = tbl_adminusersection.ads_id ) LEFT JOIN tbl_adminusers ON ( tbl_adminusersectionright.adsr_adusr_id = tbl_adminusers.admusr_id ) WHERE tbl_adminusers.admusr_id = adminId;

Disable time in bootstrap date time picker

Here's the solution for you. It's very easy to just add code like this:

    $('#datetimepicker4').datetimepicker({ 

    pickTime: false 

    minview:2;(Please see here.)

    }); 

Mysql: Select all data between two dates

You can use a concept that is frequently referred to as 'calendar tables'. Here is a good guide on how to create calendar tables in MySql:

-- create some infrastructure
CREATE TABLE ints (i INTEGER);
INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

-- only works for 100 days, add more ints joins for more
SELECT cal.date, tbl.data
FROM (
    SELECT '2009-06-25' + INTERVAL a.i * 10 + b.i DAY as date
    FROM ints a JOIN ints b
    ORDER BY a.i * 10 + b.i
) cal LEFT JOIN tbl ON cal.date = tbl.date
WHERE cal.date BETWEEN '2009-06-25' AND '2009-07-01';

You might want to create table cal instead of the subselect.

How to list all tags along with the full message in git?

git tag -l --format='%(contents)'

or

git for-each-ref refs/tags/ --format='%(contents)'

will output full annotation message for every tag (including signature if its signed).

  • %(contents:subject) will output only first line
  • %(contents:body) will output annotation without first line and signature (useful text only)
  • %(contents:signature) will output only PGP-signature

See more in man git-for-each-ref “Field names” section.

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

Something like:

find /path/ -type f -exec stat \{} --printf="%y\n" \; | 
     sort -n -r | 
     head -n 1

Explanation:

  • the find command will print modification time for every file recursively ignoring directories (according to the comment by IQAndreas you can't rely on the folders timestamps)
  • sort -n (numerically) -r (reverse)
  • head -n 1: get the first entry

Table and Index size in SQL Server

On SQL 2012 getting this information on a table level has become deliciously simple:

SQL Management Studio -> Right click on Db -> Reports -> Standard Reports -> Disk usage by table !

Enjoy

converting CSV/XLS to JSON?

You can try this tool I made:

Mr. Data Converter

It converts to JSON, XML and others.

It's all client side, too, so your data never leaves your computer.

Remove specific characters from a string in Javascript

If you want to remove F0 from the whole string then the replaceAll() method works for you.

_x000D_
_x000D_
const str = 'F0123F0456F0'.replaceAll('F0', '');
console.log(str);
_x000D_
_x000D_
_x000D_

Iterate over object attributes in python

For all the pythonian zealots out there I'm sure Johan Cleeze would approve of your dogmatism ;). I'm leaving this answer keep demeriting it It actually makes me more confidant. Leave a comment you chickens!

For python 3.6

class SomeClass:

    def attr_list1(self, should_print=False):

        for k in self.__dict__.keys():
            v = self.__dict__.__getitem__(k)
            if should_print:
                print(f"attr: {k}    value: {v}")

    def attr_list(self, should_print=False):

        b = [(k, v) for k, v in self.__dict__.items()]
        if should_print:
            [print(f"attr: {a[0]}    value: {a[1]}") for a in b]
        return b

Java program to find the largest & smallest number in n numbers without using arrays

public static void main(String[] args) {
    int smallest = 0;
    int large = 0;
    int num;
    System.out.println("enter the number");//how many number you want to enter
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    num = input.nextInt();
    smallest = num; //assume first entered number as small one
    // i starts from 2 because we already took one num value
    for (int i = 2; i < n; i++) {
        num = input.nextInt();
        //comparing each time entered number with large one
        if (num > large) {
            large = num;
        }
        //comparing each time entered number with smallest one
        if (num < smallest) {
            smallest = num;
        }
    }
    System.out.println("the largest is:" + large);
    System.out.println("Smallest no is : " + smallest);
}

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

How can I add numbers in a Bash script?

You should declare metab as integer and then use arithmetic evaluation

declare -i metab num
...
num+=metab
...

For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic

Understanding repr( ) function in Python

When you say

foo = 'bar'
baz(foo)

you are not passing foo to the baz function. foo is just a name used to represent a value, in this case 'bar', and that value is passed to the baz function.

Setting a backgroundImage With React Inline Styles

The curly braces inside backgroundImage property are wrong.

Probably you are using webpack along with image files loader, so Background should be already a String: backgroundImage: "url(" + Background + ")"

You can also use ES6 string templates as below to achieve the same effect:

backgroundImage: `url(${Background})`

How to run Linux commands in Java?

The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
    try {
        return execute(command, 0, null, false);
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    return execute(command, 0, null, true);
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    Process process = new ProcessBuilder().command("bash", "-c", command).start();
    if(timeUnit != null) {
        if(process.waitFor(timeout, timeUnit)) {
            if(process.exitValue() == 0) {
                return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
            } else {
                throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
            }
        } else {
            if(destroyOnTimeout) process.destroy();
            throw new ExecutionTimeoutException("Execution timed out: " + command);
        }
    } else {
        if(process.waitFor() == 0) {
            return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
        } else {
            throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
        }
    }
}

public static class ExecutionFailedException extends Exception {

    private static final long serialVersionUID = 1951044996696304510L;

    private final int exitCode;
    private final List<String> errorOutput;

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
        super(message);
        this.exitCode = exitCode;
        this.errorOutput = errorOutput;
    }

    public int getExitCode() {
        return this.exitCode;
    }

    public List<String> getErrorOutput() {
        return this.errorOutput;
    }

}

public static class ExecutionTimeoutException extends Exception {

    private static final long serialVersionUID = 4428595769718054862L;

    public ExecutionTimeoutException(final String message) {
        super(message);
    }

}

How do I access previous promise results in a .then() chain?

What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...

In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5

/**
 * Promise like object that allows to resolve it promise from outside code. Example:
 *
```
class Api {
  fooReady = new Deferred<Data>()
  private knower() {
    inOtherMoment(data=>{
      this.fooReady.resolve(data)
    })
  }
}
```
 */
var Deferred = /** @class */ (function () {
  function Deferred(callback) {
    var instance = this;
    this.resolve = null;
    this.reject = null;
    this.status = 'pending';
    this.promise = new Promise(function (resolve, reject) {
      instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
      instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
    });
    if (typeof callback === 'function') {
      callback.call(this, this.resolve, this.reject);
    }
  }
  Deferred.prototype.then = function (resolve) {
    return this.promise.then(resolve);
  };
  Deferred.prototype.catch = function (r) {
    return this.promise.catch(r);
  };
  return Deferred;
}());

transpiled form a typescript project of mine:

https://github.com/cancerberoSgx/misc-utils-of-mine/blob/2927c2477839f7b36247d054e7e50abe8a41358b/misc-utils-of-mine-generic/src/promise.ts#L31

For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:

https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I have faced this error a lot of time, also research why this error occurs and finally, I caught this error, this error a silly error which occurs when we misspelled .xib file name.

NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];

At this point, I misspelled TableViewCell as TabelViewCell , because the perception of some time we read it as correct, this is the most common problem. Just copy your .xib file name, and paste it.

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

Is this what you are looking for? Here is a fiddle demo.

The layout is based on percentage, colors are for clarity. If the content column overflows, a scrollbar should appear.

body, html, .container-fluid {
  height: 100%;
}

.navbar {
  width:100%;
  background:yellow;
}

.article-tree {
  height:100%;
  width: 25%;
  float:left;
  background: pink;
}

.content-area {
  overflow: auto;
  height: 100%;
  background:orange;
}

.footer {
   background: red;
   width:100%;
   height: 20px;
}

How to display my location on Google Maps for Android API v2

To show the "My Location" button you have to call

map.getUiSettings().setMyLocationButtonEnabled(true);

on your GoogleMap object.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode

For angular running under IIS on Windows

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode

For angular running under Node/Express

var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;

More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS

Where do I put image files, css, js, etc. in Codeigniter?

add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this

<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css"  />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

How do I install the OpenSSL libraries on Ubuntu?

sudo apt-get install libcurl4-openssl-dev

Package opencv was not found in the pkg-config search path

When you run cmake add the additional parameter -D OPENCV_GENERATE_PKGCONFIG=YES (this will generate opencv.pc file)

Then make and sudo make install as before.

Use the name opencv4 instead of just opencv Eg:-

pkg-config --modversion opencv4

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

How to use pagination on HTML tables?

Pure js. Can apply it to multiple tables at once. Aborts if only one page is required. I used anushree as my starting point.

Sorry to the asker, obviously this is not a simplePagignation.js solution. However, it's the top google result when you type "javascript table paging", and it's a reasonable solution to many who may be considering a library but unsure whether to go that route or not.

Use like this:

addPagerToTables('#someTable', 8);

Requires no css, though it may be wise to initially hide table tBody rows in css anyway to prevent the effect of rows showing then quicky being hidden (not happening with me right now, but it's something I've seen before).

The code:

function addPagerToTables(tables, rowsPerPage = 10) {

    tables = 
        typeof tables == "string"
      ? document.querySelectorAll(tables)
      : tables;

    for (let table of tables) 
        addPagerToTable(table, rowsPerPage);

}

function addPagerToTable(table, rowsPerPage = 10) {

    let tBodyRows = table.querySelectorAll('tBody tr');
    let numPages = Math.ceil(tBodyRows.length/rowsPerPage);

    let colCount = 
    [].slice.call(
        table.querySelector('tr').cells
    )
    .reduce((a,b) => a + parseInt(b.colSpan), 0);

    table
    .createTFoot()
    .insertRow()
    .innerHTML = `<td colspan=${colCount}><div class="nav"></div></td>`;

    if(numPages == 1)
        return;

    for(i = 0;i < numPages;i++) {

        let pageNum = i + 1;

        table.querySelector('.nav')
        .insertAdjacentHTML(
            'beforeend',
            `<a href="#" rel="${i}">${pageNum}</a> `        
        );

    }

    changeToPage(table, 1, rowsPerPage);

    for (let navA of table.querySelectorAll('.nav a'))
        navA.addEventListener(
            'click', 
            e => changeToPage(
                table, 
                parseInt(e.target.innerHTML), 
                rowsPerPage
            )
        );

}

function changeToPage(table, page, rowsPerPage) {

    let startItem = (page - 1) * rowsPerPage;
    let endItem = startItem + rowsPerPage;
    let navAs = table.querySelectorAll('.nav a');
    let tBodyRows = table.querySelectorAll('tBody tr');

    for (let nix = 0; nix < navAs.length; nix++) {

        if (nix == page - 1)
            navAs[nix].classList.add('active');
        else 
            navAs[nix].classList.remove('active');

        for (let trix = 0; trix < tBodyRows.length; trix++) 
            tBodyRows[trix].style.display = 
                (trix >= startItem && trix < endItem)
                ? 'table-row'
                : 'none';  

    }

}

Get latest from Git branch

Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.

Assuming the original branch is named master, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master updates into your local master:

 git fetch origin
 git checkout master
 git merge origin/master

To switch to your branch, just do

 git checkout branch1

kill -3 to get java thread dump

When using kill -3 one should see the thread dump in the standard output. Most of the application servers write the standard output to a separate file. You should find it there when using kill -3. There are multiple ways of getting thread dumps:

  • kill -3 <PID>: Gives output to standard output.
  • If one has access to the console window where server is running, one can use Ctrl+Break combination of keys to generate the stack trace on STDOUT.
  • For hotspot VM's we can also use jstack command to generate a thread dump. It’s a part of the JDK. Syntax is as follows:

    Usage:
    
    jstack [-l] <pid> (to connect to running process)
    jstack -F [-m] [-l] <pid>(to connect to a hung process)
    
     - For JRockit JVM we can use JRCMD command which comes with JDK Syntax: 
       jrcmd <jrockit pid> [<command> [<arguments>]] [-l] [-f file] [-p] -h]
    

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

Java parsing XML document gives "Content not allowed in prolog." error

I think this is also a solution of this problem.

Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'

I got resolved my problem by doing same changes.

How to convert DateTime? to DateTime

You want to use the null-coalescing operator, which is designed for exactly this purpose.

Using it you end up with this code.

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

Passing parameter to controller from route in laravel

You can add them like this

  Route::get('company/{name}', 'PublicareaController@companydetails');

How to create a numpy array of all True or all False?

>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

How can I clear console

The easiest way for me without having to reinvent the wheel.

void Clear()
{
#if defined _WIN32
    system("cls");
    //clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
    //std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences 
#elif defined (__APPLE__)
    system("clear");
#endif
}
  • On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
  • On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
    std::cout<< u8"\033[2J\033[1;1H"; 
  • On MacOS Investigating...

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

macro - open all files in a folder

Try the below code:

Sub opendfiles()

Dim myfile As Variant
Dim counter As Integer
Dim path As String

myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
    MsgBox "No files selected"
End If
While counter <= UBound(myfile)
    path = myfile(counter)
    Workbooks.Open path
    counter = counter + 1
Wend

End Sub

Insert a string at a specific index

I know this is an old thread, however, here is a really effective approach.

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");

What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.

Were you to need a string, simply access the node's text content property.

tn.textContent
#=> "I am just trying to help"

How does one set up the Visual Studio Code compiler/debugger to GCC?

Ctrl+P and Type "ext install cpptools" it will install everything you need to debug c and c++.

Debugging in VS code is very complete, but if you just need to compile and run: https://code.visualstudio.com/docs/languages/cpp

Look in the debugging section and it will explain everything

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4