Programs & Examples On #Loadoptions

"Invalid JSON primitive" in Ajax processing

Jquery Ajax will default send the data as query string parameters form like:

RecordId=456&UserId=123

unless the processData option is set to false, in which case it will sent as object to the server.

  • contentType option is for the server that in which format client has sent the data.

  • dataType option is for the server which tells that what type of data client is expecting back from the server.

Don't specify contentType so that server will parse them as query String parameters not as json.

OR

Use contentType as 'application/json; charset=utf-8' and use JSON.stringify(object) so that server would be able to deserialize json from string.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

Count number of rows matching a criteria

With dplyr package, Use

 nrow(filter(mydata, sCode == "CA")),

All the solutions provided here gave me same error as multi-sam but that one worked.

Change User Agent in UIWebView

Apple will soon stop accepting apps with UIWebView. Find below for how you could change the user agent in WKWebView.

let config = WKWebViewConfiguration()

config.applicationNameForUserAgent = "My iOS app"

webView = WKWebView(frame: <the frame you need>, configuration: config)

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Spring sets the default content-type to octet-stream when the response is missing that field. All you need to do is to add a message converter to fix this.

Java - get index of key in HashMap?

Simply put, hash-based collections aren't indexed so you have to do it manually.

Start thread with member function

Here is a complete example

#include <thread>
#include <iostream>

class Wrapper {
   public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread([=] { member1(); });
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread([=] { member2(arg1, arg2); });
      }
};
int main(int argc, char **argv) {
   Wrapper *w = new Wrapper();
   std::thread tw1 = w->member1Thread();
   std::thread tw2 = w->member2Thread("hello", 100);
   tw1.join();
   tw2.join();
   return 0;
}

Compiling with g++ produces the following result

g++ -Wall -std=c++11 hello.cc -o hello -pthread

i am member1
i am member2 and my first arg is (hello) and second arg is (100)

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

How do you disable browser Autocomplete on web form field / input tag?

In Chrome, for password type inputs, the autocomplete="new-password" is the only thing working for me.

How to generate XML file dynamically using PHP?

I'd use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

Converting Secret Key into a String and Vice Versa

Converting SecretKeySpec to String and vice-versa: you can use getEncoded() method in SecretKeySpec which will give byteArray, from that you can use encodeToString() to get string value of SecretKeySpec in Base64 object.

While converting SecretKeySpec to String: use decode() in Base64 will give byteArray, from that you can create instance for SecretKeySpec with the params as the byteArray to reproduce your SecretKeySpec.

String mAesKey_string;
SecretKeySpec mAesKey= new SecretKeySpec(secretKey.getEncoded(), "AES");

//SecretKeySpec to String 
    byte[] byteaes=mAesKey.getEncoded();
    mAesKey_string=Base64.encodeToString(byteaes,Base64.NO_WRAP);

//String to SecretKeySpec
    byte[] aesByte = Base64.decode(mAesKey_string, Base64.NO_WRAP);
    mAesKey= new SecretKeySpec(aesByte, "AES");

How to get the row number from a datatable?

You do know that DataRow is the row of a DataTable correct?

What you currently have already loop through each row. You just have to keep track of how many rows there are in order to get the current row.

int i = 0;
int index = 0;
foreach (DataRow row in dt.Rows) 
{
index = i;
// do stuff
i++;
} 

Java: notify() vs. notifyAll() all over again

However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.

That is not correct. o.notifyAll() wakes all of the threads that are blocked in o.wait() calls. The threads are only allowed to return from o.wait() one-by-one, but they each will get their turn.


Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?

In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time.

Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.


In many cases, the code to await a condition will be written as a loop:

synchronized(o) {
    while (! IsConditionTrue()) {
        o.wait();
    }
    DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}

That way, if an o.notifyAll() call wakes more than one waiting thread, and the first one to return from the o.wait() makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.

How can I use jQuery to make an input readonly?

Perhaps it's meaningful to also add that

$('#fieldName').prop('readonly',false);

can be used as a toggle option..

Finding sum of elements in Swift array

For sum of elements in array of Objects

self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)

How to store a list in a column of a database table

you can store it as text that looks like a list and create a function that can return its data as an actual list. example:

database:

 _____________________
|  word  | letters    |
|   me   | '[m, e]'   |
|  you   |'[y, o, u]' |  note that the letters column is of type 'TEXT'
|  for   |'[f, o, r]' |
|___in___|_'[i, n]'___|

And the list compiler function (written in python, but it should be easily translatable to most other programming languages). TEXT represents the text loaded from the sql table. returns list of strings from string containing list. if you want it to return ints instead of strings, make mode equal to 'int'. Likewise with 'string', 'bool', or 'float'.

def string_to_list(string, mode):
    items = []
    item = ""
    itemExpected = True
    for char in string[1:]:
        if itemExpected and char not in [']', ',', '[']:
            item += char
        elif char in [',', '[', ']']:
            itemExpected = True
            items.append(item)
            item = ""
    newItems = []
    if mode == "int":
        for i in items:
            newItems.append(int(i))

    elif mode == "float":
        for i in items:
            newItems.append(float(i))

    elif mode == "boolean":
        for i in items:
            if i in ["true", "True"]:
                newItems.append(True)
            elif i in ["false", "False"]:
                newItems.append(False)
            else:
                newItems.append(None)
    elif mode == "string":
        return items
    else:
        raise Exception("the 'mode'/second parameter of string_to_list() must be one of: 'int', 'string', 'bool', or 'float'")
    return newItems

Also here is a list-to-string function in case you need it.

def list_to_string(lst):
    string = "["
    for i in lst:
        string += str(i) + ","
    if string[-1] == ',':
        string = string[:-1] + "]"
    else:
        string += "]"
    return string

Initialize a byte array to a certain value, other than the default null?

This is a faster version of the code from the post marked as the answer.

All of the benchmarks that I have performed show that a simple for loop that only contains something like an array fill is typically twice as fast if it is decrementing versus if it is incrementing.

Also, the array Length property is already passed as the parameter so it doesn't need to be retrieved from the array properties. It should also be pre-calculated and assigned to a local variable. Loop bounds calculations that involve a property accessor will re-compute the value of the bounds before each iteration of the loop.

public static byte[] CreateSpecialByteArray(int length)
{
    byte[] array = new byte[length];

    int len = length - 1;

    for (int i = len; i >= 0; i--)
    {
        array[i] = 0x20;
    }

    return array;
}

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

    //source    
    public async Task<string> methodName()
            {
             return Data;
             }

    //Consumption
     methodName().Result;

Hope this helps :)

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

Lombok added but getters and setters not recognized in Intellij IDEA

I fixed it by following steps:

  1. Installed previous version of Idea(12.16) and start it(idea 13 was launched)
  2. then i switch on window with idea 13 (it proposed to reread some config files. I agreed and restart my IDE). And then everithing became ok with tha latest version of IDEA

Angular 2 two way binding using ngModel is not working

For newer versions of Angular:

  1. -write it as [(ngModel)] = yourSearch

  2. declare a empty variable(property) named as yourSearch in .ts file

  3. add FormsModule in app.module.ts file from - @angular/forms;

  4. if your application is running, then restart it as you made changes in its module.ts file

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

How to upload (FTP) files to server in a bash script?

You can use a heredoc to do this e.g.

ftp -n $Server <<End-Of-Session
# -n option disables auto-logon

user anonymous "$Password"
binary
cd $Directory
put "$Filename.lsm"
put "$Filename.tar.gz"
bye
End-Of-Session

so the ftp process is fed on stdin with everything up to End-Of-Session. A useful tip for spawning any process, not just ftp! Note that this saves spawning a separate process (echo, cat etc.). Not a major resource saving, but worth bearing in mind.

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

npm ERR cb() never called

sudo npm cache clean didn't work out for me. Update to the latest version of node helps.

I had node v.5.91 and updated to v6.9.1

How can I get color-int from color resource?

Based on the new Android Support Library (and this update), now you should call:

ContextCompat.getColor(context, R.color.name.color);

According to the documentation:

public int getColor (int id)

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id):

