Programs & Examples On #Glui

Finding out the name of the original repository you cloned from in Git

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

It was tested with three different URL styles:

echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

ImportError: No module named 'django.core.urlresolvers'

if you want to import reverse, import it from django.urls

from django.urls import reverse

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

C:\Users\abhay kumar>mysql --user=admin --password=root..

This command is working for root user..you can access mysql tool from any where using command prompt..

C:\Users\lelaprasad>mysql --user=root --password=root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.5.47 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

How do I get class name in PHP?

It sounds like you answered your own question. get_class will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class

Here is their example:

 <?php

 class foo 
 {
     function name()
     {
         echo "My name is " , get_class($this) , "\n";
     }
 }

 // create an object
 $bar = new foo();

 // external call
 echo "Its name is " , get_class($bar) , "\n"; // It's name is foo

 // internal call
 $bar->name(); // My name is foo

To make it more like your example you could do something like:

 <?php

 class MyClass
 {
       public static function getClass()
       {
            return get_class();
       }
 }

Now you can do:

 $className = MyClass::getClass();

This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.

<?php

class MyClass
{
    public static function getClass()
    {
        return get_called_class();
    }

    public static function getDefiningClass()
    {
        return get_class();
    }
}

class MyExtendedClass extends MyClass {}

$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'

How to generate a random int in C?

Well, STL is C++, not C, so I don't know what you want. If you want C, however, there is the rand() and srand() functions:

int rand(void);

void srand(unsigned seed);

These are both part of ANSI C. There is also the random() function:

long random(void);

But as far as I can tell, random() is not standard ANSI C. A third-party library may not be a bad idea, but it all depends on how random of a number you really need to generate.

Changing text color onclick

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>

How do I get the first n characters of a string without checking the size or going out of bounds?

If you are lucky enough to develop with Kotlin,
you can use take to achieve your goal.

val someString = "hello"

someString.take(10) // result is "hello"
someString.take(4) // result is "hell" )))

How do I get the current time zone of MySQL?

From the manual (section 9.6):

The current values of the global and client-specific time zones can be retrieved like this:
mysql> SELECT @@global.time_zone, @@session.time_zone;

Edit The above returns SYSTEM if MySQL is set to slave to the system's timezone, which is less than helpful. Since you're using PHP, if the answer from MySQL is SYSTEM, you can then ask the system what timezone it's using via date_default_timezone_get. (Of course, as VolkerK pointed out, PHP may be running on a different server, but as assumptions go, assuming the web server and the DB server it's talking to are set to [if not actually in] the same timezone isn't a huge leap.) But beware that (as with MySQL), you can set the timezone that PHP uses (date_default_timezone_set), which means it may report a different value than the OS is using. If you're in control of the PHP code, you should know whether you're doing that and be okay.

But the whole question of what timezone the MySQL server is using may be a tangent, because asking the server what timezone it's in tells you absolutely nothing about the data in the database. Read on for details:

Further discussion:

If you're in control of the server, of course you can ensure that the timezone is a known quantity. If you're not in control of the server, you can set the timezone used by your connection like this:

set time_zone = '+00:00';

That sets the timezone to GMT, so that any further operations (like now()) will use GMT.

Note, though, that time and date values are not stored with timezone information in MySQL:

mysql> create table foo (tstamp datetime) Engine=MyISAM;
Query OK, 0 rows affected (0.06 sec)

mysql> insert into foo (tstamp) values (now());
Query OK, 1 row affected (0.00 sec)

mysql> set time_zone = '+01:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp              |
+---------------------+
| 2010-05-29 08:31:59 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+02:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp              |
+---------------------+
| 2010-05-29 08:31:59 |      <== Note, no change!
+---------------------+
1 row in set (0.00 sec)

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2010-05-29 10:32:32 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+00:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2010-05-29 08:32:38 |      <== Note, it changed!
+---------------------+
1 row in set (0.00 sec)

So knowing the timezone of the server is only important in terms of functions that get the time right now, such as now(), unix_timestamp(), etc.; it doesn't tell you anything about what timezone the dates in the database data are using. You might choose to assume they were written using the server's timezone, but that assumption may well be flawed. To know the timezone of any dates or times stored in the data, you have to ensure that they're stored with timezone information or (as I do) ensure they're always in GMT.

Why is assuming the data was written using the server's timezone flawed? Well, for one thing, the data may have been written using a connection that set a different timezone. The database may have been moved from one server to another, where the servers were in different timezones (I ran into that when I inherited a database that had moved from Texas to California). But even if the data is written on the server, with its current time zone, it's still ambiguous. Last year, in the United States, Daylight Savings Time was turned off at 2:00 a.m. on November 1st. Suppose my server is in California using the Pacific timezone and I have the value 2009-11-01 01:30:00 in the database. When was it? Was that 1:30 a.m. November 1st PDT, or 1:30 a.m. November 1st PST (an hour later)? You have absolutely no way of knowing. Moral: Always store dates/times in GMT (which doesn't do DST) and convert to the desired timezone as/when necessary.

Use tab to indent in textarea

Multiple-line indetation script based on @kasdega solution.

$('textarea').on('keydown', function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === 9) {
        e.preventDefault();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        var val = this.value;
        var selected = val.substring(start, end);
        var re = /^/gm;
        var count = selected.match(re).length;


        this.value = val.substring(0, start) + selected.replace(re, '\t') + val.substring(end);
        this.selectionStart = start;
        this.selectionEnd = end + count;
    }
});

How to compile without warnings being treated as errors?

You can make all warnings being treated as such using -Wno-error. You can make specific warnings being treated as such by using -Wno-error=<warning name> where <warning name> is the name of the warning you don't want treated as an error.

If you want to entirely disable all warnings, use -w (not recommended).


Source: http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

Tree implementation in Java (root, parents and children)

This tree is not a binary tree, so you need an array of the children elements, like List.

public Node(Object data, List<Node> children) {
    this.data = data;
    this.children = children;
}

Then create the instances.

Passing parameters to a JQuery function

try something like this

#vote_links a will catch all ids inside vote links div id ...

