Programs & Examples On #Wcf routing

An intermediary WCF service that acts as a message router

Git asks for username every time I push

To solve this problem, github recommends Connecting over HTTPS.

Git's documentation discuss how to how to do exactly that using gitcredentials.

Solution 1

Static configuration of usernames for a given authentication context.

https://username:<personal-access-tokens>@repository-url.com

You will find the details in the documentation.

Solution 2

Use credential helpers to cache password (in memory for a short period of time).

git config --global credential.helper cache

Solution 3

Use credential helpers to store password (indefinitely on disk).

git config --global credential.helper 'store --file ~/.my-credentials'

You can find where the credential will be saved (If not set explicitly with --file) in the documentation.

If not set explicitly with --file, there are two files where git-credential-store will search for credentials in order of precedence:

~/.git-credentials

User-specific credentials file. $XDG_CONFIG_HOME/git/credentials

Second user-specific credentials file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/credentials will be used. Any

credentials stored in this file will not be used if ~/.git-credentials has a matching credential as well. It is a good idea not to create this file if you sometimes use older versions of Git that do not support it.

P.S.

To address the concern:

your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials.

You can always encrypt the file and decrypt it before using.

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

Use of Finalize/Dispose method in C#

Pattern from msdn

public class BaseResource: IDisposable
{
   private IntPtr handle;
   private Component Components;
   private bool disposed = false;
   public BaseResource()
   {
   }
   public void Dispose()
   {
      Dispose(true);      
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing)
   {
      if(!this.disposed)
      {        
         if(disposing)
         {
            Components.Dispose();
         }         
         CloseHandle(handle);
         handle = IntPtr.Zero;
       }
      disposed = true;         
   }
   ~BaseResource()      
   {      Dispose(false);
   }
   public void DoSomething()
   {
      if(this.disposed)
      {
         throw new ObjectDisposedException();
      }
   }
}
public class MyResourceWrapper: BaseResource
{
   private ManagedResource addedManaged;
   private NativeResource addedNative;
   private bool disposed = false;
   public MyResourceWrapper()
   {
   }
   protected override void Dispose(bool disposing)
   {
      if(!this.disposed)
      {
         try
         {
            if(disposing)
            {             
               addedManaged.Dispose();         
            }
            CloseHandle(addedNative);
            this.disposed = true;
         }
         finally
         {
            base.Dispose(disposing);
         }
      }
   }
}

How can I get the count of line in a file in an efficient way?

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

Update: To answer the performance-question raised here, I made a measurement. First thing: 20.000 lines are too few, to get the program running for a noticeable time. I created a text-file with 5 million lines. This solution (started with java without parameters like -server or -XX-options) needed around 11 seconds on my box. The same with wc -l (UNIX command-line-tool to count lines), 11 seconds. The solution reading every single character and looking for '\n' needed 104 seconds, 9-10 times as much.

Strip first and last character from C string

To "remove" the 1st character point to the second character:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */

To remove the last character replace it with a '\0'.

p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */

What is <=> (the 'Spaceship' Operator) in PHP 7?

The <=> ("Spaceship") operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How can I create an Asynchronous function in Javascript?

You can use a timer:

setTimeout( yourFn, 0 );

(where yourFn is a reference to your function)

or, with Lodash:

_.defer( yourFn );

Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

Count number of occurences for each unique value

length(unique(df$col)) is the most simple way I can see.

Using pip behind a proxy with CNTLM

You can continue to use pip over HTTPS by adding your corporation's root certificate to the cacert.pem file in your site-packages/pip folder. Then configure pip to use your proxy by adding the following lines to ~/pip/pip.conf (or ~\pip\pip.ini if you're on Windows):

[global]
proxy = [user:passwd@]proxy.server:port

That's it. No need to use third party packages or give up HTTPS (of course, your network admin can still see what you're doing).

Access IP Camera in Python OpenCV

For getting the IP Camera video link:

  1. Open the IP Camera with given IP and PORT in browser
  2. Right click the video and select "copy image address"
  3. Use that address to capture video

Submit form using a button outside the <form> tag

You can tell a form that an external component from outside the <form> tag belongs to it by adding the form="yourFormName" to the definition of the component.

In this case,

<form id="login-form">
... blah...
</form>

<button type="submit" form="login-form" name="login_user" class="login-form-btn">
        <B>Autentificate</B>
</button>

... would still submit the form happily because you assigned the form name to it. The form thinks the button is part of it, even if the button is outside the tag, and this requires NO javascript to submit the form (which can be buggy i.e. form may submit but bootstrap errors / validations my fail to show, I tested).

Is it possible only to declare a variable without assigning any value in Python?

Well, if you want to check if a variable is defined or not then why not check if its in the locals() or globals() arrays? Your code rewritten:

for index in sequence:
   if 'value' not in globals() and conditionMet:
       value = index
       break

If it's a local variable you are looking for then replace globals() with locals().

Copy struct to struct in C

memcpy expects the first two arguments to be void*.

Try: memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );

P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.

Only detect click event on pseudo-element

This is not possible; pseudo-elements are not part of the DOM at all so you can't bind any events directly to them, you can only bind to their parent elements.

If you must have a click handler on the red region only, you have to make a child element, like a span, place it right after the opening <p> tag, apply styles to p span instead of p:before, and bind to it.

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

nodeJs callbacks simple example

This blog-post has a good write-up:

https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

_x000D_
_x000D_
function doHomework(subject, callback) {_x000D_
  alert(`Starting my ${subject} homework.`);_x000D_
  callback();_x000D_
}_x000D_
_x000D_
function alertFinished(){_x000D_
  alert('Finished my homework');_x000D_
}_x000D_
_x000D_
doHomework('math', alertFinished);
_x000D_
_x000D_
_x000D_

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

all i found solution for whatever you all get the exception like.. org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]..

the problem with bulid path of the jars..

To over come this problem.. place all jars in "WebContent/lib" whatever you need to in your project. i hope it will useful to you...

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

In Android O and later this error happens when you set

 android:screenOrientation="portrait"

in Manifest.

Remove that line and use

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

in your activity.

This will fix your issue.

Array versus linked-list

Arrays Vs Linked List:

  1. Array memory allocation will fail sometimes because of fragmented memory.
  2. Caching is better in Arrays as all elements are allocated contiguous memory space.
  3. Coding is more complex than Arrays.
  4. No size constraint on Linked List, unlike Arrays
  5. Insertion/Deletion is faster in Linked List and access is faster in Arrays.
  6. Linked List better from multi-threading point of view.

bootstrap 4 file input doesn't show the file name

Johann-S solution works great. (And it looks like he created the awesome plugin)

The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input

Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.

$(document).ready(function () {
  bsCustomFileInput.init()
})

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

.Contains() on a list of custom class objects

By default reference types have reference equality (i.e. two instances are only equal if they are the same object).