You have to change it like this:

ContextCompat.getColorStateList(getContext(),id);

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

val color = ContextCompat.getColor(
  closestView.context,
  R.color.name.color
)

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Nick Butcher - Droidcon Berlin - Developing Themes with Style

How to execute a stored procedure inside a select query

"Not Possible". You can do this using this query. Initialize here

declare @sql nvarchar(4000)=''

Set Value & exec command of your sp with parameters

SET @sql += ' Exec spName @param'
EXECUTE sp_executesql @sql,  N'@param type', @param = @param

Responsive font size in CSS

 h1 { font-size: 2.25em; } 
 h2 { font-size: 1.875em; }
 h3 { font-size: 1.5em; }
 h4 { font-size: 1.125em; }
 h5 { font-size: 0.875em; }
 h6 { font-size: 0.75em; }

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

com.sun.jdi.InvocationException occurred invoking method

Removing hashCode() and equals() solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.

Difference between ApiController and Controller in ASP.NET MVC

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}

How to get terminal's Character Encoding

To my knowledge, no.

Circumstantial indications from $LC_CTYPE, locale and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.

They only way to detect encoding for sure is to output something only present in the encoding, e.g. ä, take a screenshot, analyze that image and check if the output character is correct.

So no, it's not possible, sadly.

How to reset Jenkins security settings from the command line?

We can reset the password while leaving security on.

The config.xml file in /var/lib/Jenkins/users/admin/ acts sort of like the /etc/shadow file Linux or UNIX-like systems or the SAM file in Windows, in the sense that it stores the hash of the account's password.

If you need to reset the password without logging in, you can edit this file and replace the old hash with a new one generated from bcrypt:

$ pip install bcrypt
$ python
>>> import bcrypt
>>> bcrypt.hashpw("yourpassword", bcrypt.gensalt(rounds=10, prefix=b"2a"))
'YOUR_HASH'

This will output your hash, with prefix 2a, the correct prefix for Jenkins hashes.

Now, edit the config.xml file:

...
<passwordHash>#jbcrypt:REPLACE_THIS</passwordHash>
...

Once you insert the new hash, reset Jenkins:

(if you are on a system with systemd):

sudo systemctl restart Jenkins

You can now log in, and you didn't leave your system open for a second.

How do you revert to a specific tag in Git?

You can use git checkout.

I tried the accepted solution but got an error, warning: refname '<tagname>' is ambiguous'

But as the answer states, tags do behave like a pointer to a commit, so as you would with a commit hash, you can just checkout the tag. The only difference is you preface it with tags/:

git checkout tags/<tagname>

Python [Errno 98] Address already in use

Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

How to draw a line with matplotlib?

This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)

x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.

x2 and y2 are the same for the other line.

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.

What if I don't want line segments?

There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.

As follows:

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

What is the C++ function to raise a number to a power?

It's pow or powf in <math.h>

There is no special infix operator like in Visual Basic or Python

How to extract a floating number from a string

Another approach that may be more readable is simple type conversion. I've added a replacement function to cover instances where people may enter European decimals:

>>> for possibility in "Current Level: -13.2 db or 14,2 or 3".split():
...     try:
...         str(float(possibility.replace(',', '.')))
...     except ValueError:
...         pass
'-13.2'
'14.2'
'3.0'

This has disadvantages too however. If someone types in "1,000", this will be converted to 1. Also, it assumes that people will be inputting with whitespace between words. This is not the case with other languages, such as Chinese.

Get all column names of a DataTable into string array using (LINQ/Predicate)

Use

var arrayNames = (from DataColumn x in dt.Columns
                  select x.ColumnName).ToArray();

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

I was facing the same issue. Trying to compare a varchar(100) column with numeric 1. Resulted in the 1292 error. Fixed by adding single quotes around 1 ('1').

Thanks for the explanation above

Get size of a View in React Native

Here is the code to get the Dimensions of the complete view of the device.

var windowSize = Dimensions.get("window");

Use it like this:

width=windowSize.width,heigth=windowSize.width/0.565

How to draw circle by canvas in Android?

Here is example to draw stroke circle canvas

val paint = Paint().apply {
    color = Color.RED
    style = Paint.Style.STROKE
    strokeWidth = 10f
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Example to draw solid circle canvas

val paint = Paint().apply {
    color = Color.RED
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Hope it help

Calculate difference between 2 date / times in Oracle SQL

declare
strTime1 varchar2(50) := '02/08/2013 01:09:42 PM';
strTime2 varchar2(50) := '02/08/2013 11:09:00 PM';
v_date1 date := to_date(strTime1,'DD/MM/YYYY HH:MI:SS PM');
v_date2 date := to_date(strTime2,'DD/MM/YYYY HH:MI:SS PM');
difrence_In_Hours number;
difrence_In_minutes number;
difrence_In_seconds number;
begin
    difrence_In_Hours   := (v_date2 - v_date1) * 24;
    difrence_In_minutes := difrence_In_Hours * 60;
    difrence_In_seconds := difrence_In_minutes * 60;

    dbms_output.put_line(strTime1);        
    dbms_output.put_line(strTime2);
    dbms_output.put_line('*******');
    dbms_output.put_line('difrence_In_Hours  : ' || difrence_In_Hours);
    dbms_output.put_line('difrence_In_minutes: ' || difrence_In_minutes);
    dbms_output.put_line('difrence_In_seconds: ' || difrence_In_seconds);        
end ;

Hope this helps.

SHOW PROCESSLIST in MySQL command: sleep

It's not a query waiting for connection; it's a connection pointer waiting for the timeout to terminate.

It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does.

The really worst case: It's using one connection of your pool; If you would connect multiple times via console client and just close the client without closing the connection, you could use up all your connections and have to wait for the timeout to be able to connect again... but this is highly unlikely :-)

See MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"? and https://dba.stackexchange.com/questions/1558/how-long-is-too-long-for-mysql-connections-to-sleep for more information.

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

change image opacity using javascript

I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example.
I mean this CSS snippet should do the work for you:

img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}

Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

toggle show/hide div with button?

Pure JavaScript:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

SEE DEMO

jQuery:

$("#button").click(function() { 
    // assumes element with id='button'
    $("#newpost").toggle();
});

SEE DEMO

How can I count occurrences with groupBy?

I think you're just looking for the overload which takes another Collector to specify what to do with each group... and then Collectors.counting() to do the counting:

import java.util.*;
import java.util.stream.*;

class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Hello");
        list.add("Hello");
        list.add("World");

        Map<String, Long> counted = list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
    }
}

Result:

{Hello=2, World=1}

(There's also the possibility of using groupingByConcurrent for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)

Using unset vs. setting a variable to empty

Mostly you don't see a difference, unless you are using set -u:

/home/user1> var=""
/home/user1> echo $var

/home/user1> set -u
/home/user1> echo $var

/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable

So really, it depends on how you are going to test the variable.

I will add that my preferred way of testing if it is set is:

[[ -n $var ]]  # True if the length of $var is non-zero

or

[[ -z $var ]]  # True if zero length

Date to milliseconds and back to date in Swift

@Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:

If you don't need this precision, use the Travis solution because it will be faster.

extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}

How do I open a URL from C++?

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

For Instance:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

#ifdef _WIN32

WSACleanup();

#endif

How to get a string between two characters?

Use Pattern and Matcher

public class Chk {

    public static void main(String[] args) {

        String s = "test string (67)";
        ArrayList<String> arL = new ArrayList<String>();
        ArrayList<String> inL = new ArrayList<String>();

        Pattern pat = Pattern.compile("\\(\\w+\\)");
        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            arL.add(mat.group());
            System.out.println(mat.group());

        }

        for (String sx : arL) {

            Pattern p = Pattern.compile("(\\w+)");
            Matcher m = p.matcher(sx);

            while (m.find()) {

                inL.add(m.group());
                System.out.println(m.group());
            }
        }

        System.out.println(inL);

    }

}

http to https through .htaccess

None of these worked for me, except for this. My site was hosted in https://www.asmallorange.com

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

How to implement drop down list in flutter?