<script type="text/javascript">

  jQuery(document).ready(function() {
  jQuery(\'#vote_links a\').click(function() {// alert(\'vote clicked\');
    var det = jQuery(this).get(0).id.split("-");// alert(jQuery(this).get(0).id);
    var votes_id = det[0];


   $("#about-button").css({
    opacity: 0.3
   });
   $("#contact-button").css({
    opacity: 0.3
   });

   $("#page-wrap div.button").click(function(){

change background image in body

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

What is a typedef enum in Objective-C?

You can use in the below format, Raw default value starting from 0, so

  • kCircle is 0,
  • kRectangle is 1,
  • kOblateSpheroid is 2.

You can assign your own specific start value.

typedef enum : NSUInteger {
    kCircle, // for your value; kCircle = 5, ...
    kRectangle,
    kOblateSpheroid
} ShapeType;

ShapeType circleShape = kCircle;
NSLog(@"%lu", (unsigned long) circleShape); // prints: 0

How can I generate an apk that can run without server with react-native?

Run this command:

react-native run-android --variant=release

Note that --variant=release is only available if you've set up signing with cd android && ./gradlew assembleRelease.

How can I wrap text in a label using WPF?

Often you cannot replace a Label with a TextBlock as you want to the use the Target property (which sets focus to the targeted control when using the keyboard e.g. ALT+C in the sample code below), as that's all a Label really offers over a TextBlock.

However, a Label uses a TextBlock to render text (if a string is placed in the Content property, which it typically is); therefore, you can add a style for TextBlock inside the Label like so:

<Label              
    Content="_Content Text:"
    Target="{Binding ElementName=MyTargetControl}">
    <Label.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    </Label.Resources>
 </Label>
 <CheckBox x:Name = "MyTargetControl" />

This way you get to keep the functionality of a Label whilst also being able to wrap the text.

How to convert a byte array to its numeric value (Java)?

One could use the Buffers that are provided as part of the java.nio package to perform the conversion.

Here, the source byte[] array has a of length 8, which is the size that corresponds with a long value.

First, the byte[] array is wrapped in a ByteBuffer, and then the ByteBuffer.getLong method is called to obtain the long value:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

Result

4

I'd like to thank dfa for pointing out the ByteBuffer.getLong method in the comments.


Although it may not be applicable in this situation, the beauty of the Buffers come with looking at an array with multiple values.

For example, if we had a 8 byte array, and we wanted to view it as two int values, we could wrap the byte[] array in an ByteBuffer, which is viewed as a IntBuffer and obtain the values by IntBuffer.get:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

Result:

1
4

Convert DateTime to TimeSpan

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime).

If you simply want to convert a DateTime to a number you can use the Ticks property.

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

How do I escape double quotes in attributes in an XML String in T-SQL?

Wouldn't that be &quot; in xml? i.e.

"hi &quot;mom&quot; lol" 

**edit: ** tested; works fine:

declare @xml xml

 set @xml = '<transaction><item value="hi &quot;mom&quot; lol" 
    ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'

select @xml.value('(//item/@value)[1]','varchar(50)')

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

C# static class why use?

Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.

As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.

The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.

Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.

One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,

public class Foo
{
    public static Foo New(string fooString)
    {
        ProxyGenerator generator = new ProxyGenerator();

        return (Foo)generator.CreateClassProxy
             (typeof(Foo), new object[] { fooString }, new Interceptor()); 
    }

This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

Select box arrow style

http://jsfiddle.net/u3cybk2q/2/ check on windows, iOS and Android (iexplorer patch)

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 240px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
}_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: visible;_x000D_
   background: url(http://nightly.enyojs.com/latest/lib/moonstone/dist/moonstone/images/caret-black-small-down-icon.png) no-repeat right #FFF;_x000D_
   border: 1px solid #ccc;_x000D_
}_x000D_
.styled-select select::-ms-expand {_x000D_
    display: none;_x000D_
}
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

docker error: /var/run/docker.sock: no such file or directory

For boot2docker on Windows, after seeing:

FATA[0000] Get http:///var/run/docker.sock/v1.18/version: 
dial unix /var/run/docker.sock: no such file or directory.  
Are you trying to connect to a TLS-enabled daemon without TLS?

All I did was:

boot2docker start
boot2docker shellinit

That generated:

export DOCKER_CERT_PATH=C:\Users\vonc\.boot2docker\certs\boot2docker-vm
export DOCKER_TLS_VERIFY=1
export DOCKER_HOST=tcp://192.168.59.103:2376

Finally:

boot2docker ssh

And docker works again

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

validation is working with ng repeat if I use the following syntax scope.step3Form['item[107][quantity]'].$touched I don't know it's a best practice or the best solution, but it works

<tr ng-repeat="item in items">
   <td>
        <div class="form-group">
            <input type="text" ng-model="item.quantity" name="item[<% item.id%>][quantity]" required="" class="form-control" placeholder = "# of Units" />
            <span ng-show="step3Form.$submitted || step3Form['item[<% item.id %>][quantity]'].$touched">
                <span class="help-block" ng-show="step3Form['item[<% item.id %>][quantity]'].$error.required"> # of Units is required.</span>
            </span>
        </div>
    </td>
</tr>

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Quickest way to convert XML to JSON in Java

I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

How does one remove a Docker image?

Here's a shell script to remove a tagged (named) image and it's containers. Save as docker-rmi and run using 'docker-rmi my-image-name'

#!/bin/bash

IMAGE=$1

if [ "$IMAGE" == "" ] ; then
  echo "Missing image argument"
  exit 2
fi

docker ps -qa -f "ancestor=$IMAGE" | xargs docker rm
docker rmi $IMAGE

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

Is <img> element block level or inline level?

behaves as an inline-block element as it allows other images in same line i.e. inline and also we can change the width and height of the image and this is the property of a block element. Hence, provide both the features of inline and block elements.

Java LinkedHashMap get first or last entry

Perhaps something like this :

LinkedHashMap<Integer, String> myMap;

public String getFirstKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
    break;
  }
  return out;
}

public String getLastKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
  }
  return out;
}

What is a regex to match ONLY an empty string?

Another possible answer considering also the case that an empty string might contain several whitespace characters for example spaces,tabs,line break characters can be the folllowing pattern.

pattern = r"^(\s*)$"

This pattern matches if the string starts and ends with zero or more whitespace characters.

It was tested in Python 3

submitting a GET form with query string params and hidden params disappear

I usually write something like this:

foreach($_GET as $key=>$content){
        echo "<input type='hidden' name='$key' value='$content'/>";
}

This is working, but don't forget to sanitize your inputs against XSS attacks!

Difference Between Schema / Database in MySQL

in MySQL schema is synonym of database. Its quite confusing for beginner people who jump to MySQL and very first day find the word schema, so guys nothing to worry as both are same.

When you are starting MySQL for the first time you need to create a database (like any other database system) to work with so you can CREATE SCHEMA which is nothing but CREATE DATABASE

In some other database system schema represents a part of database or a collection of Tables, and collection of schema is a database.

How do I seed a random class to avoid getting duplicate random values

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.

How can I set the default timezone in node.js?

Here is a 100% working example for getting custom timezone Date Time in NodeJs without using any external modules:

_x000D_
_x000D_
const nDate = new Date().toLocaleString('en-US', {_x000D_
  timeZone: 'Asia/Calcutta'_x000D_
});_x000D_
_x000D_
console.log(nDate);
_x000D_
_x000D_
_x000D_

change html text from link with jquery

I found this to be the simplest piece of code for getting the job done. As you can see it is super simple.

for original link text

I use:

    $("#sec1").text(Sector1);

where

   Sector1 = 'my new link text';

How to redirect the output of a PowerShell to a file during its execution

Use:

Write "Stuff to write" | Out-File Outputfile.txt -Append

Draw a connecting line between two elements

VisJS supports this with its Arrows example, that supports draggable elements.

It also supports editable connections, with its Interaction Events example.

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

Gradle does not find tools.jar

I solved problem on this way:

Difference between jQuery .hide() and .css("display", "none")

You can have a look at the source code (here it is v1.7.2).

Except for the animation that we can set, this also keep in memory the old display style (which is not in all cases block, it can also be inline, table-cell, ...).

Using NSLog for debugging

type : BOOL DATA (YES/NO) OR(1/0)

BOOL dtBool = 0; 

OR

BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");

OUTPUT : NO

type : Long

long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);

OUTPUT : Display Long: 2015

long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);

OUTPUT : Display very Long: 20152015

type : String

NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);

OUTPUT : Display String: a String

type : Float

float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);

OUTPUT : isplay Float: 5.342450

type : Integer

int aInteger = 3;    
NSLog(@"Display Integer: %i", aInteger);

OUTPUT : Display Integer: 3

NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);

OUTPUT : String: a String

Display Float: 5.342450

Display Integer: 3