You need to override Object.Equals (and Object.GetHashCode to match) to implement your own equality. (And it is then good practice to implement an equality, ==, operator.)

Groovy / grails how to determine a data type?

You can use the Membership Operator isCase() which is another groovy way:

assert Date.isCase(new Date())

Why did Servlet.service() for servlet jsp throw this exception?

The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.

It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>


Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.

How to get document height and width without using jquery

You can try also:

document.body.offsetHeight
document.body.offsetWidth

How to check iOS version?

As suggested by the official Apple docs: you can use the NSFoundationVersionNumber, from the NSObjCRuntime.h header file.

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // here you go with iOS 7
}

How to append text to an existing file in Java?

If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

There are few points to note:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

Using an if statement to check if a div is empty

It depends what you mean by empty.

To check if there is no text (this allows child elements that are empty themselves):

if ($('#leftmenu').text() == '')

To check if there are no child elements or text:

if ($('#leftmenu').contents().length == 0)

Or,

if ($('#leftmenu').html() == '')

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

How do I change Bootstrap 3 column order on mobile layout?

You cannot change the order of columns in smaller screens but you can do that in large screens.

So change the order of your columns.

<!--Main Content-->
<div class="col-lg-9 col-lg-push-3">
</div>

<!--Sidebar-->
<div class="col-lg-3 col-lg-pull-9">
</div>

By default this displays the main content first.

So in mobile main content is displayed first.

By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.

Working fiddle here.

What is the single most influential book every programmer should read?

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Recommended way to get hostname in Java

InetAddress.getLocalHost().getHostName() is the more portable way.

exec("hostname") actually calls out to the operating system to execute the hostname command.

Here are a couple other related answers on SO:

EDIT: You should take a look at A.H.'s answer or Arnout Engelen's answer for details on why this might not work as expected, depending on your situation. As an answer for this person who specifically requested portable, I still think getHostName() is fine, but they bring up some good points that should be considered.

Unable to connect to SQL Server instance remotely

In addition to configuring the SQL Server Browser service in Services.msc to Automatic, and starting the service, I had to enable TCP/IP in: SQL Server Configuration Manager | SQL Server Network Configuration | Protocols for [INSTANCE NAME] | TCP/IP

enter image description here

What is the use of DesiredCapabilities in Selenium WebDriver?

Desired capabilities comes in handy while doing remote or parallel execution using selenium grid. We will be parametrizing the browser details and passing in to selenium server using desired capabilities class.

Another usage is, test automation using Appium as shown below

// Created object of DesiredCapabilities class. 
DesiredCapabilities capabilities = new DesiredCapabilities(); 
// Set android deviceName desired capability. Set your device name. 
capabilities.setCapability("deviceName", "your Device Name"); 
// Set BROWSER_NAME desired capability. 
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome"); 
// Set android VERSION desired capability. Set your mobile device's OS version. 
capabilities.setCapability(CapabilityType.VERSION, "5.1"); 
// Set android platformName desired capability. It's Android in our case here. 
capabilities.setCapability("platformName", "Android"); 

How to hash a string into 8 digits?

Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

ValueError: unconverted data remains: 02:05

Well it was very simple. I was missing the format of the date in the json file, so I should write :

st = datetime.strptime(st, '%A %d %B %H %M')

because in the json file the date was like :

"start": "Friday 06 December 02:05",

scrollable div inside container

If you put overflow: scroll on a fixed height div, the div will scroll if the contents take up too much space.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

You probably have one .OBJ or .LIB file that's targeted for x64 (that's the module machine type) while you're linking for x86 (that's the target machine type).

Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

How can I make SQL case sensitive string comparison on MySQL?

Following is for MySQL versions equal to or higher than 5.5.

Add to /etc/mysql/my.cnf

  [mysqld]
  ...
  character-set-server=utf8
  collation-server=utf8_bin
  ...

All other collations I tried seemed to be case-insensitive, only "utf8_bin" worked.

Do not forget to restart mysql after this:

   sudo service mysql restart

According to http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html there is also a "latin1_bin".

The "utf8_general_cs" was not accepted by mysql startup. (I read "_cs" as "case-sensitive" - ???).

Twitter Bootstrap 3: how to use media queries?

Here is a more modular example using LESS to mimic Bootstrap without importing the less files.

@screen-xs-max: 767px;
@screen-sm-min: 768px;
@screen-sm-max: 991px;
@screen-md-min: 992px;
@screen-md-max: 1199px;
@screen-lg-min: 1200px;

//xs only
@media(max-width: @screen-xs-max) {

}
//small and up
@media(min-width: @screen-sm-min) {

}
//sm only
@media(min-width: @screen-sm-min) and (max-width: @screen-sm-max) {

}
//md and up
@media(min-width: @screen-md-min) {

}
//md only
@media(min-width: @screen-md-min) and (max-width: @screen-md-max) {

}
//lg and up
@media(min-width: @screen-lg-min) {

}

How can I delete Docker's images?

Remove all the containers

docker ps -q -a | xargs docker rm

Force remove all the Docker images

docker rmi -f $(docker images -f dangling=true -q)

When do I need to use AtomicBoolean in Java?

There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.

public final class MyThreadSafeClass{

    private AtomicBoolean myBoolean = new AtomicBoolean(false);
    private SomeThreadSafeObject someObject = new SomeThreadSafeObject();

    public boolean doSomething(){
         someObject.doSomeWork(myBoolean);
         return myBoolean.get(); //will return true
    }
}

and in the someObject class

public final class SomeThreadSafeObject{
    public void doSomeWork(AtomicBoolean b){
        b.set(true);
    }
}

More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.

How to delete rows from a pandas DataFrame based on a conditional expression

In pandas you can do str.len with your boundary and using the Boolean result to filter it .

df[df['column name'].str.len().lt(2)]

How do I make a burn down chart in Excel?

No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.

Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.

Burndown Chart of Pages Read

sql: check if entry in table A exists in table B

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)

How can I plot with 2 different y-axes?

update: Copied material that was on the R wiki at http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes, link now broken: also available from the wayback machine

Two different y axes on the same plot

(some material originally by Daniel Rajdl 2006/03/31 15:26)

Please note that there are very few situations where it is appropriate to use two different scales on the same plot. It is very easy to mislead the viewer of the graphic. Check the following two examples and comments on this issue (example1, example2 from Junk Charts), as well as this article by Stephen Few (which concludes “I certainly cannot conclude, once and for all, that graphs with dual-scaled axes are never useful; only that I cannot think of a situation that warrants them in light of other, better solutions.”) Also see point #4 in this cartoon ...

If you are determined, the basic recipe is to create your first plot, set par(new=TRUE) to prevent R from clearing the graphics device, creating the second plot with axes=FALSE (and setting xlab and ylab to be blank – ann=FALSE should also work) and then using axis(side=4) to add a new axis on the right-hand side, and mtext(...,side=4) to add an axis label on the right-hand side. Here is an example using a little bit of made-up data:

set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000) 
par(mar = c(5, 4, 4, 4) + 0.3)  # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)

twoord.plot() in the plotrix package automates this process, as does doubleYScale() in the latticeExtra package.

Another example (adapted from an R mailing list post by Robert W. Baer):

## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)

## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)

## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="", 
   type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()

## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15,  xlab="", ylab="", ylim=c(0,7000), 
    axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4) 
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)

## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)  

## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
  text.col=c("black","red"),pch=c(16,15),col=c("black","red"))

enter image description here

Similar recipes can be used to superimpose plots of different types – bar plots, histograms, etc..

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

From Which comparator, test, bracket, or double bracket, is fastest? (http://bashcurescancer.com)

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code.

The test and single bracket are the most portable as they exist as separate and external commands. However, if your using any remotely modern version of BASH, the double bracket is supported.

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

UICollectionView Self Sizing Cells with Auto Layout

EDIT 11/19/19: For iOS 13, just use UICollectionViewCompositionalLayout with estimated heights. Don't waste your time dealing with this broken API.

After struggling with this for some time, I noticed that resizing does not work for UITextViews if you don't disable scrolling:

let textView = UITextView()
textView.scrollEnabled = false

Using sed, how do you print the first 'N' characters of a line?

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Connect to SQL Server database from Node.js

This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.

At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.

"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.

On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.

If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE

Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js

Just in case, if the above links are not working, I am including the source code here:

_x000D_
_x000D_
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
    server: "localhost\\SQL2K14",_x000D_
    database: "SampleDb",_x000D_
    user: "sa",_x000D_
    password: "sql2014",_x000D_
    port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
    var conn = new sql.Connection(dbConfig);_x000D_
    _x000D_
    conn.connect().then(function () {_x000D_
        var req = new sql.Request(conn);_x000D_
        req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
            console.log(recordset);_x000D_
            conn.close();_x000D_
        })_x000D_
        .catch(function (err) {_x000D_
            console.log(err);_x000D_
            conn.close();_x000D_
        });        _x000D_
    })_x000D_
    .catch(function (err) {_x000D_
        console.log(err);_x000D_
    });_x000D_
_x000D_
    //--> another way_x000D_
    //var req = new sql.Request(conn);_x000D_
    //conn.connect(function (err) {_x000D_
    //    if (err) {_x000D_
    //        console.log(err);_x000D_
    //        return;_x000D_
    //    }_x000D_
    //    req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
    //        if (err) {_x000D_
    //            console.log(err);_x000D_
    //        }_x000D_
    //        else { _x000D_
    //            console.log(recordset);_x000D_
    //        }_x000D_
    //        conn.close();_x000D_
    //    });_x000D_
    //});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
_x000D_
_x000D_

The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.

The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql

UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)

Form inside a form, is that alright?

It's not valid XHTML to have to have nested forms. However, you can use multiple submit buttons and use a serverside script to run different codes depending on which button the users has clicked.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

After further reading, and confirmation from Linus G Thiel above, I found I simply had to,

  • Downgrade to Node.js 0.6.12
  • And either,
    • Install Mocha as global
    • Add ./node_modules/.bin to my PATH

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Static variables in JavaScript

To condense all class concepts here, test this:

var Test = function() {
  // "super private" variable, accessible only here in constructor. There are no real private variables
  //if as 'private' we intend variables accessible only by the class that defines the member and NOT by child classes
  var test_var = "super private";

  //the only way to access the "super private" test_var is from here
  this.privileged = function(){
    console.log(test_var);
  }();

  Test.test_var = 'protected';//protected variable: accessible only form inherited methods (prototype) AND child/inherited classes

  this.init();
};//end constructor

Test.test_var = "static";//static variable: accessible everywhere (I mean, even out of prototype, see domready below)

Test.prototype = {

 init:function(){
   console.log('in',Test.test_var);
 }

};//end prototype/class


//for example:
$(document).ready(function() {

 console.log('out',Test.test_var);

 var Jake = function(){}

 Jake.prototype = new Test();

 Jake.prototype.test = function(){
   console.log('jake', Test.test_var);
 }

 var jake = new Jake();

 jake.test();//output: "protected"

});//end domready

Well, another way to take a look to best practices in these things, is to just see how coffeescript translates these concepts.

#this is coffeescript
class Test
 #static
 @prop = "static"

 #instance
 constructor:(prop) ->
   @prop = prop
   console.log(@prop)

 t = new Test('inst_prop');

 console.log(Test.prop);


//this is how the above is translated in plain js by the CS compiler
  Test = (function() {
    Test.prop = "static";

    function Test(prop) {
     this.prop = prop;
     console.log(this.prop);
    }

    return Test;

  })();

  t = new Test('inst_prop');

  console.log(Test.prop);

Add empty columns to a dataframe with specified names from a vector

Maybe

df <- do.call("cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector

Python error when trying to access list by index - "List indices must be integers, not str"

player['score'] is your problem. player is apparently a list which means that there is no 'score' element. Instead you would do something like:

name, score = player[0], player[1]
return name + ' ' + str(score)

Of course, you would have to know the list indices (those are the 0 and 1 in my example).

Something like player['score'] is allowed in python, but player would have to be a dict.

You can read more about both lists and dicts in the python documentation.

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

I'm sorry to say, but the time discontinuity has moved a bit in

JDK 6 two years ago, and in JDK 7 just recently in update 25.

Lesson to learn: avoid non-UTC times at all costs, except maybe for display.

How do I set the driver's python version in spark?

I had the same problem, just forgot to activate my virtual environment. For anyone out there who also had a mental blank.

C# code to validate email address

  1. In a "try block" send a verification email.
  2. Make the user open the email and click a link verifying the email is real.

Until this process completes successfully, the email is assumed to be invalid.

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

You should first take a look at this. This explains what happens when you import a package. For convenience:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package.

So PyCharm respects this by showing a warning message, so that the author can decide which of the modules get imported when * from the package is imported. Thus this seems to be useful feature of PyCharm (and in no way can it be called a bug, I presume). You can easily remove this warning by adding the names of the modules to be imported when your package is imported in the __all__ variable which is list, like this

__init__.py

from . import MyModule1, MyModule2, MyModule3
__all__ = [MyModule1, MyModule2, MyModule3]

After you add this, you can ctrl+click on these module names used in any other part of your project to directly jump to the declaration, which I often find very useful.

JavaScript for detecting browser language preference

There is no decent way to get that setting, at least not something browser independent.

But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)

So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader

What is the reason for a red exclamation mark next to my project in Eclipse?

My problem concerning exclamation mark was in the section: "right click on project folder" - Properties - Libraries tab. There was an Error marked in red on a libray that probably wasn't in the right place so I removed it and ex. mark disappeared. The problem raised after deleting some old projects.

Fetch first element which matches criteria

I think this is the best way:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);

How do I create delegates in Objective-C?

Here is a simple method to create delegates