Use StatefulWidget and setState to update dropdown.

  String _dropDownValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      hint: _dropDownValue == null
          ? Text('Dropdown')
          : Text(
              _dropDownValue,
              style: TextStyle(color: Colors.blue),
            ),
      isExpanded: true,
      iconSize: 30.0,
      style: TextStyle(color: Colors.blue),
      items: ['One', 'Two', 'Three'].map(
        (val) {
          return DropdownMenuItem<String>(
            value: val,
            child: Text(val),
          );
        },
      ).toList(),
      onChanged: (val) {
        setState(
          () {
            _dropDownValue = val;
          },
        );
      },
    );
  }

initial state of dropdown:

Initial State

Open dropdown and select value:

Select Value

Reflect selected value to dropdown:

Value selected

WebView and HTML5 <video>

On honeycomb use hardwareaccelerated=true and pluginstate.on_demand seems to work

Visual Studio Code compile on save

Select Preferences -> Workspace Settings and add the following code, If you have Hot reload enabled, then the changes reflect immediately in the browser

{
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.js.map": true,
        "**/*.js": {"when": "$(basename).ts"}
    },
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000
}

Mocking methods of local scope objects with Mockito

You can do this by creating a factory method in MyObject:

class MyObject {
    public static MyObject create() {
      return new MyObject();
    }
}

then mock that with PowerMock.

However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.

In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:

void method1(MyObject obj1) {
   obj1.method1();
}

passing in the dependency, which you can easily mock for the unit test.

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

Simplest way to download and unzip files in Node.js cross-platform?

It's 2017 (October 26th, to be exact).

For an ancient and pervasive technology such as unzip I would expect there to exist a fairly popular, mature node.js unzip library that is "stagnant" and "unmaintained" because it is "complete".

However, most libraries appear either to be completely terrible or to have commits recently as just a few months ago. This is quite concerning... so I've gone through several unzip libraries, read their docs, and tried their examples to try to figure out WTF. For example, I've tried these:

Update 2020: Haven't tried it yet, but there's also archiver

Top Recommendation: yauzl

Works great for completely downloaded file. Not as great for streaming.

Well documented. Works well. Makes sense.

2nd Pick: node-stream-zip

antelle's node-stream-zip seems to be the best

Install:

npm install --save node-stream-zip

Usage:

'use strict';

var fs = require('fs');
var StreamZip = require('node-stream-zip');

var zip = new StreamZip({
  file: './example.zip'
, storeEntries: true
});

zip.on('error', function (err) { console.error('[ERROR]', err); });

zip.on('ready', function () {
  console.log('All entries read: ' + zip.entriesCount);
  //console.log(zip.entries());
});

zip.on('entry', function (entry) {
  var pathname = path.resolve('./temp', entry.name);
  if (/\.\./.test(path.relative('./temp', pathname))) {
      console.warn("[zip warn]: ignoring maliciously crafted paths in zip file:", entry.name);
      return;
  }

  if ('/' === entry.name[entry.name.length - 1]) {
    console.log('[DIR]', entry.name);
    return;
  }

  console.log('[FILE]', entry.name);
  zip.stream(entry.name, function (err, stream) {
    if (err) { console.error('Error:', err.toString()); return; }

    stream.on('error', function (err) { console.log('[ERROR]', err); return; });

    // example: print contents to screen
    //stream.pipe(process.stdout);

    // example: save contents to file
    fs.mkdir(
      path.dirname(pathname),
      { recursive: true },
      function (err) {
        stream.pipe(fs.createWriteStream(pathname));
      }
    );
  });
});

Security Warning:

Not sure if this checks entry.name for maliciously crafted paths that would resolve incorrectly (such as ../../../foo or /etc/passwd).

You can easily check this yourself by comparing /\.\./.test(path.relative('./to/dir', path.resolve('./to/dir', entry.name))).