http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html

Using C# to read/write Excel files (.xls/.xlsx)

I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.

Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.

Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.

Easier way to debug a Windows service

#if DEBUG
    System.Diagnostics.Debugger.Break();
#endif

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

SQL-Server: The backup set holds a backup of a database other than the existing

USE [master];
GO

CREATE DATABASE db;
GO

CREATE DATABASE db2;
GO

BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO

RESTORE DATABASE db2
  FROM DISK = 'c:\temp\db.bak'
  WITH REPLACE,
  MOVE 'db' TO 'c:\temp\db2.mdf',
  MOVE 'db_log' TO 'c:\temp\db2.ldf';

Regular expressions inside SQL Server

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'

Explaining Python's '__enter__' and '__exit__'

Python calls __enter__ when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__ to free up the resource

Let's consider Context Managers and the “with” Statement in Python. Context Manager is a simple “protocol” (or interface) that your object needs to follow so it can be used with the with statement. Basically all you need to do is add enter and exit methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.

Let’s take a look at what this would look like in practical terms. Here’s how a simple implementation of the open() context manager might look like:

class ManagedFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

Our ManagedFile class follows the context manager protocol and now supports the with statement.

>>> with ManagedFile('hello.txt') as f:
...    f.write('hello, world!')
...    f.write('bye now')`enter code here`

Python calls enter when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls exit to free up the resource.

Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases matches what’s offered by contextlib.

Why does ++[[]][+[]]+[+[]] return the string "10"?

If we split it up, the mess is equal to:

++[[]][+[]]
+
[+[]]

In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).

Therefore, we can simplify it (++ has precendence over +):

++[[]][0]
+
[0]

Because [[]][0] means: get the first element from [[]], it is true that:

[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.

++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).

Again, we can simplify the mess into something more legible. Let's substitute [] back for A:

(+[] + 1)
+
[0]

Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.

  • (+[] + 1) === (+"" + 1)
  • (+"" + 1) === (0 + 1)
  • (0 + 1) === 1

Let's simplify it even more:

1
+
[0]

Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.

In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.

"1" + "0" === "10" // Yay!

Specification details for +[]:

This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber() says:

Object

Apply the following steps:

  1. Let primValue be ToPrimitive(input argument, hint String).

  2. Return ToString(primValue).

ToPrimitive() says:

Object

Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

[[DefaultValue]] says:

8.12.8 [[DefaultValue]] (hint)

When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:

  1. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".

  2. If IsCallable(toString) is true then,

a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.

b. If str is a primitive value, return str.

The .toString of an array says:

15.4.4.2 Array.prototype.toString ( )

When the toString method is called, the following steps are taken:

  1. Let array be the result of calling ToObject on the this value.

  2. Let func be the result of calling the [[Get]] internal method of array with argument "join".

  3. If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).

  4. Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.

So +[] comes down to +"", because [].join() === "".

Again, the + is defined as:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber is defined for "" as:

The MV of StringNumericLiteral ::: [empty] is 0.

So +"" === 0, and thus +[] === 0.

How to install PHP intl extension in Ubuntu 14.04

sudo apt-get install php-intl

then restart your server

JFrame: How to disable window resizing?

This Code May be Help you : [ Both maximizing and preventing resizing on a JFrame ]

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);

UIButton: set image for selected-highlighted state

You can do this in Interface Builder.

Select the UIButton you wish to set in IB then go to the attributes inspector.

In the screen shots,I am using a custom button type , but that does not matter.

Custom Default

enter image description here

enter image description here

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

3-dimensional array in numpy

Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.

https://opensourceoptions.com/blog/numpy-array-shapes-and-reshaping-arrays/#:~:text=3D%20arrays,order%20layers%2C%20rows%2C%20columns.

Connecting to TCP Socket from browser using javascript

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

ws2s schematic diagram

enter image description here

code sample:

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

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

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

jQuery and TinyMCE: textarea value doesn't submit

When you run ajax on your form, you need to tell TinyMCE to update your textarea first:

// TinyMCE will now save the data into textarea
tinyMCE.triggerSave(); 
// now grap the data
var form_data = form.serialize(); 

How to replace multiple white spaces with one white space

Smallest solution:

var regExp=/\s+/g, newString=oldString.replace(regExp,' ');

Add image in pdf using jspdf

This worked for me in Angular 2:

var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)

jsPDF version 1.5.3

assets directory is in src directory of the Angular project root

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

Skipping Iterations in Python

I think you're looking for continue

How to uninstall Anaconda completely from macOS

This is one more place that anaconda had an entry that was breaking my python install after removing Anaconda. Hoping this helps someone else.

If you are using yarn, I found this entry in my .yarn.rc file in ~/"username"

python "/Users/someone/anaconda3/bin/python3"

removing this line fixed one last place needed for complete removal. I am not sure how that entry was added but it helped

IsNullOrEmpty with Object

object MyObject = null;

if (MyObject != null && !string.IsNullOrEmpty(MyObject.ToString())) { ... }

How to run sql script using SQL Server Management Studio?

This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):

sqlcmd -S .\SQLExpress -i SqlScript.sql

Where SqlScript.sql is the script file name located at the current directory. See this Microsoft page for more examples

How to count the number of occurrences of an element in a List

I didn't want to make this case more difficult and made it with two iterators I have a HashMap with LastName -> FirstName. And my method should delete items with dulicate FirstName.

public static void removeTheFirstNameDuplicates(HashMap<String, String> map)
{

    Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
    Iterator<Map.Entry<String, String>> iter2 = map.entrySet().iterator();
    while(iter.hasNext())
    {
        Map.Entry<String, String> pair = iter.next();
        String name = pair.getValue();
        int i = 0;

        while(iter2.hasNext())
        {

            Map.Entry<String, String> nextPair = iter2.next();
            if (nextPair.getValue().equals(name))
                i++;
        }

        if (i > 1)
            iter.remove();

    }

}

Split comma-separated input box values into array in jquery, and loop through it

var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

AngularJS - add HTML element to dom in directive without jQuery

In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.

So basically, you can rewrite your code to something like this:

link: function (scope, iElement, iAttrs) {
  var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');
  angular.element(svgTag).appendTo(iElement[0]);
  //...
}

How to move the cursor word by word in the OS X Terminal

If you happen to be a Vim user, you could try bash's vim mode. Run this or put it in your ~/.bashrc file:

set -o vi

By default you're in insert mode; hit escape and you can move around just like you can in normal-mode Vim, so movement by word is w or b, and the usual movement keys also work.

make div's height expand with its content

Added display:inline to the div and it grew auto ( not the scroll stuff ) when height content got bigger then the set div height of 200px

How to round an image with Glide library?

implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'


RequestOptions options=new RequestOptions();
        options.centerCrop().placeholder(getResources().getDrawable(R.drawable.user_placeholder));
        Glide.with(this)
                .load(preferenceSingleTon.getImage())
                .apply(options)
                .into(ProfileImage);

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Using ffmpeg to encode a high quality video

A couple of things:

  • You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k to the command line to get more or less DVD video bitrate.

  • You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264 as part of the command line. Otherwise -vcodec mpeg4 will also do a better job than MPEG-1, but not as well as x264.

  • There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.

How do I set the maximum line length in PyCharm?

You can even set a separate right margin for HTML. Under the specified path:

File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)

This is very useful because generally HTML and JS may be usually long in one line than Python. :)

Run a task every x-minutes with Windows Task Scheduler