Create Protocol in .h file. Make sure that is defined before the protocol using @class followed by the name of the UIViewController < As the protocol I am going to use is UIViewController class>.

Step : 1 : Create a new class Protocol named "YourViewController" which will be the subclass of UIViewController class and assign this class to the second ViewController.

Step : 2 : Go to the "YourViewController" file and modify it as below:

#import <UIKit/UIkit.h>
@class YourViewController;

@protocol YourViewController Delegate <NSObject>

 @optional
-(void)defineDelegateMethodName: (YourViewController *) controller;

@required
-(BOOL)delegateMethodReturningBool: (YourViewController *) controller;

  @end
  @interface YourViewController : UIViewController

  //Since the property for the protocol could be of any class, then it will be marked as a type of id.

  @property (nonatomic, weak) id< YourViewController Delegate> delegate;

@end

The methods defined in the protocol behavior can be controlled with @optional and @required as part of the protocol definition.

Step : 3 : Implementation of Delegate

    #import "delegate.h"

   @interface YourDelegateUser ()
     <YourViewControllerDelegate>
   @end

   @implementation YourDelegateUser

   - (void) variousFoo {
      YourViewController *controller = [[YourViewController alloc] init];
      controller.delegate = self;
   }

   -(void)defineDelegateMethodName: (YourViewController *) controller {
      // handle the delegate being called here
   }

   -(BOOL)delegateMethodReturningBool: (YourViewController *) controller {
      // handle the delegate being called here
      return YES;
   }

   @end

//test whether the method has been defined before you call it

 - (void) someMethodToCallDelegate {
     if ([[self delegate] respondsToSelector:@selector(defineDelegateMethodName:)]) {
           [self.delegate delegateMethodName:self]; 
     }
  }

Filtering Table rows using Jquery

I used Beetroot-Betroot's solution, but instead of using contains, I used containsNC, which makes it case insensitive.