Pros: (Why do I think it's the best?)

  • can unzip normal files (maybe not some crazy ones with weird extensions)
  • can stream
  • seems to not have to load the whole zip to read entries
  • has examples in normal JavaScript (not compiled)
  • doesn't include the kitchen sink (i.e. url loading, S3, or db layers)
  • uses some existing code from a popular library
  • doesn't have too much senseless hipster or ninja-foo in the code

Cons:

  • Swallows errors like a hungry hippo
  • Throws strings instead of errors (no stack traces)
  • zip.extract() doesn't seem to work (hence I used zip.stream() in my example)

Runner up: node-unzipper

Install:

npm install --save unzipper

Usage:

'use strict';

var fs = require('fs');
var unzipper = require('unzipper');

fs.createReadStream('./example.zip')
  .pipe(unzipper.Parse())
  .on('entry', function (entry) {
    var fileName = entry.path;
    var type = entry.type; // 'Directory' or 'File'

    console.log();
    if (/\/$/.test(fileName)) {
      console.log('[DIR]', fileName, type);
      return;
    }

    console.log('[FILE]', fileName, type);

    // TODO: probably also needs the security check

    entry.pipe(process.stdout/*fs.createWriteStream('output/path')*/);
    // NOTE: To ignore use entry.autodrain() instead of entry.pipe()
  });

Pros:

  • Seems to work in a similar manner to node-stream-zip, but less control
  • A more functional fork of unzip
  • Seems to run in serial rather than in parallel

Cons:

  • Kitchen sink much? Just includes a ton of stuff that's not related to unzipping
  • Reads the whole file (by chunk, which is fine), not just random seeks

Web Service vs WCF Service

Web Service is based on SOAP and return data in XML form. It support only HTTP protocol. It is not open source but can be consumed by any client that understands xml. It can be hosted only on IIS.

WCF is also based on SOAP and return data in XML form. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ. The main issue with WCF is, its tedious and extensive configuration. It is not open source but can be consumed by any client that understands xml. It can be hosted with in the applicaion or on IIS or using window service.

Five equal columns in twitter bootstrap

For Bootstrap 3, if you want full-width and are using LESS, SASS, or something similar, all you have to do is make use of Bootstrap's mixin functions make-md-column, make-sm-column, etc.

LESS:

.col-lg-2-4{
  .make-lg-column(2.4)
}
.col-md-2-4{
  .make-md-column(2.4)
}
.col-sm-2-4{
  .make-sm-column(2.4)
}

SASS:

.col-lg-2-4{
  @include make-lg-column(2.4)
}
.col-md-2-4{
  @include make-md-column(2.4)
}
.col-sm-2-4{
  @include make-sm-column(2.4)
}

Not only can you build true full-width bootstrap column classes using these mixins, but you can also build all the related helper classes like .col-md-push-*, .col-md-pull-*, and .col-md-offset-*:

LESS:

.col-md-push-2-4{
  .make-md-column-push(2.4)
}
.col-md-pull-2-4{
  .make-md-column-pull(2.4)
}
.col-md-offset-2-4{
  .make-md-column-offset(2.4)
}

SASS:

.col-md-push-2-4{
  @include make-md-column-push(2.4)
}
.col-md-pull-2-4{
  @include make-md-column-pull(2.4)
}
.col-md-offset-2-4{
  @include make-md-column-offset(2.4)
}

Other answers talk about setting @gridColumns which is perfectly valid, but that changes the core column width for all of bootstrap. Using the above mixin functions will add 5 column layout on top of the default bootstrap columns, so it will not break any 3rd party tools or existing styling.

How to convert QString to std::string?

One of the things you should remember when converting QString to std::string is the fact that QString is UTF-16 encoded while std::string... May have any encodings.

So the best would be either:

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

The suggested (accepted) method may work if you specify codec.

See: http://doc.qt.io/qt-5/qstring.html#toLatin1

How to add AUTO_INCREMENT to an existing column?

I managed to do this with the following code:

ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;

This is the only way I could make a column auto increment.

INT(11) shows that the maximum int length is 11, you can skip it if you want.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Convert string to Color in C#

It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:

System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Match at every second occurrence

Would something like

(pattern.*?(pattern))*

work for you?

Edit:

The problem with this is that it uses the non-greedy operator *?, which can require an awful lot of backtracking along the string instead of just looking at each letter once. What this means for you is that this could be slow for large gaps.

How to hide underbar in EditText

If you want this to affect all instances of EditText and any class that inherits from it, then you should set in your theme the value for the attribute, editTextBackground.

  <item name="android:editTextBackground">@drawable/bg_no_underline</item>

An example of the drawable I use is:

<inset xmlns:android="http://schemas.android.com/apk/res/android"
     android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
     android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
     android:insetTop="@dimen/abc_edit_text_inset_top_material"
     android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">
    <selector>
      <item android:drawable="@android:color/transparent"/>
    </selector>
</inset>

This is slightly modified version of what the default material design implementation is.

When applied it will make all your EditText remove the underline throughout the app, and you don't have to apply the style to each and every one manually.

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

How to update /etc/hosts file in Docker image during "docker build"

I think docker recently added the --add-host flag to docker build which is really great.

[Edit] So this feature was updated on 17.04.0-ce

For more detail on how to use docker build with the --add-host flag please visit: https://docs.docker.com/edge/engine/reference/commandline/build/

What's the C# equivalent to the With statement in VB?

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0:

    var bar = Stuff.Elements.Foo
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

Index all *except* one item in python

I'm going to provide a functional (immutable) way of doing it.

  1. The standard and easy way of doing it is to use slicing:

    index_to_remove = 3
    data = [*range(5)]
    new_data = data[:index_to_remove] + data[index_to_remove + 1:]
    
    print(f"data: {data}, new_data: {new_data}")
    

    Output:

    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
    
  2. Use list comprehension:

    data = [*range(5)]
    new_data = [v for i, v in enumerate(data) if i != index_to_remove]
    
    print(f"data: {data}, new_data: {new_data}") 
    

    Output:

    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
    
  3. Use filter function:

    index_to_remove = 3
    data = [*range(5)]
    new_data = [*filter(lambda i: i != index_to_remove, data)]
    

    Output:

    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
    
  4. Using masking. Masking is provided by itertools.compress function in the standard library:

    from itertools import compress
    
    index_to_remove = 3
    data = [*range(5)]
    mask = [1] * len(data)
    mask[index_to_remove] = 0
    new_data = [*compress(data, mask)]
    
    print(f"data: {data}, mask: {mask}, new_data: {new_data}")
    

    Output:

    data: [0, 1, 2, 3, 4], mask: [1, 1, 1, 0, 1], new_data: [0, 1, 2, 4]
    
  5. Use itertools.filterfalse function from Python standard library

    from itertools import filterfalse
    
    index_to_remove = 3
    data = [*range(5)]
    new_data = [*filterfalse(lambda i: i == index_to_remove, data)]
    
    print(f"data: {data}, new_data: {new_data}")
    

    Output:

    data: [0, 1, 2, 3, 4], new_data: [0, 1, 2, 4]
    

Read connection string from web.config

In VB : This should work

ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString

In C# it would be (as per comment of Ala)

ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString

jQuery UI themes and HTML tables

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

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

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

Difference between setUp() and setUpBeforeClass()

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

How To Change DataType of a DataColumn in a DataTable?

Dim tblReady1 As DataTable = tblReady.Clone()

'' convert all the columns type to String 
For Each col As DataColumn In tblReady1.Columns
  col.DataType = GetType(String)
Next

tblReady1.Load(tblReady.CreateDataReader)

Setting Action Bar title and subtitle

    <activity android:name=".yourActivity" android:label="@string/yourText" />

Put this code into your android manifest file and it should set the title of the action bar to what ever you want!

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

Converting video to HTML5 ogg / ogv and mpg4

The Miro video converter does a beautiful job and is drag-n-drop. http://www.mirovideoconverter.com/

BTW it's FREE and also very good for mobile device encoding.

cannot redeclare block scoped variable (typescript)

For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.

Just add:

export {};

at the top of your code.

Credit to EUGENE MURAVITSKY

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

What are the JavaScript KeyCodes?

I needed something like this for a game's control configuration UI, so I compiled a list for the standard US keyboard layout keycodes and mapped them to their respective key names.

Here's a fiddle that contains a map for code -> name and visi versa: http://jsfiddle.net/vWx8V/

If you want to support other key layouts you'll need to modify these maps to accommodate for them separately.

That is unless you were looking for a list of keycode values that included the control characters and other special values that are not (or are rarely) possible to input using a keyboard and may be outside of the scope of the keydown/keypress/keyup events of Javascript. Many of them are control characters or special characters like null (\0) and you most likely won't need them.

Notice that the number of keys on a full keyboard is less than many of the keycode values.

Javascript - Regex to validate date format

You could use a character class ([./-]) so that the seperators can be any of the defined characters

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

python: order a list of numbers without built-in sort, min, max function

Here is a not very efficient sorting algorithm :)

>>> data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
>>> from itertools import permutations
>>> for p in permutations(data_list):
...     if all(i<=j for i,j in zip(p,p[1:])):
...         print p
...         break
... 
(-23, -6, -5, 0, 5, 23, 23, 67)

Convert a list of characters into a string

This works in many popular languages like JavaScript and Ruby, why not in Python?

>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

Strange enough, in Python the join method is on the str class:

# this is the Python way
"".join(['a','b','c','d'])

Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).

Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.

DropDownList in MVC 4 with Razor

_x000D_
_x000D_
List<tblstatu> status = new List<tblstatu>();_x000D_
            status = psobj.getstatus();_x000D_
            model.statuslist = status;_x000D_
            model.statusid = status.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.StatusId.ToString(),_x000D_
                Text = x.StatusName_x000D_
            });_x000D_
_x000D_
_x000D_
  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
_x000D_
_x000D_

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

How to change MenuItem icon in ActionBar programmatically

Its Working

      MenuItem tourchmeMenuItem; // Declare Global .......

 public boolean onCreateOptionsMenu(Menu menu) 
 {
        getMenuInflater().inflate(R.menu.search, menu);
        menu.findItem(R.id.action_search).setVisible(false);
        tourchmeMenuItem = menu.findItem(R.id.done);
        return true;
 }

    public boolean onOptionsItemSelected(MenuItem item) {

    case R.id.done:
                       if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(false);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32));
                            }
                        }else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                mScannerView.setFlash(true);
                                LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true);
                                tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32));
                            }
                        }
                        break;

}

Where are static variables stored in C and C++?

Well this question is bit too old, but since nobody points out any useful information: Check the post by 'mohit12379' explaining the store of static variables with same name in the symbol table: http://www.geekinterview.com/question_details/24745

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

I like the Hola Soy method of not using gettimeofday(). It happened to me on a running server the admin changed the timezone. The clock was updated to show the same (correct) local value. This caused the function time() and gettimeofday() to shift 2 hours and all timestamps in some services got stuck.

Cannot implicitly convert type 'int?' to 'int'.

Check the declaration of your variable. It must be like that

public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }

I hope it is useful for you

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

Type or namespace name does not exist

I have experienced same problem with System.Data.SQLite. The source of the problem is the dll you have used should have same .NET version with your project.

For example if you have used (in my case) SQLite for .NET 4.5, your platform target should be .NET 4.5 too.

You can find platform target by: Project > (project name) Properties > Build.

Convert HTML Character Back to Text Using Java Standard Library

The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.

After a search I found a Translate class within the HTML Parser library.

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

  1. Exact ical format: http://www.ietf.org/rfc/rfc2445.txt
  2. According to the spec, it has to end in .ics

Edit: actually I'm not sure - line 6186 gives an example in .ics naming format, but it also states you can use url parameters. I don't think it matters, so long as the MIME type is correct.

Edit: Example from wikipedia: http://en.wikipedia.org/wiki/ICalendar

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR

MIME type is configured on the server.

PostgreSQL visual interface similar to phpMyAdmin?

phpPgAdmin might work for you, if you're already familiar with phpMyAdmin.

Please note that development of phpPgAdmin has moved to github per this notice but the SourceForge link above is for historical / documentation purposes.

But really there are dozens of tools that can do this.

Check if table exists without using "select from"

show tables like 'table_name'

if this returns rows > 0 the table exists

How to check if the docker engine and a docker container are running?