You can also create a batch file like the following if you need finer granularity between calls:

:loop
CallYour.Exe
timeout /t timeToWaitBetweenCallsInSeconds /nobreak
goto :loop

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

That error message also appeared into my VM. First of all, I tried to disable the option "Enable VT-x/AMD-V" (you can find it opening the settings of your VM: Settings->System->Acceleration), there was a warning saying that "Invalid settings detected (you accept the changes and the box was selected again).

Then I read this posts and I tried to enable the Virtualiation Techniuqe (used when you want to enable various VM in your computer (by default is set as Disabled because you don't need that property working.

OOP vs Functional Programming vs Procedural

I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.

For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.

It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!

Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

enter image description here

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

Auto-fitting columns

Further study

Evaluate list.contains string in JSTL

If you are using Spring Framework, you can use Spring TagLib and SpEL:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="mylist.contains(myValue)" />
<c:if test="${containsValue}">style='display:none;'</c:if>

How do I get the number of elements in a list?

There is an inbuilt function called len() in python which will help in these conditions.

a=[1,2,3,4,5,6]
print(len(a))     #Here the len() function counts the number of items in the list.

Output:

>>> 6

This will work slightly different in the case of string (below):

a="Hello"
print(len(a)) #Here the len() function counts the alphabets or characters in the list.

Output:

>>> 5

This is because variable (a) is a string and not a list, so it will count the number of characters or alphabets in the string and then print the output.

Move / Copy File Operations in Java

Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.

Duration using FileOutputStream byte stream: 4 965 078

Duration using BufferedOutputStream: 1 237 206

Duration using (character text Reader: 2 858 875

Duration using BufferedReader(Buffered character text stream: 1 998 005

Duration using (Files NIO copy): 18 351 115

when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.

Laravel Escaping All HTML in Blade Template

There is no problem with displaying HTML code in blade templates.

For test, you can add to routes.php only one route:

Route::get('/', function () {

        $data = new stdClass();
        $data->page_desc
            = '<strong>aaa</strong><em>bbb</em>
               <p>New paragaph</p><script>alert("Hello");</script>';

        return View::make('hello')->with('content', $data);
    }
);

and in hello.blade.php file:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>

{{ $content->page_desc }}

</body>
</html>

For the following code you will get output as on image

Output

So probably page_desc in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags

EDIT

I've also tested it with putting the same code into database:

Route::get('/', function () {

        $data = User::where('id','=',1)->first();

        return View::make('hello')->with('content', $data);
    }
);

Output is exactly the same in this case

Edit2

I also don't know if Pages is your model or it's a vendor model. For example it can have accessor inside:

public function getPageDescAttribute($value)
{
    return htmlspecialchars($value);
}

and then when you get page_desc attribute you will get modified page_desc with htmlspecialchars. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages class

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

How do I exit from the text window in Git?

That's the vi editor. Try ESC :q!.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

getApplicationContext()

this is used for application level and refer to all activities.

getContext() and getBaseContext()

is most probably same .these are reffered only current activity which is live.

this

is refer current class object always.

Merge PDF files

A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):

import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
    for file in files:
        filepath = subdir + os.sep + file
        # you can have multiple endswith
        if filepath.endswith((".pdf", ".PDF")):
            file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)

for k, v in file_dict.items():
    print(k, v)
    merger.append(v)

merger.write("combined_result.pdf")

C++ int float casting

he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float

 (float)(a.y - b.y) / (a.x - b.x);

How can I download a file from a URL and save it in Rails?

I think this is the clearest way:

require 'open-uri'

File.write 'image.png', open('http://example.com/image.png').read

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

error 1265. Data truncated for column when trying to load data from txt file

I had this issue when trying to convert an existing varchar column to enum. For me the issue was that there were existing values for that column that were not part of the enum's list of accepted values. So if your enum will only allow values, say ('dog', 'cat') but there is a row with bird in your table, the MODIFY COLUMN will fail with this error.

"Keep Me Logged In" - the best approach

Generate a hash, maybe with a secret only you know, then store it in your DB so it can be associated with the user. Should work quite well.

Android read text raw resource file

1.First create a Directory folder and name it raw inside the res folder 2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt.... 3.copy and paste the text you want inside the .txt file you created"articles.txt" 4.dont forget to include a textview in your main.xml MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gettingtoknowthe_os);

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
    helloTxt.setText(readTxt());

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();//to exclude the ActionBar
}

private String readTxt() {

    //getting the .txt file
    InputStream inputStream = getResources().openRawResource(R.raw.articles);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        int i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArrayOutputStream.toString();
}

Hope it worked!

Apache Name Virtual Host with SSL

You MUST add below part to enable NameVirtualHost functionality with given IP.

NameVirtualHost IP_Address:443

Convert Text to Date?

I had a very similar issue earlier. Unfortunately I looked at this thread and didn't find an answer which I was happy with. Hopefully this will help others.

Using VBA.DateSerial(year,month,day) you can overcome Excel's intrinsic bias to US date format. It also means you have full control over the data, which is something I personally prefer:

function convDate(str as string) as Date
  Dim day, month, year as integer
  year  = int(mid(str,1,4))
  month = int(mid(str,6,2))
  day   = int(mid(str,9,2))
  convDate = VBA.DateSerial(year,month,day)
end function

How to Implement Custom Table View Section Headers and Footers with Storyboard

I used to do the following to create header/footer views lazily:

  • Add a freeform view controller for the section header/footer to the storyboard
  • Handle all stuff for the header in the view controller
  • In the table view controller provide a mutable array of view controllers for the section headers/footers repopulated with [NSNull null]
  • In viewForHeaderInSection/viewForFooterInSection if view controller does not yet exist, create it with storyboards instantiateViewControllerWithIdentifier, remember it in the array and return the view controllers view

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

how to get html content from a webview?

above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code

AssetManager mgr = mContext.getAssets();
             try {
InputStream in = null;              
if(condition)//you have a local html saved in assets
                            {
                            in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
                           }
                            else if(condition)//you have an url
                            {
                            URL feedURL = new URL(sURL);
                  in = feedURL.openConnection().getInputStream();}

                            // here you will get your html
                 String sHTML = streamToString(in);
                 in.close();

                 //display this html in the browser or web view              


             } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             }
        public static String streamToString(InputStream in) throws IOException {
            if(in == null) {
                return "";
            }

            Writer writer = new StringWriter();
            char[] buffer = new char[1024];

            try {
                Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }

            } finally {

            }

            return writer.toString();
        }

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Android ADB stop application command like "force-stop" for non rooted device

To kill from the application, you can do:

android.os.Process.killProcess(android.os.Process.myPid());

Redirect all output to file in Bash

It might be the standard error. You can redirect it:

... > out.txt 2>&1

How to substring in jquery

That's just plain JavaScript: see substring and substr.

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html

Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html

Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html

Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

Select2() is not a function

I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

As mentioned by @leocaseiro on github issue.

I found 3 solutions for those who are looking for easy fixes.

1) Moving from ngAfterViewInit to ngAfterContentInit

2) Moving to ngAfterViewChecked combined with ChangeDetectorRef as suggested on #14748 (comment)

3) Keep with ngOnInit() but call ChangeDetectorRef.detectChanges() after your changes.

Java IOException "Too many open files"

For UNIX:

As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.

Try looking at your present file descriptor capacity:

   $ ulimit -n

Then change the limit according to your requirements.

   $ ulimit -n <value>

Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

how to start the tomcat server in linux?

I know this is old question, but this command helped me!