$.extend($.expr[":"], {
"containsNC": function(elem, i, match, array) {
return (elem.textContent || elem.innerText ||
"").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});

Background images: how to fill whole div if image is small and vice versa

This will work like a charm.

background-image:url("http://assets.toptal.io/uploads/blog/category/logo/4/php.png");
background-repeat: no-repeat;
background-size: contain;

Finding the index of an item in a list

Let’s give the name lst to the list that you have. One can convert the list lst to a numpy array. And, then use numpy.where to get the index of the chosen item in the list. Following is the way in which you will implement it.

import numpy as np

lst = ["foo", "bar", "baz"]  #lst: : 'list' data type
print np.where( np.array(lst) == 'bar')[0][0]

>>> 1

Difference between git pull and git pull --rebase

In the very most simple case of no collisions

  • with rebase: rebases your local commits ontop of remote HEAD and does not create a merge/merge commit
  • without/normal: merges and creates a merge commit

See also:

man git-pull

More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.

See also:
When should I use git pull --rebase?
http://git-scm.com/book/en/Git-Branching-Rebasing

Call js-function using JQuery timer

jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.

$('#foo').slideUp(300).delay(800).fadeIn(400);

http://api.jquery.com/delay/

Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

C# LINQ select from list

Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method

Split List into Sublists with LINQ

If the list is of type system.collections.generic you can use the "CopyTo" method available to copy elements of your array to other sub arrays. You specify the start element and number of elements to copy.

You could also make 3 clones of your original list and use the "RemoveRange" on each list to shrink the list to the size you want.

Or just create a helper method to do it for you.

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

What is the Python equivalent of static variables inside a function?

Soulution n +=1

def foo():
  foo.__dict__.setdefault('count', 0)
  foo.count += 1
  return foo.count

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Search for value in DataGridView in a column

It's better also to separate your logic in another method, or maybe in another class.

This method will help you retreive the DataGridViewCell object in which the text was found.

    /// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }

How do I ignore files in a directory in Git?

PATTERN FORMAT

  • A blank line matches no files, so it can serve as a separator for readability.

  • A line starting with # serves as a comment.

  • An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

  • If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

  • If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

  • Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, Documentation/*.html matches Documentation/git.html but not Documentation/ppc/ppc.html or tools/perf/Documentation/perf.html.

  • A leading slash matches the beginning of the pathname. For example, /*.c matches cat-file.c but not mozilla-sha1/sha1.c.

You can find more here

git help gitignore
or
man gitignore

Chart.js canvas resize

 let canvasBox = ReactDOM.findDOMNode(this.refs.canvasBox);
 let width = canvasBox.clientWidth;
 let height = canvasBox.clientHeight;
 let charts = ReactDOM.findDOMNode(this.refs.charts);
 let ctx = charts.getContext('2d');
 ctx.canvas.width = width;
 ctx.canvas.height = height;
 this.myChart = new Chart(ctx);

return in for loop or outside loop

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

Extend a java class from one file in another java file

Just put the two files in the same directory. Here's an example:

Person.java

public class Person {
  public String name;

  public Person(String name) {
    this.name = name;
  }

  public String toString() {
    return name;
  }
}

Student.java

public class Student extends Person {
  public String somethingnew;

  public Student(String name) {
    super(name);
    somethingnew = "surprise!";
  }

  public String toString() {
    return super.toString() + "\t" + somethingnew;
  }

  public static void main(String[] args) {
    Person you = new Person("foo");
    Student me = new Student("boo");

    System.out.println("Your name is " + you);
    System.out.println("My name is " + me);
  }
}

Running Student (since it has the main function) yields us the desired outcome:

Your name is foo
My name is boo  surprise!

How to completely hide the navigation bar in iPhone / HTML5

Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":

Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:

window.scrollTo(0, 1); 

However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.

You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/

I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:

setTimeout(function () {   window.scrollTo(0, 1); }, 1000);

However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):

/mobile/i.test(navigator.userAgent) && setTimeout(function
() {   window.scrollTo(0, 1); }, 1000); 

The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):

/mobile/i.test(navigator.userAgent) && !location.hash &&
setTimeout(function () {   window.scrollTo(0, 1); }, 1000);?

Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.

Convert Pixels to Points

There are 72 points per inch; if it is sufficient to assume 96 pixels per inch, the formula is rather simple:

points = pixels * 72 / 96

There is a way to get the configured pixels per inch of your display in Windows using GetDeviceCaps. Microsoft has a guide called "Developing DPI-Aware Applications", look for the section "Creating DPI-Aware Fonts".

The W3C has defined the pixel measurement px as exactly 1/96th of 1in regardless of the actual resolution of your display, so the above formula should be good for all web work.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Open soft keyboard programmatically

This works:

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

And you call this method like this:

showKeyboard(NameOfActivity.this);

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

Python creating a dictionary of lists

easy way is:

a = [1,2]
d = {}
for i in a:
  d[i]=[i, ]

print(d)
{'1': [1, ], '2':[2, ]}

gradient descent using python and numpy

Below you can find my implementation of gradient descent for linear regression problem.

At first, you calculate gradient like X.T * (X * w - y) / N and update your current theta with this gradient simultaneously.

  • X: feature matrix
  • y: target values
  • w: weights/values
  • N: size of training set

Here is the python code:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random

def generateSample(N, variance=100):
    X = np.matrix(range(N)).T + 1
    Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
    return X, Y

def fitModel_gradient(x, y):
    N = len(x)
    w = np.zeros((x.shape[1], 1))
    eta = 0.0001

    maxIteration = 100000
    for i in range(maxIteration):
        error = x * w - y
        gradient = x.T * error / N
        w = w - eta * gradient
    return w

def plotModel(x, y, w):
    plt.plot(x[:,1], y, "x")
    plt.plot(x[:,1], x * w, "r-")
    plt.show()

def test(N, variance, modelFunction):
    X, Y = generateSample(N, variance)
    X = np.hstack([np.matrix(np.ones(len(X))).T, X])
    w = modelFunction(X, Y)
    plotModel(X, Y, w)


test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)

test1 test2 test2

SQL Server - SELECT FROM stored procedure

It is not necessary use a temporary table.

This is my solution

SELECT  *  FROM    
OPENQUERY(YOURSERVERNAME, 'EXEC MyProc @parameters')
WHERE somefield = anyvalue

Determining whether an object is a member of a collection in VBA

I did it like this, a variation on Vadims code but to me a bit more readable:

' Returns TRUE if item is already contained in collection, otherwise FALSE

Public Function Contains(col As Collection, item As String) As Boolean

    Dim i As Integer

    For i = 1 To col.Count

    If col.item(i) = item Then
        Contains = True
        Exit Function
    End If

    Next i

    Contains = False

End Function

Editing the git commit message in GitHub

GitHub's instructions for doing this:

  1. On the command line, navigate to the repository that contains the commit you want to amend.
  2. Type git commit --amend and press Enter.
  3. In your text editor, edit the commit message and save the commit.
  4. Use the git push --force example-branch command to force push over the old commit.

Source: https://help.github.com/articles/changing-a-commit-message/

How to import an existing project from GitHub into Android Studio

Steps:

  1. Download the Zip from the website or clone from Github Desktop. Don't use VCS in android studio.
  2. (Optional)Copy the folder extracted into your AndroidStudioProjects folder which must contain the hidden .git folder.
  3. Open Android Studio-> File-> Open-> Select android directory.
  4. If it's a Eclipse project then convert it to gradle(Provided by Android Studio). Otherwise, it's done.

Specify JDK for Maven to use

So bottom line is, is there a way to specify a jdk for a single invocation of maven?

Temporarily change the value of your JAVA_HOME environment variable.

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

As mentioned in some answers, there is the ability to create an exception class for each HTTP status that you want to return. I don't like the idea of having to create a class per status for each project. Here is what I came up with instead.

  • Create a generic exception that accepts an HTTP status
  • Create an Controller Advice exception handler

Let's get to the code

package com.javaninja.cam.exception;

import org.springframework.http.HttpStatus;


/**
 * The exception used to return a status and a message to the calling system.
 * @author norrisshelton
 */
@SuppressWarnings("ClassWithoutNoArgConstructor")
public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    /**
     * Gets the HTTP status code to be returned to the calling system.
     * @return http status code.  Defaults to HttpStatus.INTERNAL_SERVER_ERROR (500).
     * @see HttpStatus
     */
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified HttpStatus code and detail message.
     * The cause is not initialized, and may subsequently be initialized by a call to {@link #initCause}.
     * @param httpStatus the http status.  The detail message is saved for later retrieval by the {@link
     *                   #getHttpStatus()} method.
     * @param message    the detail message. The detail message is saved for later retrieval by the {@link
     *                   #getMessage()} method.
     * @see HttpStatus
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then I create a controller advice class

package com.javaninja.cam.spring;


import com.javaninja.cam.exception.ResourceException;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;


/**
 * Exception handler advice class for all SpringMVC controllers.
 * @author norrisshelton
 * @see org.springframework.web.bind.annotation.ControllerAdvice
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    /**
     * Handles ResourceExceptions for the SpringMVC controllers.
     * @param e SpringMVC controller exception.
     * @return http response entity
     * @see ExceptionHandler
     */
    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }
}

To use it

throw new ResourceException(HttpStatus.BAD_REQUEST, "My message");

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

Set LIMIT with doctrine 2?

$query_ids = $this->getEntityManager()
      ->createQuery(
        "SELECT e_.id
        FROM MuzichCoreBundle:Element e_
        WHERE [...]
        GROUP BY e_.id")
     ->setMaxResults(5)
     ->setMaxResults($limit) 
    ;

HERE in the second query the result of the first query should be passed ..

$query_select = "SELECT e
      FROM MuzichCoreBundle:Element e 
      WHERE e.id IN (".$query_ids->getResult().")
      ORDER BY e.created DESC, e.name DESC"
    ;


$query = $this->getEntityManager()
      ->createQuery($query_select)
      ->setParameters($params)
      ->setMaxResults($limit);
    ;

$resultCollection = $query->getResult();

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

Load different application.yml in SpringBoot Test

You can set your test properties in src/test/resources/config/application.yml file. Spring Boot test cases will take properties from application.yml file in test directory.

The config folder is predefined in Spring Boot.

As per documentation:

If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

The same works for application.yml

Documentation:

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

The 'Access-Control-Allow-Origin' header contains multiple values

Add to Register WebApiConfig

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Or web.config

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>  
</httpProtocol>

BUT NOT BOTH

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

How can I prevent a window from being resized with tkinter?

This code makes a window with the conditions that the user cannot change the dimensions of the Tk() window, and also disables the maximise button.

import tkinter as tk

root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()

Within the program you can change the window dimensions with @Carpetsmoker's answer, or by doing this:

root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))

It should be fairly easy for you to implement that into your code. :)

Align DIV's to bottom or baseline

Seven years later searches for vertical alignment still bring up this question, so I'll post another solution we have available to us now: flexbox positioning. Just set display:flex; justify-content: flex-end; flex-direction: column on the parent div (demonstrated in this fiddle as well):

#parentDiv
{
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
  width:300px;
  height:300px;
  background-color:#ccc;
  background-repeat:repeat
}

How to evaluate a math expression given in string form?

With JDK1.6, you can use the built-in Javascript engine.

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Test {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String foo = "40+2";
    System.out.println(engine.eval(foo));
    } 
}

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

Passing a variable from node.js to html

I found the possible way to write.

Server Side -

app.get('/main', function(req, res) {

  var name = 'hello';

  res.render(__dirname + "/views/layouts/main.html", {name:name});

});

Client side (main.html) -

<h1><%= name %></h1>

How to tell if UIViewController's view is visible

Here's @progrmr's solution as a UIViewController category:

// UIViewController+Additions.h

@interface UIViewController (Additions)

- (BOOL)isVisible;

@end