I have a more fleshed out example of using some of the work above in the context of a Gitea container, but it could easily be converted to another container based on the name. Also, you could probably use the docker ps --filter capability to set $GITEA_CONTAINER in a newer system or one without docker-compose in use.

# Set to name or ID of the container to be watched.
GITEA_CONTAINER=$(./bin/docker-compose ps |grep git|cut -f1 -d' ')

# Set timeout to the number of seconds you are willing to wait.
timeout=500; counter=0
# This first echo is important for keeping the output clean and not overwriting the previous line of output.
echo "Waiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
#This says that until docker inspect reports the container is in a running state, keep looping.
until [[ $(docker inspect --format '{{json .State.Running}}' $GITEA_CONTAINER) == true ]]; do

  # If we've reached the timeout period, report that and exit to prevent running an infinite loop.
  if [[ $timeout -lt $counter ]]; then
    echo "ERROR: Timed out waiting for $GITEA_CONTAINER to come up."
    exit 1
  fi

  # Every 5 seconds update the status
  if (( $counter % 5 == 0 )); then
    echo -e "\e[1A\e[KWaiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
  fi

  # Wait a second and increment the counter
  sleep 1s
  ((counter++))

done

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

How to get htaccess to work on MAMP

If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.

Does MS SQL Server's "between" include the range boundaries?

I've always used this:

WHERE myDate BETWEEN startDate AND (endDate+1)

Disable Chrome strict MIME type checking

In case you are using node.js (with express)

If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:

app.use(express.static("public"));

Where app is:

const express = require("express");
const app = express();

Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)

Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.

After you add them change the stylesheet accordingly. For example if it was:

href="cssFileName.css"

and

src="imgName.png"

Make them:

href="css/cssFileName.css"
src="css/images/imgName.png"

That should work

Update MongoDB field using value of another field

For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()

db.person.find().snapshot().forEach( function (hombre) {
    hombre.name = hombre.firstName + ' ' + hombre.lastName; 
    db.person.save(hombre); 
});

http://docs.mongodb.org/manual/reference/method/cursor.snapshot/

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

How to recursively find and list the latest modified files in a directory with subdirectories and times

For those, who faced

stat: unrecognized option: format

when executed the line from Heppo's answer (find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head)

Please try the -c key to replace --format and finally the call will be:

find $1 -type f -exec stat -c '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

That worked for me inside of some Docker containers, where stat was not able to use --format option.

PHP cURL not working - WAMP on Windows 7 64 bit

I have struggled a lot with this myself.. In the end, PHP version 5.3.1 with Apache 2.2.9 worked...

I was getting the consistent error of missing php5.dll. For this, I renamed all the old php.ini files which are not required (outside of the WAMP folder) to old_ohp.ini.

How to round each item in a list of floats to 2 decimal places?

You might want to look at Python's decimal module, which can make using floating point numbers and doing arithmetic with them a lot more intuitive. Here's a trivial example of one way of using it to "clean up" your list values:

>>> from decimal import *
>>> mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
>>> getcontext().prec = 2
>>> ["%.2f" % e for e in mylist]
['0.30', '0.50', '0.20']
>>> [Decimal("%.2f" % e) for e in mylist]
[Decimal('0.30'), Decimal('0.50'), Decimal('0.20')]
>>> data = [float(Decimal("%.2f" % e)) for e in mylist]
>>> data
[0.3, 0.5, 0.2]

ASP.NET Background image

resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...

hard-size your DIV relative to your image

position your asp:login control where needed...

How to run regasm.exe from command line other than Visual Studio command prompt?

I use the following in a batch file:

path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

SELECT
     AlarmEventTransactionTable.TxnID,
     CASE 
    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,
     AlarmEventTransactionTable.DateTimeOfTxn
FROM
     multiMAXTxn.dbo.AlarmEventTransactionTable

It is more efficient to use if-return-return or if-else-return?

I know the question is tagged python, but it mentions dynamic languages so thought I should mention that in ruby the if statement actually has a return type so you can do something like

def foo
  rv = if (A > B)
         A+1
       else
         A-1
       end
  return rv 
end

Or because it also has implicit return simply

def foo 
  if (A>B)
    A+1
  else 
    A-1
  end
end

which gets around the style issue of not having multiple returns quite nicely.

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How to serialize SqlAlchemy result to JSON?

Python 3.7+ and Flask 1.1+ can use the built-in dataclasses package

from dataclasses import dataclass
from datetime import datetime
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
db = SQLAlchemy(app)


@dataclass
class User(db.Model):
  id: int
  email: str

  id = db.Column(db.Integer, primary_key=True, auto_increment=True)
  email = db.Column(db.String(200), unique=True)


@app.route('/users/')
def users():
  users = User.query.all()
  return jsonify(users)  


if __name__ == "__main__":
  users = User(email="[email protected]"), User(email="[email protected]")
  db.create_all()
  db.session.add_all(users)
  db.session.commit()
  app.run()

The /users/ route will now return a list of users.

[
  {"email": "[email protected]", "id": 1},
  {"email": "[email protected]", "id": 2}
]

Auto-serialize related models

@dataclass
class Account(db.Model):
  id: int
  users: User

  id = db.Column(db.Integer)
  users = db.relationship(User)  # User model would need a db.ForeignKey field

The response from jsonify(account) would be this.

{  
   "id":1,
   "users":[  
      {  
         "email":"[email protected]",
         "id":1
      },
      {  
         "email":"[email protected]",
         "id":2
      }
   ]
}

Overwrite the default JSON Encoder

from flask.json import JSONEncoder


class CustomJSONEncoder(JSONEncoder):
  "Add support for serializing timedeltas"

  def default(o):
    if type(o) == datetime.timedelta:
      return str(o)
    elif type(o) == datetime.datetime:
      return o.isoformat()
    else:
      return super().default(o)

app.json_encoder = CustomJSONEncoder      

How to execute 16-bit installer on 64-bit Win7?

It took me months of googling to find a solution for this issue. You don't need to install a virtual environment running a 32-bit version of Windows to run a program with a 16-bit installer on 64-bit Windows. If the program itself is 32-bit, and just the installer is 16-bit, here's your answer.

There are ways to modify a 16-bit installation program to make it 32-bit so it will install on 64-bit Windows 7. I found the solution on this site:

http://www.reactos.org/forum/viewtopic.php?f=22&t=10988

In my case, the installation program was InstallShield 5.X. The issue was that the setup.exe program used by InstallShield 5.X is 16-bit. First I extracted the installation program contents (changed the extension from .exe to .zip, opened it and extracted). I then replaced the original 16-bit setup.exe, located in the disk1 folder, with InstallShield's 32-bit version of setup.exe (download this file from the site referenced in the above link). Then I just ran the new 32-bit setup.exe in disk1 to start the installation and my program installed and runs perfectly on 64-bit Windows.

You can also repackage this modified installation, so it can be distributed as an installation program, using a free program like Inno Setup 5.

How do I remove the last comma from a string using PHP?

It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this ini_set("mbstring.func_overload", 2);

_x000D_
_x000D_
$string = "'test1', 'test2', 'test3',";_x000D_
echo mb_substr($string, 0, -1);
_x000D_
_x000D_
_x000D_

Get list of Excel files in a folder using VBA

You can use the built-in Dir function or the FileSystemObject.

They each have their own strengths and weaknesses.

Dir Function

The Dir Function is a built-in, lightweight method to get a list of files. The benefits for using it are:

  • Easy to Use
  • Good performance (it's fast)
  • Wildcard support

The trick is to understand the difference between calling it with or without a parameter. Here is a very simple example to demonstrate:

Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)

    Dim sFile As String

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file name
    sFile = Dir(sPath & sFilter)

   'call it again until there are no more files
    Do Until sFile = ""

        Debug.Print sFile

        'subsequent calls without param return next file name
        sFile = Dir

    Loop

End Sub

If you alter any of the files inside the loop, you will get unpredictable results. It is better to read all the names into an array of strings before doing any operations on the files. Here is an example which builds on the previous one. This is a Function that returns a String Array:

Public Function GetFilesDir(ByVal sPath As String, _
    Optional ByVal sFilter As String) As String()

    'dynamic array for names
    Dim aFileNames() As String
    ReDim aFileNames(0)

    Dim sFile As String
    Dim nCounter As Long

    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If

    If sFilter = "" Then
        sFilter = "*.*"
    End If

    'call with path "initializes" the dir function and returns the first file
    sFile = Dir(sPath & sFilter)

    'call it until there is no filename returned
    Do While sFile <> ""

        'store the file name in the array
        aFileNames(nCounter) = sFile

        'subsequent calls without param return next file
        sFile = Dir

        'make sure your array is large enough for another
        nCounter = nCounter + 1
        If nCounter > UBound(aFileNames) Then
            'preserve the values and grow by reasonable amount for performance
            ReDim Preserve aFileNames(UBound(aFileNames) + 255)
        End If

    Loop

    'truncate the array to correct size
    If nCounter < UBound(aFileNames) Then
        ReDim Preserve aFileNames(0 To nCounter - 1)
    End If

    'return the array of file names
    GetFilesDir = aFileNames()

End Function

File System Object

The File System Object is a library for IO operations which supports an object-model for manipulating files. Pros for this approach:

  • Intellisense
  • Robust object-model

You can add a reference to to "Windows Script Host Object Model" (or "Windows Scripting Runtime") and declare your objects like so:

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As FileSystemObject
    Dim oFolder As Folder
    Dim oFile As File

    Set oFSO = New FileSystemObject
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub

If you don't want intellisense you can do like so without setting a reference:

Public Sub ListFilesFSO(ByVal sPath As String)

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    For Each oFile In oFolder.Files
        Debug.Print oFile.Name
    Next 'oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

End Sub

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,

then on the actual $_post's I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.

After it does whatever to the data, I run a function to clear all the $_post data for each section. you can hit refresh till your blue in the face it won't do anything but refresh the page and display.

So you just need to think logically and make it idiot proof for your users...

Uploading multiple files using formData()

This worked fine !

var fd = new FormData();

$('input[type="file"]').on('change', function (e) {
    [].forEach.call(this.files, function (file) {
        fd.append('filename[]', file);
    });
});

$.ajax({
    url: '/url/to/post/on',
    method: 'post',
    data: fd,
    contentType: false,
    processData: false,
    success: function (response) {
        console.log(response)
    },
    error: function (err) {
        console.log(err);
    }
});

How to display a range input slider vertically

_x000D_
_x000D_
window.onload = function(){
var slider = document.getElementById("sss");
 var  result = document.getElementById("final");
slider.oninput = function(){
    result.innerHTML = slider.value ;
}
}
_x000D_
.slider{
    width: 100vw;
    height: 100vh;
   
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider .container-slider{
    width: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(90deg)
}

.slider .container-slider input[type="range"]{
    width: 60%;
    -webkit-appearance: none;
    background-color: blue;
    height: 7px;
    border-radius: 5px;;
    outline: none;
    margin: 0 20px
    
}

.slider .container-slider input[type="range"]::-webkit-slider-thumb{
    -webkit-appearance: none;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: red;
}



.slider .container-slider input[type="range"]::-webkit-slider-thumb:hover{

box-shadow: 0px 0px 10px rgba(255,255,255,.3),
            0px 0px 15px rgba(255,255,255,.4),
            0px 0px 20px rgba(255,255,255,.5),
            0px 0px 25px rgba(255,255,255,.6),
            0px 0px 30px rgba(255,255,255,.7)

}


.slider .container-slider .val {
    width: 60px;
    height: 40px;
    background-color: #ACB6E5;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: consolas;
    font-weight: 700;
    font-size: 20px;
    letter-spacing: 1.3px;
    transform: rotate(-90deg)
}

.slider .container-slider .val::before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    display: block;
    border: 20px solid transparent;
    border-bottom-color: #ACB6E5;
    top: -30px;
}
_x000D_
<div class="slider">
  <div class="container-slider">
    <input type="range" min="0" max="100" step="1" value="" id="sss">
    <div class="val" id="final">0</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Bash script plugin for Eclipse?

ShellEd

Solutions below how to install ShellEd don't work for me. A lot of error on dependencies. Found solution that works for me.

System:

Linux Lubuntu 12.04

IDE:

Eclipse Kepler

In Eclipse, go to Help > Install New Software

Click Add...

Add the following Location, http://download.eclipse.org/releases/kepler, and name it "Eclipse Kepler".

Click OK.

Select the newly-created Eclipse Kepler site.

Expand the Web, XML, Java EE and OSGi Enterprise Development section at the bottom. Select WST Server Adaptors.

Click Next, and install like usual.

Restart Eclipse

Then add ShellEd repo likewise as listed above: http://sourceforge.net/projects/shelled/files/shelled/update/

And install it.

Restart Eclipse.

Also worked in Eclipse Indigo as said here: http://docs.wraithmonster.com/install-shelled

Enjoy :)

Modifying CSS class property values on the fly with JavaScript / jQuery

Why not just use a .class selector to modify the properties of every object in that class?

ie:

$('.myclass').css('color: red;');

IE prompts to open or save json result from server

Sounds like this SO question may be relevant to you:

How can I convince IE to simply display Application json rather than offer to download

If not:

Have you tried setting the dataType expected in the ajax options? i.e. dataType: 'json'

Have you tried other content types such as 'application/json' or 'text/javascript'

How to left align a fixed width string?

This version uses the str.format method.

Python 2.7 and newer

sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))

Python 2.6 version

sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))

UPDATE

Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been removed from the docs.

C# - How to convert string to char?

string[] array = {"USA", "ITLY"};
char[] element1 = array[0].ToCharArray();
// Now for element no 2
char[] element2 = array[1].ToCharArray();

How to create a timer using tkinter?

Python3 clock example using the frame.after() rather than the top level application. Also shows updating the label with a StringVar()

#!/usr/bin/env python3

# Display UTC.
# started with https://docs.python.org/3.4/library/tkinter.html#module-tkinter

import tkinter as tk
import time

def current_iso8601():
    """Get current date and time in ISO8601"""
    # https://en.wikipedia.org/wiki/ISO_8601
    # https://xkcd.com/1179/
    return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.now = tk.StringVar()
        self.time = tk.Label(self, font=('Helvetica', 24))
        self.time.pack(side="top")
        self.time["textvariable"] = self.now

        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="bottom")

        # initial time display
        self.onUpdate()

    def onUpdate(self):
        # update displayed time
        self.now.set(current_iso8601())
        # schedule timer to call myself after 1 second
        self.after(1000, self.onUpdate)

root = tk.Tk()
app = Application(master=root)
root.mainloop()

Error: allowDefinition='MachineToApplication' beyond application level

This error occurs when you attempt to open a project as a website. The easiest way to determine if you've created a website or a project is to check your solution folder (i.e. where you saved your code) and see if you have a *.sln file in the root directory, if you do then you've created a project.

Just to add, I encountered this error just now when I attempted to open a project I created a while back by selecting "File", "Open Website" from the Visual Studio menus whereas I should have selected "File", "Open Project" instead. I facepalmed as soon as I realised :)

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Checking if a variable is defined?

defined?(your_var) will work. Depending on what you're doing you can also do something like your_var.nil?

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

C# using streams

There is only one basic type of Stream. However in various circumstances some members will throw an exception when called because in that context the operation was not available.

For example a MemoryStream is simply a way to moves bytes into and out of a chunk of memory. Hence you can call Read and Write on it.

On the other hand a FileStream allows you to read or write (or both) from/to a file. Whether you can actually Read or Write depends on how the file was opened. You can't Write to a file if you only opened it for Read access.

Eloquent - where not equal to

For where field not empty this worked for me:

->where('table_name.field_name', '<>', '')

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

How do I get client IP address in ASP.NET CORE?

try this.

var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                 ipAddress = ip.ToString();
            }
        }

Axios get access to response header fields

Custom HTTP headers can not be accessed on client-side due to CORS restrictions. You need to add Access-Control-Expose-Headers setting on the server-side.