Go to your Tomcat Directory
Just type this command in your terminal:

./catalina.sh start

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Writing a VLOOKUP function in vba

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

Enable IIS7 gzip

Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup

test gzip

To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression

Using CMake to generate Visual Studio C++ project files

CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.

Adding and removing source files is just a matter of modifying the CMakeLists.txt which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).

The following link explains CMake and Visual Studio specific behavior very well.

CMake and Visual Studio

Android: Vertical alignment for multi line EditText (Text area)

Use this:

android:gravity="top"

or

android:gravity="top|left"

How to append new data onto a new line

I presume that all you are wanting is simple string concatenation:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name + " ")
   hs.close() 

Alternatively, change the " " to "\n" for a newline.

R dplyr: Drop multiple columns

also try

## Notice the lack of quotes
iris %>% select (-c(Sepal.Length, Sepal.Width))

Font Awesome not working, icons showing as squares

I tried a number of the suggestions above without success.

I use the NuGeT packages. The are (for some reason) multiple named version (font-awesome, fontawesome, font.awesome, etc.)

For what it's worth: I removed all the version installed and then only installed the latest version of font.awesome. font.awesome just worked without the need to tweak or configure anything.

I assume there are a number of things are missing from the other named versions.

Spell Checker for Python

I'd recommend starting by carefully reading this post by Peter Norvig. (I had to something similar and I found it extremely useful.)

The following function, in particular has the ideas that you now need to make your spell checker more sophisticated: splitting, deleting, transposing, and inserting the irregular words to 'correct' them.

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

Note: The above is one snippet from Norvig's spelling corrector

And the good news is that you can incrementally add to and keep improving your spell-checker.

Hope that helps.

How to use placeholder as default value in select2 framework

Use a empty placeholder on your html like:

<select class="select2" placeholder = "">
    <option value="1">red</option>
    <option value="2">blue</option>
</select>

and in your script use:

$(".select2").select2({
        placeholder: "Select a color",
        allowClear: true
    });

Understanding the Rails Authenticity Token

The Authenticity Token is rails' method to prevent 'cross-site request forgery (CSRF or XSRF) attacks'.

To put it simple, it makes sure that the PUT / POST / DELETE (methods that can modify content) requests to your web app are made from the client's browser and not from a third party (an attacker) that has access to a cookie created on the client side.

How can I expand and collapse a <div> using javascript?

Take a look at toggle() jQuery function :

http://api.jquery.com/toggle/

Also, innerHTML jQuery Function is .html().

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

What is the main purpose of setTag() getTag() methods of View?

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

Reference: http://developer.android.com/reference/android/view/View.html

How to remove all options from a dropdown using jQuery / JavaScript

Try this

function removeElements(){
    $('#models').html("");
}

How can I stop redis-server?

Another way could be :

brew services stop redis

Filter dict to contain only certain keys?

You could use python-benedict, it's a dict subclass.

Installation: pip install python-benedict

from benedict import benedict

dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])

It's open-source on GitHub: https://github.com/fabiocaccamo/python-benedict


Disclaimer: I'm the author of this library.

Android saving file to external storage

You need a permission for this

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

and method:

public boolean saveImageOnExternalData(String filePath, byte[] fileData) {

    boolean isFileSaved = false;
    try {
        File f = new File(filePath);
        if (f.exists())
            f.delete();
        f.createNewFile();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(fileData);
        fos.flush();
        fos.close();
        isFileSaved = true;
        // File Saved
    } catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IOException");
        e.printStackTrace();
    }
    return isFileSaved;
    // File Not Saved
}

How to split a string, but also keep the delimiters?

One of the subtleties in this question involves the "leading delimiter" question: if you are going to have a combined array of tokens and delimiters you have to know whether it starts with a token or a delimiter. You could of course just assume that a leading delim should be discarded but this seems an unjustified assumption. You might also want to know whether you have a trailing delim or not. This sets two boolean flags accordingly.

Written in Groovy but a Java version should be fairly obvious:

            String tokenRegex = /[\p{L}\p{N}]+/ // a String in Groovy, Unicode alphanumeric
            def finder = phraseForTokenising =~ tokenRegex
            // NB in Groovy the variable 'finder' is then of class java.util.regex.Matcher
            def finderIt = finder.iterator() // extra method added to Matcher by Groovy magic
            int start = 0
            boolean leadingDelim, trailingDelim
            def combinedTokensAndDelims = [] // create an array in Groovy

            while( finderIt.hasNext() )
            {
                def token = finderIt.next()
                int finderStart = finder.start()
                String delim = phraseForTokenising[ start  .. finderStart - 1 ]
                // Groovy: above gets slice of String/array
                if( start == 0 ) leadingDelim = finderStart != 0
                if( start > 0 || leadingDelim ) combinedTokensAndDelims << delim
                combinedTokensAndDelims << token // add element to end of array
                start = finder.end()
            }
            // start == 0 indicates no tokens found
            if( start > 0 ) {
                // finish by seeing whether there is a trailing delim
                trailingDelim = start < phraseForTokenising.length()
                if( trailingDelim ) combinedTokensAndDelims << phraseForTokenising[ start .. -1 ]

                println( "leading delim? $leadingDelim, trailing delim? $trailingDelim, combined array:\n $combinedTokensAndDelims" )

            }

How to test code dependent on environment variables using JUnit?

A lot of focus in the suggestions above on inventing ways in runtime to pass in variables, set them and clear them and so on..? But to test things 'structurally', I guess you want to have different test suites for different scenarios? Pretty much like when you want to run your 'heavier' integration test builds, whereas in most cases you just want to skip them. But then you don't try and 'invent ways to set stuff in runtime', rather you just tell maven what you want? It used to be a lot of work telling maven to run specific tests via profiles and such, if you google around people would suggest doing it via springboot (but if you haven't dragged in the springboot monstrum into your project, it seems a horrendous footprint for 'just running JUnits', right?). Or else it would imply loads of more or less inconvenient POM XML juggling which is also tiresome and, let's just say it, 'a nineties move', as inconvenient as still insisting on making 'spring beans out of XML', showing off your ultimate 600 line logback.xml or whatnot...?

Nowadays, you can just use Junit 5 (this example is for maven, more details can be found here JUnit 5 User Guide 5)

 <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>5.7.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

and then

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>

and then in your favourite utility lib create a simple nifty annotation class such as

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIfEnvironmentVariable(named = "MAVEN_CMD_LINE_ARGS", matches = "(.*)integration-testing(.*)")
public @interface IntegrationTest {}

so then whenever your cmdline options contain -Pintegration-testing for instance, then and only then will your @IntegrationTest annotated test-class/method fire. Or, if you don't want to use (and setup) a specific maven profile but rather just pass in 'trigger' system properties by means of

mvn <cmds> -DmySystemPop=mySystemPropValue

and adjust your annotation interface to trigger on that (yes, there is also a @EnabledIfSystemProperty). Or making sure your shell is set up to contain 'whatever you need' or, as is suggested above, actually going through 'the pain' adding system env via your POM XML.

Having your code internally in runtime fiddle with env or mocking env, setting it up and then possibly 'clearing' runtime env to change itself during execution just seems like a bad, perhaps even dangerous, approach - it's easy to imagine someone will always sooner or later make a 'hidden' internal mistake that will go unnoticed for a while, just to arise suddenly and bite you hard in production later..? You usually prefer an approach entailing that 'given input' gives 'expected output', something that is easy to grasp and maintain over time, your fellow coders will just see it 'immediately'.