// UIViewController+Additions.m

#import "UIViewController+Additions.h"

@implementation UIViewController (Additions)

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

@end

How to build splash screen in windows forms application?

create splash

private void timer1_Tick(object sender, EventArgs e)
{
    counter++;
    progressBar1.Value = counter *5;
    // label2.Text = (5*counter).ToString();
    if (counter ==20)
    {
        timer1.Stop();
        this.Close();
    }
}
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.GradientInactiveCaption;
this.ClientSize = new System.Drawing.Size(397, 283);
this.ControlBox = false;
this.Controls.Add(this.label2);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.label1);
this.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Splash";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();

Then in your application

sp = new Splash();
sp.ShowDialog();

HintPath vs ReferencePath in Visual Studio

According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/

There is a search order for assemblies when building. The search order is as follows:

  • Files from the current project – indicated by ${CandidateAssemblyFiles}.
  • $(ReferencePath) property that comes from .user/targets file.
  • %(HintPath) metadata indicated by reference item.
  • Target framework directory.
  • Directories found in registry that uses AssemblyFoldersEx Registration.
  • Registered assembly folders, indicated by ${AssemblyFolders}.
  • $(OutputPath) or $(OutDir)
  • GAC

So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.

set dropdown value by text using jquery

The below code works for me -:

jQuery('[id^=select_] > option').each(function(){
        if (this.text.toLowerCase()=='text'){
            jQuery('[id^=select_]').val(this.value);
        }
});

jQuery('[id^=select_]') - This allows you to select drop down where ID of the drop down starts from select_

Hope the above helps!

Cheers S

Runtime vs. Compile time

I think of it in terms of errors, and when they can be caught.

Compile time:

string my_value = Console.ReadLine();
int i = my_value;

A string value can't be assigned a variable of type int, so the compiler knows for sure at compile time that this code has a problem

Run time:

string my_value = Console.ReadLine();
int i = int.Parse(my_value);

Here the outcome depends on what string was returned by ReadLine(). Some values can be parsed to an int, others can't. This can only be determined at run time

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

In any case, your code will generate invalid markup: You shouldn't wrap block contents in a link. tags don't work like this. If you want this effect you should use js or create an absolutely positioned link above the content (z-index). More on this here: Make a div into a link.

You should make sure to validate your code when it renders: http://validator.w3.org

Error inflating class android.support.design.widget.NavigationView

For me, I encountered this error many times,

Error inflating class android.support.design.widget.NavigationView #28 and #29

The solution that works for me is that you must match your support design library and your support appcompat library.

compile 'com.android.support:appcompat-v7:23.1.1'

compile 'com.android.support:design:23.1.1'

For me they must match. :) It works for me!

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Use stopPropagation method, see an example:

$("#clickable a").click(function(e) {
   e.stopPropagation();
});

As said by jQuery Docs:

stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.

Test iOS app on device without apple developer program or jailbreak

With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:

enter image description here

Check it out here.

Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.

I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.


UPDATE:

Some people are having problems with iOS 8.4, here is how to fix it.

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

Move an array element from one array position to another

let ar = ['a', 'b', 'c', 'd'];

function change( old_array, old_index , new_index ){

  return old_array.map(( item , index, array )=>{
    if( index === old_index ) return array[ new_index ];
    else if( index === new_index ) return array[ old_index ];
    else return item;
  });

}

let result = change( ar, 0, 1 );

console.log( result );

result:

["b", "a", "c", "d"]

Eclipse Java error: This selection cannot be launched and there are no recent launches

Have you checked if:

  1. You created a class file under src folder in your JAVA project?(not file)
  2. Did you name your class as the same name of your class file?

I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.

SQLite Reset Primary Key Field

If you want to reset every RowId via content provider try this

rowCounter=1;
do {            
            rowId = cursor.getInt(0);
            ContentValues values;
            values = new ContentValues();
            values.put(Table_Health.COLUMN_ID,
                       rowCounter);
            updateData2DB(context, values, rowId);
            rowCounter++;

        while (cursor.moveToNext());

public static void updateData2DB(Context context, ContentValues values, int rowId) {
    Uri uri;
    uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
    context.getContentResolver().update(uri, values, null, null);
}

Anaconda / Python: Change Anaconda Prompt User Path

Go to Start and search for "Anaconda Prompt" - right click this and choose "Open File Location", which will open a folder of shortcuts. Right click the "Anaconda Prompt" shortcut, choose "Properties" and you can adjust the starting dir in the "Start in" box.

Get mouse wheel events in jQuery?

?$(document).ready(function(){
    $('#foo').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta /120 > 0) {
            console.log('scrolling up !');
        }
        else{
            console.log('scrolling down !');
        }
    });
});

Use '=' or LIKE to compare strings in SQL?

There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:

declare @transid varchar(15)

if @transid != 0

will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.

Converting VS2012 Solution to VS2010

I also faced the similar problem. I googled but couldn't find the solution. So I tried on my own and here is my solution.

Open you solution file in notepad. Make 2 changes

  1. Replace "Format Version 12.00" with "Format Version 11.00" (without quotes.)
  2. Replace "# Visual Studio 2012" with "# Visual Studio 2010" (without quotes.)

Hope this helps u as well..........

How we can bold only the name in table td tag not the value

Wrap the name in a span, give it a class and assign a style to that class:

<td><span class="names">Name text you want bold</span> rest of your text</td>

style:

.names { font-weight: bold; }