What are Access-Control-Expose-Headers?
Please go to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

By default only these HTTP headers are exposed:

  • Cache-Control
  • Content-Language
  • Content-Length
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

For custom HTTP headers, you need to customize Access-Control-Expose-Headers in response headers.

If you are using Django on the server side you can use django-cors-headers (https://pypi.org/project/django-cors-headers/) for CORS settings management.

For example, with django-cors-headers you can add a list of HTTP headers that are to be exposed to the browser by CORS_ALLOW_HEADERS setting

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
    'my-custom-header',
]

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

Seaborn plots not showing up

My advice is just to give a

plt.figure() and give some sns plot. For example

sns.distplot(data).

Though it will look it doesnt show any plot, When you maximise the figure, you will be able to see the plot.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Cannot create SSPI context

I resolved my Cannot Generate SSPI Context error by using the SQL Server Configuration Manager. Since I have SQL Server native client 10.0 on my machine, the connection to the server is trying to use named pipes (or shared memory?). Other machines could run my app with no problem. When I looked at the configuration manager, named pipes and shared memory were both enabled (good). However, under alias, the name of the computer was there with TCP forced. Since I didn't know what effect changing this would have, I changed the connection string in my program to use <servername>.<domainname> instead. Fixed.

Preserve line breaks in angularjs

Yes, I would either use the <pre> tag or use ng-bind-html-unsafe http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe (use ng-bind-html if you are using 1.2+) after using .replace() to change /n to <br />

How to build a Horizontal ListView with RecyclerView?

It's for both for Horizontal and for Vertical.

RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_recycler);
    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);

    RecyclAdapter adapter = new RecyclAdapter();

    //Vertical RecyclerView
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

    //Horizontal RecyclerView
    //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

    recyclerView.setAdapter(adapter);

}

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

jquery getting post action url

$('#signup').on("submit", function(event) {
    $form = $(this); //wrap this in jQuery

    alert('the action is: ' + $form.attr('action'));
});

Modifying list while iterating

This slice syntax makes a copy of the list and does what you want:

l  = range(100)  
for i in l[:]:  
    print i,  
    print l.pop(0),  
    print l.pop(0)

jQuery override default validation error message display (Css) Popup/Tooltip like

A few things:

First, I don't think you really need a validation error for a radio fieldset because you could just have one of the fields checked by default. Most people would rather correct something then provide something. For instance:

   Age: (*) 12 - 18 | () 19 - 30 | 31 - 50 

is more likely to be changed to the right answer as the person DOESN'T want it to go to the default. If they see it blank, they are more likely to think "none of your business" and skip it.

Second, I was able to get the effect I think you are wanting without any positioning properties. You just add padding-right to the form (or the div of the form, whatever) to provide enough room for your error and make sure your error will fit in that area. Then, you have a pre-set up css class called "error" and you set it as having a negative margin-top roughly the height of your input field and a margin-left about the distance from the left to where your padding-right should start. I tried this out, it's not great, but it works with three properties and requires no floats or absolutes:

   <style type="text/css">
    .error {
        width: 13em; /* Ensures that the div won't exceed right padding of form */
        margin-top: -1.5em;  /*Moves the div up to the same level as input */
        margin-left: 11em;   /*Moves div to the right */
        font-size: .9em;     /*Makes sure that the error div is smaller than input */
    }

   <form>
   <label for="name">Name:</label><input id="name" type="textbox" />
   <div class="error"><<< This field is required!</div>
   <label for="numb">Phone:</label><input id="numb" type="textbox" />
   <div class="error"><<< This field is required!</div>
   </form>

Java: Converting String to and from ByteBuffer and associated problems

Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)

However, the method in question (in this discussion) is a variant of encode - encode(CharBuffer in). This is a convenience method that implements the entire encoding operation. (Please see java docs reference in P.S.)

As per the docs, This method should therefore not be invoked if an encoding operation is already in progress (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).

Personally, I like to use convenience methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers.

ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:

  • Create a new encoder/decoder object when needed for each operation (not efficient as it could lead to a large number of objects). OR,
  • Use a ThreadLocal to avoid creating new encoder/decoder for each operation. OR,
  • Synchronize the entire encoding/decoding operation (this might not be preferred unless sacrificing some concurrency is ok for your program)

P.S.

java docs references:

  1. Encode (convenience) method: http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html#encode%28java.nio.CharBuffer%29
  2. General encode method: http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html#encode%28java.nio.CharBuffer,%20java.nio.ByteBuffer,%20boolean%29

Call Python function from JavaScript code

Communicating through processes

Example:

Python: This python code block should return random temperatures.

# sensor.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float
    temperatures.push(parseFloat(data));
    console.log(temperatures);
});

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

Get name of current script in Python

 def basename():
   x=__file__
   y=x.split('\\')
   y1=y[-1]
   y2=y1.split('.')
   y3=y2[0]
 return(y2[0])
  

Retrieving the text of the selected <option> in <select> element

Use the select list object, to identify its own selected options index. From there - grab the inner HTML of that index. And now you have the text string of that option.

<select onchange="alert(this.options[this.selectedIndex].innerHTML);">
       <option value="">Select Actions</option>
       <option value="1">Print PDF</option>
       <option value="2">Send Message</option>
       <option value="3">Request Review</option>
       <option value="4">Other Possible Actions</option>
    </select>

What does string::npos mean in this code?

An answer for these days of C++17, when we have std::optional:

If you squint a bit and pretend std::string::find() returns an std::optional<std::string::size_type> (which it sort of should...) - then the condition becomes:

auto position = str.find(str2);

if ( position.has_value() ) {
    std::cout << "first 'needle' found at: " << found.value() << std::endl;
}

linux find regex

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"

#1214 - The used table type doesn't support FULLTEXT indexes

Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.

Therefore either change the engine for your table to MyISAM

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Here is SQLFiddle demo

or upgrade to 5.6 and use InnoDB Full-Text Search.

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array

The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.

Good luck!

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

Terminal Commands: For loop with echo

The default shell on OS X is bash. You could write this:

for i in {1..100}; do echo http://www.example.com/${i}.jpg; done

Here is a link to the reference manual of bash concerning loop constructs.

How can I get new selection in "select" in Angular 2?

Just use [ngValue] instead of [value]!!

export class Organisation {
  description: string;
  id: string;
  name: string;
}
export class ScheduleComponent implements OnInit {
  selectedOrg: Organisation;
  orgs: Organisation[] = [];

  constructor(private organisationService: OrganisationService) {}

  get selectedOrgMod() {
    return this.selectedOrg;
  }

  set selectedOrgMod(value) {
    this.selectedOrg = value;
  }
}


<div class="form-group">
      <label for="organisation">Organisation
      <select id="organisation" class="form-control" [(ngModel)]="selectedOrgMod" required>
        <option *ngFor="let org of orgs" [ngValue]="org">{{org.name}}</option>
      </select>
      </label>
</div>

Credentials for the SQL Server Agent service are invalid

I found I had to be logged in as a domain user.

It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.

Logged in as domain user (but admin on machine) and it accepted the credentials.

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import

java.util.List;

instead of

java.awt.List;

How do I move an existing Git submodule within a Git repository?