Well long 'answer' or maybe rather just an opinion on why you'd prefer this approach (yes, at first I just read the heading for this question and went ahead to answer that, ie 'How to test code dependent on environment variables using JUnit').

Python def function: How do you specify the end of the function?

Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended.

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

jQuery: selecting each td in a tr

You don't need a jQuery selector at all. You already have a reference to the cells in each row via the cells property.

$('#tblNewAttendees tr').each(function() {

    $.each(this.cells, function(){
        alert('hi');
    });

});

It is far more efficient to utilize a collection that you already have, than to create a new collection via DOM selection.

Here I've used the jQuery.each()(docs) method which is just a generic method for iteration and enumeration.

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

How can I get selector from jQuery object

This can get you selector path of clicked HTML element-

 $("*").on("click", function() {

    let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");

    alert(selectorPath);

    return false;

});

Set Session variable using javascript in PHP

If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

An error occurred while executing the command definition. See the inner exception for details

I had a similar situation with the 'An error occurred while executing the command definition' error. I had some views which were grabbing from another db which used current user security. The second db did not allow the login for the user of the first db causing this issue to occur. I added the db login to the server it was trying to get to from the original server and this fixed the issue. Check your views and see if there are any linked dbs which have different security than the db you are logging onto originally.

how to run a command at terminal from java program?

I know this question is quite old, but here's a library that encapsulates the ProcessBuilder api.

PHP UML Generator

Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).

Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.

If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?

Basicly I accept only one answer to that question. It just got too big and incomprehensible.

Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

Call to undefined function oci_connect()

I had the same issue, the solution on this page helped me, it's caused by using incompatible oci ddl files.

Hope it helps.

Should I learn C before learning C++?

I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.

In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.

Incorrect syntax near ''

I was using ADO.NET and was using SQL Command as:

 string query =
"SELECT * " +
"FROM table_name" +
"Where id=@id";

the thing was i missed a whitespace at the end of "FROM table_name"+ So basically it said

string query = "SELECT * FROM table_nameWHERE id=@id";

and this was causing the error.

Hope it helps

How do I add a resources folder to my Java project in Eclipse

Build Path -> Configure Build Path -> Libraries (Tab) -> Add Class Folder, then select your folder or create one.

How to get N rows starting from row M from sorted table in T-SQL

There is a pretty straight-forward method for T-SQL, although I'm not sure if it is prestanda-effective if you're skipping a large number of rows.

SELECT TOP numberYouWantToTake 
    [yourColumns...] 
FROM yourTable 
WHERE yourIDColumn NOT IN (
    SELECT TOP numberYouWantToSkip 
        yourIDColumn 
    FROM yourTable 
    ORDER BY yourOrderColumn
)
ORDER BY yourOrderColumn

If you're using .Net, you can use the following on for example an IEnumerable with your data results:

IEnumerable<yourDataType> yourSelectedData = yourDataInAnIEnumerable.Skip(nubmerYouWantToSkip).Take(numberYouWantToTake);

This has the backside that you're getting all the data from the data storage.

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help
  2. Install New Software ---> Add
  3. inside Add Repository write the Name: ADT (or whatever you want)
  4. and Location: https://dl-ssl.google.com/android/eclipse/
  5. after loading you should get Developer Tools and NDK Plugins
  6. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  7. click Next
  8. Finish

Exit a while loop in VBS/VBA

what about changing the while loop to a do while loop

and exit using

Exit Do

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

Fill remaining vertical space with CSS using display:flex

Make it simple : DEMO

_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  flex-flow: column;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background: tomato;_x000D_
  /* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;  /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;  /* min-height has its purpose :) , unless you meant height*/_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br/>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- uncomment to see it break -->_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- -->_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Full screen version

_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  flex-flow: column;_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background: tomato;_x000D_
  /* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;_x000D_
  /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
  /* min-height has its purpose :) , unless you meant height*/_x000D_
}_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br/>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- uncomment to see it break -->_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- -->_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

WiX tricks and tips

Registering .NET assemblies for COM Interop with x86/x64 compatibility

NB This fragment is essentially the same as REGASM Assembly.dll /codebase

A couple of things are going on in this sample so here's the code and I'll explain it afterwards...

  <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <?include $(sys.CURRENTDIR)\Config.wxi?>
  <?if $(var.Win64) ?>
  <?define CLSIDRoots = "CLSID;Wow6432Node\CLSID"?>
  <?else ?>
  <?define CLSIDRoots = "CLSID"?>
  <?endif?>
  <!-- ASCOM Driver Assembly with related COM registrations -->
  <Fragment>
    <DirectoryRef Id="INSTALLLOCATION" />
  </Fragment>
  <Fragment>
    <ComponentGroup Id="cgAscomDriver">
      <Component Id="cmpAscomDriver" Directory="INSTALLLOCATION" Guid="{0267031F-991D-4D88-A748-00EC6604171E}">
        <File Id="filDriverAssembly" Source="$(var.TiGra.Astronomy.AWRDriveSystem.TargetPath)" KeyPath="yes" Vital="yes" Assembly=".net" AssemblyApplication="filDriverAssembly"  />
        <RegistryKey Root="HKCR" Key="$(var.DriverId)"  Action="createAndRemoveOnUninstall">
          <RegistryValue Type="string" Value="$(var.DriverTypeName)"/>
          <RegistryKey Key="CLSID">
            <RegistryValue Type="string" Value="$(var.DriverGuid)" />
          </RegistryKey>
        </RegistryKey>
        <?foreach CLSID in $(var.CLSIDRoots) ?>
        <RegistryKey Root="HKCR" Key="$(var.CLSID)" Action="none">
          <RegistryKey Key="$(var.DriverGuid)" Action="createAndRemoveOnUninstall">
            <RegistryValue Type="string" Value="$(var.DriverTypeName)"/>
            <RegistryKey Key="InprocServer32">
              <RegistryValue Type="string" Value="mscoree.dll" />
              <RegistryValue Type="string" Name="ThreadingModel" Value="Both"/>
              <RegistryValue Type="string" Name="Class" Value="$(var.DriverTypeName)"/>
              <RegistryValue Type="string" Name="Assembly" Value="!(bind.assemblyFullname.filDriverAssembly)" />
              <RegistryValue Type="string" Name="RuntimeVersion" Value="v2.0.50727"/>
              <RegistryValue Type="string" Name="CodeBase" Value="file:///[#filDriverAssembly]" />
              <RegistryKey Key="!(bind.fileVersion.filDriverAssembly)" >
                <RegistryValue Type="string" Name="Class" Value="$(var.DriverTypeName)"/>
                <RegistryValue Type="string" Name="Assembly" Value="!(bind.assemblyFullname.filDriverAssembly)" />
                <RegistryValue Type="string" Name="RuntimeVersion" Value="v2.0.50727"/>
                <RegistryValue Type="string" Name="CodeBase" Value="file:///[#filDriverAssembly]" />
              </RegistryKey>
            </RegistryKey>
            <RegistryKey Key="ProgId" Action="createAndRemoveOnUninstall">
              <RegistryValue Type="string" Value="$(var.DriverId)" />
            </RegistryKey>
            <RegistryKey Key="Implemented Categories" Action="createAndRemoveOnUninstall" >
              <RegistryKey Key="{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}" Action="createAndRemoveOnUninstall" />
            </RegistryKey>
          </RegistryKey>
        </RegistryKey>
        <?endforeach?>
      </Component>
    </ComponentGroup>
  </Fragment>