Spark read file from S3 using sc.textFile ("s3n://...)

You can add the --packages parameter with the appropriate jar: to your submission:

bin/spark-submit --packages com.amazonaws:aws-java-sdk-pom:1.10.34,org.apache.hadoop:hadoop-aws:2.6.0 code.py

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

This can also happen if you had used require instead of import within your code.

What is the best IDE for PHP?

What features of an IDE do you want? Integrated build engine? Debugger? Code highlighting? IntelliSense? Project management? Configuration management? Testing tools? Except for code highlighting, none of these are in your requirements.

So my suggestion is to use an editor that supports plugins, like Notepad++ (which you are already used to). If there's not already a plugin that does what you want, then write one.

I use Coda on Mac OS X.

Set The Window Position of an application via command line

You can use nircmd project here: http://www.nirsoft.net/utils/nircmd.html

Example code:

nircmd win move ititle "cmd.exe" 5 5 10 10
nircmd win setsize ititle "cmd.exe" 30 30 100 200
nircmd cmdwait 1000 win setsize ititle "cmd.exe" 30 30 1000 600

Kotlin Ternary Conditional Operator

fun max(x:Int,y:Int) : String = if (x>y) "max = $x" else "max = $y"

inline funcation

Changing project port number in Visual Studio 2013

There are two project types in VS for ASP.NET projects:

Web Application Projects (which notably have a .csproj or .vbproj file to store these settings) have a Properties node under the project. On the Web tab, you can configure the Project URL (assuming IIS Express or IIS) to use whatever port you want, and just click the Create Virtual Directory button. These settings are saved to the project file:

<ProjectExtensions>
  <VisualStudio>
    <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
      <WebProjectProperties>
       <DevelopmentServerPort>10531</DevelopmentServerPort>
       ...
     </WebProjectProperties>
    </FlavorProperties>
  </VisualStudio>
</ProjectExtensions>

Web Site Projects are different. They don't have a .*proj file to store settings in; instead, the settings are set in the solution file. In VS2013, the settings look something like this:

Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "WebSite1(1)", "http://localhost:10528", "{401397AC-86F6-4661-A71B-67B4F8A3A92F}"
    ProjectSection(WebsiteProperties) = preProject
        UseIISExpress = "true"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"
        ...
        SlnRelativePath = "..\..\WebSites\WebSite1\"
        DefaultWebSiteLanguage = "Visual Basic"
    EndProjectSection
EndProject

Because the project is identified by the URL (including port), there isn't a way in the VS UI to change this. You should be able to modify the solution file though, and it should work.

Eclipse doesn't stop at breakpoints

go breatpoint and click on 5th to eclipse->window>->show view->other->debug->breakpoint and click on 5th option (Skip All Breakpoints)

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

Using underscores in Java variables and method names

I think any style that breaks a language's own style guidelines (without due reason) is ugly and therefore "bad".

No doubt the code you've seen was written by someone who used to work on a language where underscores were acceptable.

Some people just cannot adapt to new coding styles...

Can angularjs routes have optional parameter values?

Like @g-eorge mention, you can make it like this:

module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);

You can also make as much as u need optional parameters.

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

How to sort a HashMap in Java

Sorting by key:

public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();

    map.put("b", "dd");
    map.put("c", "cc");
    map.put("a", "aa");

    map = new TreeMap<>(map);

    for (String key : map.keySet()) {
        System.out.println(key+"="+map.get(key));
    }
}

Python: How to create a unique file name?

To create a unique file path if its exist, use random package to generate a new string name for file. You may refer below code for same.

import os
import random
import string

def getUniquePath(folder, filename):    
    path = os.path.join(folder, filename)
    while os.path.exists(path):
         path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1]
    return path

Now you can use this path to create file accordingly.

How to retrieve SQL result column value using column name in Python?

You didn't provide many details, but you could try something like this:

# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table') 
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
    # Now you should be able to access the fields as properties of "row"
    myVar1 = row.field1
    myVar2 = row.field2
conn.close()

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

preferredStatusBarStyle isn't called

UIStatusBarStyle in iOS 7

The status bar in iOS 7 is transparent, the view behind it shows through.

The style of the status bar refers to the appearances of its content. In iOS 7, the status bar content is either dark (UIStatusBarStyleDefault) or light (UIStatusBarStyleLightContent). Both UIStatusBarStyleBlackTranslucent and UIStatusBarStyleBlackOpaque are deprecated in iOS 7.0. Use UIStatusBarStyleLightContent instead.

How to change UIStatusBarStyle

If below the status bar is a navigation bar, the status bar style will be adjusted to match the navigation bar style (UINavigationBar.barStyle):

Specifically, if the navigation bar style is UIBarStyleDefault, the status bar style will be UIStatusBarStyleDefault; if the navigation bar style is UIBarStyleBlack, the status bar style will be UIStatusBarStyleLightContent.

If there is no navigation bar below the status bar, the status bar style can be controlled and changed by an individual view controller while the app runs.

-[UIViewController preferredStatusBarStyle] is a new method added in iOS 7. It can be overridden to return the preferred status bar style:

- (UIStatusBarStyle)preferredStatusBarStyle
  {
      return UIStatusBarStyleLightContent;
  }

If the status bar style should be controlled by a child view controller instead of self, override -[UIViewController childViewControllerForStatusBarStyle] to return that child view controller.

If you prefer to opt out of this behavior and set the status bar style by using the -[UIApplication statusBarStyle] method, add the UIViewControllerBasedStatusBarAppearance key to an app’s Info.plist file and give it the value NO.

CSS Selector for <input type="?"

Sadly the other posters are correct that you're ...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.

Out of completeness, the type selector is - similar to xpath - of the form [attribute=value] but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.

What is "entropy and information gain"?

When I was implementing an algorithm to calculate the entropy of an image I found these links, see here and here.

This is the pseudo-code I used, you'll need to adapt it to work with text rather than images but the principles should be the same.

//Loop over image array elements and count occurrences of each possible
//pixel to pixel difference value. Store these values in prob_array
for j = 0, ysize-1 do $
    for i = 0, xsize-2 do begin
       diff = array(i+1,j) - array(i,j)
       if diff lt (array_size+1)/2 and diff gt -(array_size+1)/2 then begin
            prob_array(diff+(array_size-1)/2) = prob_array(diff+(array_size-1)/2) + 1
       endif
     endfor

//Convert values in prob_array to probabilities and compute entropy
n = total(prob_array)

entrop = 0
for i = 0, array_size-1 do begin
    prob_array(i) = prob_array(i)/n

    //Base 2 log of x is Ln(x)/Ln(2). Take Ln of array element
    //here and divide final sum by Ln(2)
    if prob_array(i) ne 0 then begin
        entrop = entrop - prob_array(i)*alog(prob_array(i))
    endif
endfor

entrop = entrop/alog(2)

I got this code from somewhere, but I can't dig out the link.

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

jQuery DataTables: control table width

None of the solutions here worked for me. Even the example on the datatables homepage did not work hence to the initialization of the datatable in the show option.

I found a solution to the problem. The trick is to use the activate option for tabs and to call fnAdjustColumnSizing() on the visible table:

$(function () {

// INIT TABS WITH DATATABLES
$("#TabsId").tabs({
    activate: function (event, ui) {
        var oTable = $('div.dataTables_scrollBody>table:visible', ui.panel).dataTable();
        if (oTable.length > 0) {
            oTable.fnAdjustColumnSizing();
        }
    }
});

// INIT DATATABLES
// options for datatables
var optDataTables = {
    "sScrollY": "200px",
    "bScrollCollapse": true,
    "bPaginate": false,
    "bJQueryUI": true,
    "aoColumnDefs": [
        { "sWidth": "10%", "aTargets": [-1] }
    ]
};
// initialize data table
$('table').dataTable(optDataTables);

});

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Visual Studio Code: Version: 1.53.2


If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.

Go to Edit > Replace in Files

enter image description here

From there it is similar to the search funtionality for a single file.

I changed the name of a class I was using across files and this worked perfectly.

Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.

Getting checkbox values on submit

If you want to turn specific values in to new variables if they have been selected:

// Retrieve array color[] and set as variable    
$colors = $_GET['color'];
// Use array_search to find the key for "red"
$key_red = array_search('red', $colors);
// If "red" exists, the key will be an integer (or FALSE)
if (is_int($key_red)) {
    $red_color = 'Red was selected';
}