The trick seems to be understanding that the .git directory for submodules are now kept in the master repository, under .git/modules, and each submodule has a .git file that points to it. This is the procedure you need now:

  • Move the submodule to its new home.
  • Edit the .git file in the submodule's working directory, and modify the path it contains so that it points to the right directory in the master repository's .git/modules directory.
  • Enter the master repository's .git/modules directory, and find the directory corresponding to your submodule.
  • Edit the config file, updating the worktree path so that it points to the new location of the submodule's working directory.
  • Edit the .gitmodules file in the root of the master repository, updating the path to the working directory of the submodule.
  • git add -u
  • git add <parent-of-new-submodule-directory> (It's important that you add the parent, and not the submodule directory itself.)

A few notes:

  • The [submodule "submodule-name"] lines in .gitmodules and .git/config must match each other, but don't correspond to anything else.
  • The submodule working directory and .git directory must correctly point to each other.
  • The .gitmodules and .git/config files should be synchronised.

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

Private pages for a private Github repo

There is an article with a working idea on how to request oAuth authorization before loading static content dynamically:

Securing Site That Runs on Github Pages With JSON Backend In Private Repository

Content should be stored in a secret GitHub repository with a viewer having read access to it. GitHub pages stores only the serving JS code.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

How to define relative paths in Visual Studio Project?

By default, all paths you define will be relative. The question is: relative to what? There are several options:

  1. Specifying a file or a path with nothing before it. For example: "mylib.lib". In that case, the file will be searched at the Output Directory.
  2. If you add "..\", the path will be calculated from the actual path where the .sln file resides.

Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.

How to deploy a war file in Tomcat 7

I followed the instruction in the following link, it works for me. http://www.coderanch.com/t/487178/Tomcat/war-file-show-load

  1. Stop Tomcat

  2. Delete all the logs in tomcat/logs and all files in tomcat/conf/Catalina/localhost

  3. Remove the war file and the directory it created (if it did) from tomact/webapps

  4. Start Tomcat

  5. While watching the logs, copy the war file to the webapps directory again

After this, keep an eye on the catalina.xxxx-xx-xx.log to find out the issue.

Is there a method that calculates a factorial in Java?

Short answer is: use recursion.

You can create one method and call that method right inside the same method recursively:

public class factorial {

    public static void main(String[] args) {
        System.out.println(calc(10));
    }

    public static long calc(long n) {
        if (n <= 1)
            return 1;
        else
            return n * calc(n - 1);
    }
}

How to check if mod_rewrite is enabled in php?

via command line we in centOs we can do this

httpd -l

Split a List into smaller lists of N size

List<int> orginalList =new List<int>(){1,2,3,4,5,6,7,8,9,10,12};
Dictionary<int,List<int>> dic = new Dictionary <int,List<int>> ();
int batchcount = orginalList.Count/2; //To List into two 2 parts if you 
 want three give three
List<int> lst = new List<int>();
for (int i=0;i<orginalList.Count; i++)
{
lst.Add(orginalList[i]);
if (i % batchCount == 0 && i!=0)
{
Dic.Add(threadId, lst);
lst = new List<int>();**strong text**
threadId++;
}
}
if(lst.Count>0)
Dic.Add(threadId, lst); //in case if any dayleft 
foreach(int BatchId in Dic.Keys)
{
  Console.Writeline("BatchId:"+BatchId);
  Console.Writeline('Batch Count:"+Dic[BatchId].Count);
}

How do you remove a Cookie in a Java Servlet

Cookie[] cookies = request.getCookies();
if(cookies!=null)
for (int i = 0; i < cookies.length; i++) {
 cookies[i].setMaxAge(0);
}

did that not worked? This removes all cookies if response is send back.

How do I add target="_blank" to a link within a specified div?

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}

Extract Google Drive zip from Google colab notebook

SIMPLE WAY TO CONNECT

1) You'll have to verify authentication

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()

2)To fuse google drive

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

3)To verify credentials

import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

4)Create a drive name to use it in colab ('gdrive') and check if it's working

!mkdir gdrive
!google-drive-ocamlfuse gdrive
!ls gdrive
!cd gdrive

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

In Chrome 55, prevent showing Download button for HTML 5 video

May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)

They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.

SQL multiple columns in IN clause

Ensure you have an index on your firstname and lastname columns and go with 1. This really won't have much of a performance impact at all.

EDIT: After @Dems comment regarding spamming the plan cache ,a better solution might be to create a computed column on the existing table (or a separate view) which contained a concatenated Firstname + Lastname value, thus allowing you to execute a query such as

SELECT City 
FROM User 
WHERE Fullname in (@fullnames)

where @fullnames looks a bit like "'JonDoe', 'JaneDoe'" etc

How to display image from URL on Android

You can simply use the Glide API. It avoids all the boilerplate code and the task can be achieved in two lines of code. You refer this link https://blog.mindorks.com/downloading-and-showing-image-with-glide-library-in-android. Enjoy

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

For me, I was accessing my XLS file from a network share. Moving the file for my connection manager to a local folder fixed the issue.

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

hi,that maybe the project's problem,

chose the project and setting you eclipse:

project -> clean... 

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

Is it better to use NOT or <> when comparing values?

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

<form enctype="multipart/form-data" action="post_upload.php" method="POST">

Then the key to success;

<input type="file" name="file[]" multiple />

do NOT forget those brackets! In the post_upload.php try the following:

<?php print_r($_FILES['file']['tmp_name']); ?>

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

$_FILES['file']['tmp_name'][0]

You can use php count() to count the number of files that was selected. Goodluck widdit!

Is there a way for non-root processes to bind to "privileged" ports on Linux?

The standard way is to make them "setuid" so that they start up as root, and then they throw away that root privilege as soon as they've bound to the port but before they start accepting connections to it. You can see good examples of that in the source code for Apache and INN. I'm told that Lighttpd is another good example.

Another example is Postfix, which uses multiple daemons that communicate through pipes, and only one or two of them (which do very little except accept or emit bytes) run as root and the rest run at a lower privilege.

How and where are Annotations used in Java?

Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass() ) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations). Introspection and annotations belong to what is called reflection and meta-programming.

An annotation needs to be interpreted in one way or another to be useful. Annotations can be interpreted at development-time by the IDE or the compiler, or at run-time by a framework.

Annotation processing is a very powerful mechanism and can be used in a lot of different ways:

  • to describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull
  • to describe the "nature" of an element, e.g. @Entity, @TestCase, @WebService
  • to describe the behavior of an element: @Statefull, @Transaction
  • to describe how to process the element: @Column, @XmlElement

In all cases, an annotation is used to describe the element and clarify its meaning.

Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.

Usage of annotations:

  • Documentation, e.g. XDoclet
  • Compilation
  • IDE
  • Testing framework, e.g. JUnit
  • IoC container e.g. as Spring
  • Serialization, e.g. XML
  • Aspect-oriented programming (AOP), e.g. Spring AOP
  • Application servers, e.g. EJB container, Web Service
  • Object-relational mapping (ORM), e.g. Hibernate, JPA
  • and many more...

...have a look for instance at the project Lombok, which uses annotations to define how to generate equals or hashCode methods.

Regex: ignore case sensitivity

As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'.

IGNORECASE or (?i) or /pattern/i will either generate an error or return true for every line.

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

In my situation, the Oracle 11.2 32-bit client was installed on my 64-bit Windows 2008 R2 OS.

My solution: In the Advanced Settings for the Application Pool assigned to my ASP.NET application, I set Enable 32-Bit Applications to True.

Please see below for the standalone .ashx test script that I used to test the ability to connect to Oracle. Before making the Application Pool change, its response was:

[Running as 64-bit] Connection failed.

...and after the Application Pool change:

[Running as 32-bit] Connection succeeded.

TestOracle.ashx – Script to Test an Oracle Connection via System.Data.OracleClient:

To use: Change the user, password and host variables as appropriate.

Note that this script can be used in a standalone fashion without disturbing your ASP.NET web application project file. Just drop it in your application folder.

<%@ WebHandler Language="C#" Class="Handler1" %>
<%@ Assembly Name="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" %>

using System;
using System.Data.OracleClient;
using System.Web;

public class Handler1 : IHttpHandler
{
    private static readonly string m_User = "USER";
    private static readonly string m_Password = "PASSWORD";
    private static readonly string m_Host = "HOST";

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string result = TestOracleConnection();
        context.Response.Write(result);
    }

    public bool IsReusable
    {
        get { return false; }
    }

    private string TestOracleConnection()
    {
        string result = IntPtr.Size == 8 ?
            "[Running as 64-bit]" : "[Running as 32-bit]";

        try
        {
            string connString = String.Format(
              "Data Source={0};Password={1};User ID={2};",
              m_Host, m_User, m_Password);

            OracleConnection oradb = new OracleConnection();
            oradb.ConnectionString = connString;
            oradb.Open();
            oradb.Close();
            result += " Connection succeeded.";
        }
        catch
        {
            result += " Connection failed.";
        }

        return result;
    }
}