</Wix>

If you were wondering, this is actually for an ASCOM Telescope Driver.

First, I took advice from above and created some platforma variables in a seperate file, you can see those scattered through the XML.

The if-then-else part near the top deals with x86 vs x64 compatibility. My assembly targets 'Any CPU' so on an x64 system, I need to register it twice, once in the 64-bit registry and once in the 32-bit Wow6432Node areas. The if-then-else sets me up for this, the values are used in a foreach loop later on. This way, I only have to author the registry keys once (DRY principle).

The file element specifies the actual assembly dll being installed and registered:

<File Id="filDriverAssembly" Source="$(var.TiGra.Astronomy.AWRDriveSystem.TargetPath)" KeyPath="yes" Vital="yes" Assembly=".net" AssemblyApplication="filDriverAssembly"  />

Nothing revolutionary, but notice the Assembly=".net" - this attribute alone would cause the assembly to be put into the GAC, which is NOT what I wanted. Using the AssemblyApplication attribute to point back to itself is simply a way of stopping Wix putting the file into the GAC. Now that Wix knows it's a .net assembly, though, it lets me use certain binder variables within my XML, such as the !(bind.assemblyFullname.filDriverAssembly) to get the assembly full name.

Use of #pragma in C

what i feel is #pragma is a directive where if you want the code to be location specific .say a situation where you want the program counter to read from the specific address where the ISR is written then you can specify ISR at that location using #pragma vector=ADC12_VECTOR and followd by interrupt rotines name and its description

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Reverse of JSON.stringify?

Check this out.
http://jsfiddle.net/LD55x/

Code:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

How to make fixed header table inside scrollable div?