How can I get the height and width of an uiimage?

Use the size property on the UIImage instance. See the documentation for more details.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Testing pointers for validity (C/C++)

This article MEM10-C. Define and use a pointer validation function says it is possible to do a check to some degree, especially under Linux OS.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Arrays.asList() of an array

You are trying to cast int[] to Integer[], this is not possible.

You can use commons-lang's ArrayUtils to convert the ints to Integers before getting the List from the array:

public int getTheNumber(int[] factors) {
    Integer[] integers = ArrayUtils.toObject(factors);
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(integers));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}    

Java SimpleDateFormat for time zone with a colon separator?

Since an example of Apache FastDateFormat(click for the documentations of versions:2.6and3.5) is missing here, I am adding one for those who may need it. The key here is the pattern ZZ(2 capital Zs).

import java.text.ParseException
import java.util.Date;
import org.apache.commons.lang3.time.FastDateFormat;
public class DateFormatTest throws ParseException {
    public static void main(String[] args) {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parse(stringFormattedDate));
    }
}

Here is the output of the code:

Date formatted into String:
2016-11-22T14:52:17+05:30
String parsed into Date:
Tue Nov 22 14:30:14 IST 2016

Note: The above code is of Apache Commons' lang3. The class org.apache.commons.lang.time.FastDateFormat does not support parsing, and it supports only formatting. For example, the output of the following code:

import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
public class DateFormatTest {
    public static void main(String[] args) throws ParseException {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parseObject(stringFormattedDate));
    }
}

will be this:

Date formatted into String:
2016-11-22T14:55:56+05:30
String parsed into Date:
Exception in thread "main" java.text.ParseException: Format.parseObject(String) failed
    at java.text.Format.parseObject(Format.java:228)
    at DateFormatTest.main(DateFormatTest.java:12)

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

One of the possible reasons is when you load jQuery TWICE ,like:

<script src='..../jquery.js'></script>
....
....
....
....
....
<script src='......./jquery.js'></script>

So, check your source code and remove duplicate jQuery load.

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

Can't use method return value in write context

I'm not sure if this would be a common mistake, but if you do something like:

$var = 'value' .= 'value2';

this will also produce the same error

Can't use method return value in write context

You can't have an = and a .= in the same statement. You can use one or the other, but not both.

Note, I understand this is unrelated to the actual code in the question, however this question is the top result when searching for the error message, so I wanted to post it here for completeness.

How to print the current time in a Batch-File?

Not sure if your question was answered.

This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.

Does not seem to create multiple instances, so that's a good thing.

@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls

wp-admin shows blank page, how to fix it?

[6] was spot on. I had the same problem ie a blank screen where wp-admin should have been Renaming plugins to pluginss let me get back in.

I also had a blank screen for my blog. The solution was to copy up a backup copy of wp-config,php somehow the 'live' wp-config.php had been replaced with a file size of zero.

It seems that it is very important to have an off-line backup The easy way to copy of the files is Filezilla (freeware)

You need a wordpress plugin for database backup - ie to back up all your pages and posts. But the pros will tell you that you need to get a

Peter

How to read a text file into a list or an array with Python

You will have to split your string into a list of values using split()

So,

lines = text_file.read().split(',')

EDIT: I didn't realise there would be so much traction to this. Here's a more idiomatic approach.

import csv
with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # do something

Resetting Select2 value in dropdown with reset button

If you have a populated select widget, for example:

<select>
    <option value="1">one</option>
    <option value="2" selected="selected">two</option>
    <option value="3">three</option>
    ...

you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:

$('button[type="reset"]').click(function(event) {
    // Make sure we reset the native form first
    event.preventDefault();
    $(this).closest('form').get(0).reset();
    // And then update select2 to match
    $('#d').select2('val', $('#d').find(':selected').val());
}

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

_x000D_
_x000D_
.wrapper, html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: flex;
    flex-direction: column;
}
#row1 {
    background-color: red;
}
#row2 {
    background-color: blue;
}
#row3 {
    background-color: green;
    flex:2;
    display: flex;
}
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

DEMO

Group dataframe and get sum AND count?

If you have lots of columns and only one is different you could do:

In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
                      Organisation Name   Amount
Company Name                                   
Vifor Pharma UK Ltd                  5  4207.93

Note you can then rename the Organisation Name column as you wish.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Ran into a similar issue and my problem was that MySQL installed itself configured to run on non-default port. I do not know the reason for that, but to find out which port MySQL is running on, run the following in MySql client:

SHOW GLOBAL VARIABLES LIKE 'PORT';

C# Numeric Only TextBox Control

this way is right with me:

private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
     const char Delete = (char)8;
     e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

Image re-size to 50% of original size in HTML

You can use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

Recursive file search using PowerShell

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat

Will also work

Portable way to get file size (in bytes) in shell?

wc -c < filename (short for word count, -c prints the byte count) is a portable, POSIX solution. Only the output format might not be uniform across platforms as some spaces may be prepended (which is the case for Solaris).

Do not omit the input redirection. When the file is passed as an argument, the file name is printed after the byte count.

I was worried it wouldn't work for binary files, but it works OK on both Linux and Solaris. You can try it with wc -c < /usr/bin/wc. Moreover, POSIX utilities are guaranteed to handle binary files, unless specified otherwise explicitly.

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

What datatype should be used for storing phone numbers in SQL Server 2005?

nvarchar with preprocessing to standardize them as much as possible. You'll probably want to extract extensions and store them in another field.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

File Not Found when running PHP with Nginx

In my case the PHP-script itself returned 404 code. Had nothing to do with nginx.

How to stop mysqld

Following worked for me on my macbook pro:

brew services stop mysql

Incase if you want to stop all brew services:

brew services stop --all

Ordering by specific field value first

This works for me using Postgres 9+:

SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC

How do I set/unset a cookie with jQuery?

Update April 2019

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

Basic examples:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

See the docs on github for details.


Before April 2019 (old)

See the plugin:

https://github.com/carhartl/jquery-cookie

You can then do:

$.cookie("test", 1);

To delete:

$.removeCookie("test");

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

$.cookie("test", 1, { expires : 10 });

If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.

To cover all the options:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

To read back the value of the cookie:

var cookieValue = $.cookie("test");

You may wish to specify the path parameter if the cookie was created on a different path to the current one:

var cookieValue = $.cookie("test", { path: '/foo' });

UPDATE (April 2015):

As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.

Replace characters from a column of a data frame R

Use gsub:

data1$c <- gsub('_', '-', data1$c)
data1

            a b   c
1  0.34597094 a A-B
2  0.92791908 b A-B
3  0.30168772 c A-B
4  0.46692738 d A-B
5  0.86853784 e A-C
6  0.11447618 f A-C
7  0.36508645 g A-C
8  0.09658292 h A-C
9  0.71661842 i A-C
10 0.20064575 j A-C

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

TCPDF not render all CSS properties

TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.