This is my "crutches" solution by using html and css. There used 2 tables and fixed width of tables and table cell`s

https://jsfiddle.net/babaikawow/s2xyct24/1/

HTML:

  <div class="container">
<table class="table" border = 1; >  <!-- fixed width header -->
                            <thead >
                                <tr>
                                    <th class="tbDataId" >?</th>
                                    <th class="tbDataName">?????????</th>
                                    <th class="tbDataData">????</th>
                                    <th class="tbDataData">?????? ??</th>
                                    <th class="tbDataDiseases">????????1</th>
                                    <th class="tbDataDiseases">????????2</th>
                                    <th class="tbDataDiseases">????????3</th>
                                    <th class="tbDataDiseases">????????4</th>
                                    <th class="tbDataDiseases">????????5</th>  
                                </tr>
                            </thead>  
                        </table> 

                        <div class="scrollTable"> <!-- scrolling block -->
                            <table class="table" border = 1;>
                                 <tbody>
                   <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                                </tbody>
                            </table>
                        </div> 
</div>

CSS:

*{
  box-sizing: border-box;
}

.container{
 width:1000px;
}
.scrollTable{

    overflow: scroll;
  overflow-x: hidden;
    height: 100px;
} 
table{
margin: 0px!important;
width:983px!important;
border-collapse: collapse; 

}

/*   Styles of the th and td  */

/* Id */
.tbDataId{
    width:5%;
}

/* ????,
?????? ?? */
.tbDataData{
    /*width:170px;*/
    width: 15%;
}

/* ? ? ? */
.tbDataName{
    width: 15%;
}

/*???????? */
.tbDataDiseases{
    width:10%;
}

Recyclerview and handling different type of row inflation

The trick is to create subclasses of ViewHolder and then cast them.

public class GroupViewHolder extends RecyclerView.ViewHolder {
    TextView mTitle;
    TextView mContent;
    public GroupViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

public class ImageViewHolder extends RecyclerView.ViewHolder {
    ImageView mImage;
    public ImageViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;  

And then, at runtime do something like this:

@Override
public int getItemViewType(int position) {
    // here your custom logic to choose the view type
    return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}

@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {

    switch (viewHolder.getItemViewType()) {

        case TYPE_IMAGE:
            ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
            imageViewHolder.mImage.setImageResource(...);
            break;

        case TYPE_GROUP:
            GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
            groupViewHolder.mContent.setText(...)
            groupViewHolder.mTitle.setText(...);
            break;
    }
}

Hope it helps.

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

To alter a stored procedure, here's the C# code:

SqlConnection con = new SqlConnection("your connection string");
con.Open();
cmd.CommandType = System.Data.CommandType.Text;
string sql = File.ReadAllText(YUOR_SP_SCRIPT_FILENAME);
cmd.CommandText = sql;   
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();

Things to note:

  1. Make sure the USER in the connection string have the right to alter SP
  2. Remove all the GO,SET ANSI_NULLS XX,SET QUOTED_IDENTIFIER statements from the script file. (If you don't, the SqlCommand will throw an error).

Download a file from HTTPS using download.file()

I've succeed with the following code:

url = "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x = read.csv(file=url)

Note that I've changed the protocol from https to http, since the first one doesn't seem to be supported in R.

Index of duplicates items in a python list

Using new "Counter" class in collections module, based on lazyr's answer:

>>> import collections
>>> def duplicates(n): #n="123123123"
...     counter=collections.Counter(n) #{'1': 3, '3': 3, '2': 3}
...     dups=[i for i in counter if counter[i]!=1] #['1','3','2']
...     result={}
...     for item in dups:
...             result[item]=[i for i,j in enumerate(n) if j==item] 
...     return result
... 
>>> duplicates("123123123")
{'1': [0, 3, 6], '3': [2, 5, 8], '2': [1, 4, 7]}

What is App.config in C#.NET? How to use it?

App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

See this MSDN article on how to do that.

Android Studio shortcuts like Eclipse

in androidstudio 3.0(>=) in menu bar go to help-> keymap Reference It will give all the shortcuts .. link

How to expand 'select' option width after the user wants to select an option

If you have the option pre-existing in a fixed-with <select>, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.

  • You could try and set the title attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.
  • You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the not-so-nice way to do it, because it requires JavaScript on to work at all, and it works only after something has been selected - before there is a change in value no events fire for the select box.
  • You don't use a select box at all, but implement its functionality using other markup and CSS. Not my favorite but I wanted to mention it.

If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

How can I get a uitableViewCell by indexPath?

Finally, I get the cell using the following code:

UITableViewCell *cell = (UITableViewCell *)[(UITableView *)self.view cellForRowAtIndexPath:nowIndex];

Because the class is extended UITableViewController:

@interface SearchHotelViewController : UITableViewController

So, the self is "SearchHotelViewController".

When restoring a backup, how do I disconnect all active connections?

You want to set your db to single user mode, do the restore, then set it back to multiuser:

ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK AFTER 60 --this will give your current connections 60 seconds to complete

--Do Actual Restore
RESTORE DATABASE YourDB
FROM DISK = 'D:\BackUp\YourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf'

/*If there is no error in statement before database will be in multiuser
mode.  If error occurs please execute following command it will convert
database in multi user.*/
ALTER DATABASE YourDB SET MULTI_USER
GO

Reference : Pinal Dave (http://blog.SQLAuthority.com)

Official reference: https://msdn.microsoft.com/en-us/library/ms345598.aspx

Convert a list of objects to an array of one of the object's properties

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Yes, LINQ can do this. It's simply:

MyList.Select(x => x.Name).ToArray();

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.

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

You can use selectedIndex to retrieve the current selected option:

el = document.getElementById('elemId')
selectedText = el.options[el.selectedIndex].text

Detect WebBrowser complete page loading

I had the same issue of multiple DocumentCompleted fired events and tried out all the suggestions above. Finally, seems that in my case neither IsBusy property works right nor Url property, but the ReadyState seems to be what I needed, because it has the status 'Interactive' while loading the multiple frames and it gets the status 'Complete' only after loading the last one. Thus, I know when the page is fully loaded with all its components.

I hope this may help others too :)

Check if Variable is Empty - Angular 2

Lets say we have a variable called x, as below:

var x;

following statement is valid,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1. Number:

x = 10;
if(x){
//True
}

and for x = undefined or x = 0 (be careful here)

if(x){
 //False
}

2. String x = null , x = undefined or x = ""

if(x){
  //False
}

3 Boolean x = false and x = undefined,

if(x){
  //False
}

By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.

How to hide iOS status bar

In iOS10 all I needed to do is override the prefersStatusBarHidden var in my RootViewController (Swift):

override var prefersStatusBarHidden: Bool {
    return true
}

How to print instances of a class using print()?

If you're in a situation like @Keith you could try:

print(a.__dict__)

It goes against what I would consider good style but if you're just trying to debug then it should do what you want.

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Don't do this! You're opening your machine to attacks. Instead run a local server. It's as easy as opening a shell/terminal/commandline and typing

cd path/to/files
python -m SimpleHTTPServer

Then pointing your browser to

http://localhost:8000

If you find it's too slow consider this solution

React-Router: No Not Found Route?

With the new version of React Router (using 2.0.1 now), you can use an asterisk as a path to route all 'other paths'.

So it would look like this:

<Route route="/" component={App}>
    <Route path=":area" component={Area}>
        <Route path=":city" component={City} />
        <Route path=":more-stuff" component={MoreStuff} />    
    </Route>
    <Route path="*" component={NotFoundRoute} />
</Route>

how to add button click event in android studio

Your Activity must implement View.OnClickListener, like this:

public class MainActivity extends 
Activity implements View.OnClickListener{
// YOUR CODE
}

And inside MainActivity override the method onClick(), like this:

@override
public void onClick (View view){
//here YOUR Action response to Click Button 
}

Android: How to set password property in an edit text?

The only way that worked for me using code (not XML) is this one:

etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

sql primary key and index

NOTE: This answer addresses enterprise-class development in-the-large.

This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.

In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.

Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.

The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.

I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.

css label width not taking effect

Use display: inline-block;

Explanation:

The label is an inline element, meaning it is only as big as it needs to be.

Set the display property to either inline-block or block in order for the width property to take effect.

Example:

_x000D_
_x000D_
#report-upload-form {_x000D_
    background-color: #316091;_x000D_
    color: #ddeff1;_x000D_
    font-weight: bold;_x000D_
    margin: 23px auto 0 auto;_x000D_
    border-radius: 10px;_x000D_
    width: 650px;_x000D_
    box-shadow: 0 0 2px 2px #d9d9d9;_x000D_
_x000D_
}_x000D_
_x000D_
#report-upload-form label {_x000D_
    padding-left: 26px;_x000D_
    width: 125px;_x000D_
    text-transform: uppercase;_x000D_
    display: inline-block;_x000D_
}_x000D_
_x000D_
#report-upload-form input[type=text], _x000D_
#report-upload-form input[type=file],_x000D_
#report-upload-form textarea {_x000D_
    width: 305px;_x000D_
}
_x000D_
<form id="report-upload-form" method="POST" action="" enctype="multipart/form-data">_x000D_
    <p><label for="id_title">Title:</label> <input id="id_title" type="text" class="input-text" name="title"></p>_x000D_
    <p><label for="id_description">Description:</label> <textarea id="id_description" rows="10" cols="40" name="description"></textarea></p>_x000D_
    <p><label for="id_report">Upload Report:</label> <input id="id_report" type="file" class="input-file" name="report"></p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Encrypting & Decrypting a String in C#

If you are targeting ASP.NET Core that does not support RijndaelManaged yet, you can use IDataProtectionProvider.

First, configure your application to use data protection:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
    }
    // ...
}

Then you'll be able to inject IDataProtectionProvider instance and use it to encrypt/decrypt data:

public class MyService : IService
{
    private const string Purpose = "my protection purpose";
    private readonly IDataProtectionProvider _provider;

    public MyService(IDataProtectionProvider provider)
    {
        _provider = provider;
    }

    public string Encrypt(string plainText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Protect(plainText);
    }

    public string Decrypt(string cipherText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Unprotect(cipherText);
    }
}

See this article for more details.

How to submit a form using PhantomJS

As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:

casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
  this.fill('form#loginForm', {
    'login':    'admin',
    'password':    '12345678'
   }, true);
  this.evaluate(function(){
    //trigger click event on submit button
    document.querySelector('input[type="submit"]').click();
  });
});

Change old commit message on Git

FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!

git add only modified changes and ignore untracked files

You didn't say what's currently your .gitignore, but a .gitignore with the following contents in your root directory should do the trick.

.metadata
build

Difference between string and char[] types in C++

One of the difference is Null termination (\0).

In C and C++, char* or char[] will take a pointer to a single char as a parameter and will track along the memory until a 0 memory value is reached (often called the null terminator).

C++ strings can contain embedded \0 characters, know their length without counting.

#include<stdio.h>
#include<string.h>
#include<iostream>

using namespace std;

void NullTerminatedString(string str){
   int NUll_term = 3;
   str[NUll_term] = '\0';       // specific character is kept as NULL in string
   cout << str << endl <<endl <<endl;
}

void NullTerminatedChar(char *str){
   int NUll_term = 3;
   str[NUll_term] = 0;     // from specific, all the character are removed 
   cout << str << endl;
}

int main(){
  string str = "Feels Happy";
  printf("string = %s\n", str.c_str());
  printf("strlen = %d\n", strlen(str.c_str()));  
  printf("size = %d\n", str.size());  
  printf("sizeof = %d\n", sizeof(str)); // sizeof std::string class  and compiler dependent
  NullTerminatedString(str);


  char str1[12] = "Feels Happy";
  printf("char[] = %s\n", str1);
  printf("strlen = %d\n", strlen(str1));
  printf("sizeof = %d\n", sizeof(str1));    // sizeof char array
  NullTerminatedChar(str1);
  return 0;
}

Output:

strlen = 11
size = 11
sizeof = 32  
Fee s Happy


strlen = 11
sizeof = 12
Fee

Error: EACCES: permission denied

I tried most of these suggestions but none of them worked. Then I ran npm clean-install and it solved my issues.

Uncaught ReferenceError: angular is not defined - AngularJS not working

Use the ng-click directive:

<button my-directive ng-click="alertFn()">Click Me!</button>

// In <script>:
app.directive('myDirective' function() {
  return function(scope, element, attrs) {
    scope.alertFn = function() { alert('click'); };
  };
};

Note that you don't need my-directive in this example, you just need something to bind alertFn on the current scope.

Update: You also want the angular libraries loaded before your <script> block.

What is the purpose of the return statement?

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2

How to check if a file exists in Go?

What other answers missed, is that the path given to the function could actually be a directory. Following function makes sure, that the path is really a file.

func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}

Another thing to point out: This code could still lead to a race condition, where another thread or process deletes or creates the specified file, while the fileExists function is running.

If you're worried about this, use a lock in your threads, serialize the access to this function or use an inter-process semaphore if multiple applications are involved. If other applications are involved, outside of your control, you're out of luck, I guess.