Programs & Examples On #Strikethrough

Is there an easy way to strike through text in an app widget?

For Lollipop and above. create a drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="line">
            <stroke android:width="1dp"
                android:color="@color/onePlusRed" />
        </shape>
    </item>
</selector>

and use it as foreground.
android:foreground="@drawable/strike_through"

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

Spring can you autowire inside an abstract class?

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:

public abstract class EO {
    @Autowired
    protected SmsNotificationService smsNotificationService;
    @Autowired
    protected SendEmailService sendEmailService;
    ...
    protected abstract void executeOperation(GenericMessage gMessage);
}

public final class OperationsExecutor {
    public enum OperationsType {
        ENROLL, CAMPAIGN
    }

    private OperationsExecutor() {
    }

    public static Object delegateOperation(OperationsType type, Object obj) 
    {
        switch(type) {
            case ENROLL:
                if (obj == null) {
                    return new EnrollOperation();
                }
                return EnrollOperation.validateRequestParams(obj);
            case CAMPAIGN:
                if (obj == null) {
                    return new CampaignOperation();
                }
                return CampaignOperation.validateRequestParams(obj);
            default:
                throw new IllegalArgumentException("OperationsType not supported.");
        }
    }
}

@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
    @Override
    public void executeOperation(GenericMessage genericMessage) {
        LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring autowire dependency defined in an abstract class

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

How to set header and options in axios?

I had to create a fd=new FormData() object and use the [.append()][1] method before sending it through axios to my Django API, otherwise I receive a 400 error. In my backend the profile image is related through a OneToOne relationship to the user model. Therefore it is serialized as a nested object and expects this for the put request to work.

All changes to the state within the frontend are done with the this.setState method. I believe important part is the handleSubmit method at the end.

First my axios put request:

export const PutUser=(data)=>(dispatch,getState)=>{                                                                                                                                                                                                                                                                                                                                                                                                                                           
    dispatch({type: AUTH_USER_LOADING});                                                                                                                                                                                                 
    const token=getState().auth.token;                                                                                                                                                                                                                       
    axios(                                                                                                                                                                                                                                                   
    {                                                                                                                                                                                                                                                        
    ¦ method:'put',                                                                                                                                                                                                                                          
    ¦ url:`https://<xyz>/api/account/user/`,                                                                                                                                                                                           
    ¦ data:data,                                                                                                                                                                                                                                             
    ¦ headers:{                                                                                                                                                                                                                                              
    ¦ ¦ Authorization: 'Token '+token||null,                                                                                                                                                                                                                 
    ¦ ¦ 'Content-Type': 'multipart/form-data',                                                                                                                                                                                                               
    ¦ }                                                                                                                                                                                                                                                      
    })                                                                                                                                                                                                                                                       
    ¦ .then(response=>{                                                                                                                                                                                                                                      
    ¦ ¦ dispatch({                                                                                                                                                                                                                                           
    ¦ ¦ ¦ type: AUTH_USER_PUT,                                                                                                                                                                                                                               
    ¦ ¦ ¦ payload: response.data,                                                                                                                                                                                                                            
    ¦ ¦ });                                                                                                                                                                                                                                                  
    ¦ })                                                                                                                                                                                                                                                     
    ¦ .catch(err=>{                                                                                                                                                                                                                                          
    ¦ ¦ dispatch({                                                                                                                                                                                                                                           
    ¦ ¦ ¦ type:AUTH_USER_PUT_ERROR,                                                                                                                                                                                                                          
    ¦ ¦ ¦ payload: err,                                                                                                                                                                                                                                      
    ¦ ¦ });                                                                                                                                                                                                                                                  
    ¦ })                                                                                                                                                                                                                                                     
  }      

My handleSubmit method needs to create the following json object, where the image attribute gets replaced by the actual user input:

user:{
username:'charly',
first_name:'charly',
last_name:'brown',
profile:{
image: 'imgurl',
  }
}

Here is my handleSumit method inside the component: check append

handleSubmit=(e)=>{                                                                                                                                                                                                                                      
¦ e.preventDefault();                                                                                                                                                                                                                                                                                                                                                                                                                  
¦ let fd=new FormData();                                                                                                                                                                                                                                 
¦ fd.append('username',this.state.username);                                                                                                                                                                                                             
¦ fd.append('first_name',this.state.first_name);                                                                                                                                                                                                         
¦ fd.append('last_name',this.state.last_name);                                                                                                                                                                                                                                                                                                                                                                                                                  
¦ if(this.state.image!=null){fd.append('profile.image',this.state.image, this.state.image.name)};                                                                                                                                                                                                                                                                                                                                                        
¦ this.props.PutUser(fd);                                                                                                                                                                                                                                
}; 

Issue with background color and Google Chrome

I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.

IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.

Check whether user has a Chrome extension installed

If you have control over the Chrome extension, you can try what I did:

// Inside Chrome extension
var div = document.createElement('div');
div.setAttribute('id', 'myapp-extension-installed-div');
document.getElementsByTagName('body')[0].appendChild(div);

And then:

// On web page that needs to detect extension
if ($('#myapp-extension-installed-div').length) {

}

It feels a little hacky, but I couldn't get the other methods to work, and I worry about Chrome changing its API here. It's doubtful this method will stop working any time soon.

Including jars in classpath on commandline (javac or apt)

javac HelloWorld.java -classpath ./javax.jar , assuming javax is in current folder, and compile target is "HelloWorld.java", and you can compile without a main method

How to convert POJO to JSON and vice versa?

We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:

Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());

Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);

And the Maven settings:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>1.7.1</version>
</dependency>

<plugin>
    <groupId>com.googlecode.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>0.3.7</version>
    <configuration>
        <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
        <targetPackage>com.example.types</targetPackage>
    </configuration>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Converting <br /> into a new line for use in a text area

Here is another approach.

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
        $buff = trim($buff);

        return $buff;
    }
}

how to check if item is selected from a comboBox in C#

Here is the perfect coding which checks whether the Combo Box Item is Selected or not

if (string.IsNullOrEmpty(comboBox1.Text))
{
    MessageBox.Show("No Item is Selected"); 
}
else
{
    MessageBox.Show("Item Selected is:" + comboBox1.Text);
}

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I have tried all suggestions and found my own simple solution.

The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008.

Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat. I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS.

You can find my step by step solution below:

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS90COMNTOOLS to the variable name
  7. Enter the value of current version to the new variable.
  8. Close all windows

Now open a new session and pip install your-package

convert a JavaScript string variable to decimal/money

I made a little helper function to do this and catch all malformed data

function convertToPounds(str) { 
    var n = Number.parseFloat(str);
    if(!str || isNaN(n) || n < 0) return 0;
    return n.toFixed(2);
}

Demo is here

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

How do I search for an object by its ObjectId in the mongo console?

If you are working on the mongo shell, Please refer this : Answer from Tyler Brock

I wrote the answer if you are using mongodb using node.js

You don't need to convert the id into an ObjectId. Just use :

db.collection.findById('4ecbe7f9e8c1c9092c000027');

this collection method will automatically convert id into ObjectId.

On the other hand :

db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.

That can be done like this :

let id = '58c85d1b7932a14c7a0a320d';

let o_id = new ObjectId(id);   // id as a string is passed

db.collection.findOne({"_id":o_id});

static linking only some libraries

You could also use ld option -Bdynamic

gcc <objectfiles> -static -lstatic1 -lstatic2 -Wl,-Bdynamic -ldynamic1 -ldynamic2

All libraries after it (including system ones linked by gcc automatically) will be linked dynamically.

How to save a git commit message from windows cmd?

If you enter git commit but omit to enter a comment using the –m parameter, then Git will open up the default editor for you to edit your check-in note. By default that is Vim. Now you can do two things:

Alternative 1 – Exit Vim without entering any comment and repeat

A blank or unsaved comment will be counted as an aborted attempt to commit your changes and you can exit Vim by following these steps:

  1. Press Esc to make sure you are not in edit mode (you can press Esc several times if you are uncertain)

  2. Type :q! enter
    (that is, colon, letter q, exclamation mark, enter), this tells Vim to discard any changes and exit)
    Git will then respond:

    Aborting commit due to empty commit message

    and you are once again free to commit using:

    git commit –m "your comment here"
    

Alternative 2 – Use Vim to write a comment

Follow the following steps to use Vim for writing your comments

  1. Press i to enter Edit Mode (or Insert Mode).
    That will leave you with a blinking cursor on the first line. Add your comment. Press Esc to make sure you are not in edit mode (you can press Esc several time if you are uncertain)
  2. Type :wq enter
    (that is colon, letter w, letter q, enter), this will tell Vim to save changes and exit)

Response from https://blogs.msdn.microsoft.com/kristol/2013/07/02/the-git-command-line-101-for-windows-users/

Reverse / invert a dictionary mapping

This handles non-unique values and retains much of the look of the unique case.

inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}

For Python 3.x, replace itervalues with values.

Structs data type in php?

You can use an array

$something = array(
   'key' => 'value',
   'key2' => 'value2'
);

or with standard object.

$something = new StdClass();

$something->key = 'value';
$something->key2 = 'value2';

How to pass the values from one jsp page to another jsp without submit button?

You just have to include following script.

<script language="javascript" type="text/javascript">  
        var xmlHttp  
        function showState(str)
        {
            //if you want any text box value you can get it like below line. 
            //just make sure you have specified its "id" attribute
            var name=document.getElementById("id_attr").value;
            if (typeof XMLHttpRequest != "undefined")
            {
              xmlHttp= new XMLHttpRequest();
            }
            var url="forwardPage.jsp";
            url +="?count1=" +str+"&count2="+name";
            xmlHttp.onreadystatechange = stateChange;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        }
        function stateChange()
        {   
            if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
            {   
                document.getElementById("div_id").innerHTML=xmlHttp.responseText   
            }   
        }
      </script>

So if you got the code, let me tell you, div_id will be id of div tag where you have to show your result. By using this code, you are passing parameters to another page. Whatever the processing is done there will be reflected in div tag whose id is "div_id". You can call showState(this.value) on "onChange" event of any control or "onClick" event of button not submit. Further queries will be appreciated.

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

OpenCV - Saving images to a particular folder of choice

Thank you everyone. Your ways are perfect. I would like to share another way I used to fix the problem. I used the function os.chdir(path) to change local directory to path. After which I saved image normally.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Different version similar to the one offered by Maxim Shoustin

I liked the answer but the part that bothered me was the use of <script id="..."> as a container for the modal's template.

I wanted to place the modal's template in a hidden <div> and bind the inner html with a scope variable called modal_html_template mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div> instead of <script id="...">

this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})

in order to bind the inner html, i created inner-html-bind which is a simple directive

check out the example plunker

<div ng-controller="ModalDemoCtrl">

    <div inner-html-bind inner-html="modal_html_template" class="hidden">
        <div class="modal-header">
            <h3>I'm a modal!</h3>
        </div>
        <div class="modal-body">
            <ul>
                <li ng-repeat="item in items">
                    <a ng-click="selected.item = item">{{ item }}</a>
                </li>
            </ul>
            Selected: <b>{{ selected.item }}</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </div>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>

inner-html-bind directive:

app.directive('innerHtmlBind', function() {
  return {
    restrict: 'A',
    scope: {
      inner_html: '=innerHtml'
    },
    link: function(scope, element, attrs) {
      scope.inner_html = element.html();
    }
  }
});

NoClassDefFoundError - Eclipse and Android

Sometimes it will happen due to not including jar, which you have dependency, with "uses-libary" tag in your AndroidManifest.xml.

Also, make sure it should be inside "application" tag.

Regards,

Ravi

Leaflet - How to find existing markers, and delete markers?

When you save the reverence to the marker in the adding function the marker can remove it self. No need for arrays.

function addPump(){
   var pump = L.marker(cords,{icon: truckPump}).addTo(map).bindPopup($('<a href="#" class="speciallink">Remove ME</a>').click(function() {
            map.removeLayer(pump);
          })[0]);
        }

Access multiple elements of list knowing their index

Basic and not very extensive testing comparing the execution time of the five supplied answers:

def numpyIndexValues(a, b):
    na = np.array(a)
    nb = np.array(b)
    out = list(na[nb])
    return out

def mapIndexValues(a, b):
    out = map(a.__getitem__, b)
    return list(out)

def getIndexValues(a, b):
    out = operator.itemgetter(*b)(a)
    return out

def pythonLoopOverlap(a, b):
    c = [ a[i] for i in b]
    return c

multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]

using the following input:

a = range(0, 10000000)
b = range(500, 500000)

simple python loop was the quickest with lambda operation a close second, mapIndexValues and getIndexValues were consistently pretty similar with numpy method significantly slower after converting lists to numpy arrays.If data is already in numpy arrays the numpyIndexValues method with the numpy.array conversion removed is quickest.

numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995

Get a list of URLs from a site

Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.

Replacing accented characters php

I have tried all sorts based on the variations listed in the answers, but the following worked:

$unwanted_array = array(    'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                            'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                            'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                            'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                            'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$str = strtr( $str, $unwanted_array );

Shorter syntax for casting from a List<X> to a List<Y>?

In case when X derives from Y you can also use ToList<T> method instead of Cast<T>

listOfX.ToList<Y>()

specifying goal in pom.xml

Add the goal like -

 <build>
        <defaultGoal>install</defaultGoal>
        <!-- Source directory configuration -->
        <sourceDirectory>src</sourceDirectory>
</build>

This will solve the issue

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">

This is not supported with all browsers though (IE)

This may work:

<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">

Otherwise, if you are using jQuery, you can use .focus and .css to change the color.

How do I sort a VARCHAR column in SQL server that contains numbers?

SELECT *, CONVERT(int, your_column) AS your_column_int
FROM your_table
ORDER BY your_column_int

OR

SELECT *, CAST(your_column AS int) AS your_column_int
FROM your_table
ORDER BY your_column_int

Both are fairly portable I think.

HTML5: Slider with two inputs possible?

No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

I get this fairly regularily. Currently what's working for me (with Photon) is:

  • Close project
  • Open project

If this doesn't work :

  • Close project
  • Exit Eclipse
  • Restart Eclipse
  • Open Project

I know, stupid isn't it.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

The ActionBar will use the android:logo attribute of your manifest, if one is provided. That lets you use separate drawable resources for the icon (Launcher) and the logo (ActionBar, among other things).

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

What does MVW stand for?

I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.

It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.

In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.

I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.

How to bring a window to the front?

I tested your answers and only Stefan Reich's one worked for me. Although I couldn't manage to restore the window to its previous state (maximized/normal). I found this mutation better:

view.setState(java.awt.Frame.ICONIFIED);
view.setState(java.awt.Frame.NORMAL);

That is setState instead of setExtendedState.

How to list all dates between two dates

You can create a stored procedure passing 2 dates

CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);

Create table #tmpDates
(displayDate date)

WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END

Select * 
from #tmpDates

drop table #tmpDates

adding and removing classes in angularJs using ng-click

I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.

<ul ng-init="selectedTab = 'users'">
   <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
   <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>

How do I create a custom Error in JavaScript?

I had a similar issue to this. My error needs to be an instanceof both Error and NotImplemented, and it also needs to produce a coherent backtrace in the console.

My solution:

var NotImplemented = (function() {
  var NotImplemented, err;
  NotImplemented = (function() {
    function NotImplemented(message) {
      var err;
      err = new Error(message);
      err.name = "NotImplemented";
      this.message = err.message;
      if (err.stack) this.stack = err.stack;
    }
    return NotImplemented;
  })();
  err = new Error();
  err.name = "NotImplemented";
  NotImplemented.prototype = err;

  return NotImplemented;
}).call(this);

// TEST:
console.log("instanceof Error: " + (new NotImplemented() instanceof Error));
console.log("instanceof NotImplemented: " + (new NotImplemented() instanceofNotImplemented));
console.log("message: "+(new NotImplemented('I was too busy').message));
throw new NotImplemented("just didn't feel like it");

Result of running with node.js:

instanceof Error: true
instanceof NotImplemented: true
message: I was too busy

/private/tmp/t.js:24
throw new NotImplemented("just didn't feel like it");
      ^
NotImplemented: just didn't feel like it
    at Error.NotImplemented (/Users/colin/projects/gems/jax/t.js:6:13)
    at Object.<anonymous> (/Users/colin/projects/gems/jax/t.js:24:7)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:487:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

The error passes all 3 of my criteria, and although the stack property is nonstandard, it is supported in most newer browsers which is acceptable in my case.

Django datetime issues (default=datetime.now())

In Django 3.0 auto_now_add seems to work with auto_now

reg_date=models.DateField(auto_now=True,blank=True)

Implode an array with JavaScript?

You can do this in plain JavaScript, use Array.prototype.join:

arrayName.join(delimiter);

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

If you want to drop rows of data frame on the basis of some complicated condition on the column value then writing that in the way shown above can be complicated. I have the following simpler solution which always works. Let us assume that you want to drop the column with 'header' so get that column in a list first.

text_data = df['name'].tolist()

now apply some function on the every element of the list and put that in a panda series:

text_length = pd.Series([func(t) for t in text_data])

in my case I was just trying to get the number of tokens:

text_length = pd.Series([len(t.split()) for t in text_data])

now add one extra column with the above series in the data frame:

df = df.assign(text_length = text_length .values)

now we can apply condition on the new column such as:

df = df[df.text_length  >  10]
def pass_filter(df, label, length, pass_type):

    text_data = df[label].tolist()

    text_length = pd.Series([len(t.split()) for t in text_data])

    df = df.assign(text_length = text_length .values)

    if pass_type == 'high':
        df = df[df.text_length  >  length]

    if pass_type == 'low':
        df = df[df.text_length  <  length]

    df = df.drop(columns=['text_length'])

    return df

How to apply slide animation between two activities in Android?

enter image description here

You can overwrite your default activity animation and it perform better than overridePendingTransition. I use this solution that work for every android version. Just copy paste 4 files and add a 4 lines style as below:

Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>

</style>

<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>

Then Create anim folder under res folder and then create this four animation files into anim folder:

slide_in_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_in_left.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

If you face any problem then you can download my sample project from github.

Thanks

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

HTML favicon won't show on google chrome

The path must be via the URI (full).

Like: http://example.com/favicon.png

so in your case:

<!DOCTYPE html>
<html> 
    <head profile="http://www.w3.org/2005/10/profile">
        <title></title>
        <link rel="shortcut icon" 
              type="image/png" 
              href=" http://example.com/favicon.png" />
    </head>
    <body>
    </body>
</html>

Ref: http://www.w3.org/2005/10/howto-favicon

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /?)

Its effect lives for the duration of the script, or an ENDLOCAL:

When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION in a script, any environment variable changes are lost at the end of it unless you take special measures.

What is the difference between class and instance methods?

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:

enter image description here

A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.

enter image description here

An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

How to validate an e-mail address in swift?

I improved @Azik answer. I allow more special characters which are allowed by guidelines, as well as return a few extra edge cases as invalid.

The group think going on here to only allow ._%+- in the local part is not correct per guidelines. See @Anton Gogolev answer on this question or see below:

The local-part of the email address may use any of these ASCII characters:

  • uppercase and lowercase Latin letters A to Z and a to z;

  • digits 0 to 9;

  • special characters !#$%&'*+-/=?^_`{|}~;

  • dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but "John..Doe"@example.com is allowed);

  • space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); comments are allowed

  • with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected];

The code I use will not allow restricted out of place special characters, but will allow many more options than the majority of answers here. I would prefer more relaxed validation to error on the side of caution.

if enteredText.contains("..") || enteredText.contains("@@") 
   || enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
       return false
}

let emailFormat = "[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)     
return emailPredicate.evaluate(with: enteredText)

What does git rev-parse do?

git rev-parse is an ancillary plumbing command primarily used for manipulation.

One common usage of git rev-parse is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short for printing a shorter unique SHA1.

There are other use cases as well (in scripts and other tools built on top of git) that I've used for:

  • --verify to verify that the specified object is a valid git object.
  • --git-dir for displaying the abs/relative path of the the .git directory.
  • Checking if you're currently within a repository using --is-inside-git-dir or within a work-tree using --is-inside-work-tree
  • Checking if the repo is a bare using --is-bare-repository
  • Printing SHA1 hashes of branches (--branches), tags (--tags) and the refs can also be filtered based on the remote (using --remote)
  • --parse-opt to normalize arguments in a script (kind of similar to getopt) and print an output string that can be used with eval

Massage just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:

  • a branch or tag name into the commit's SHA1 it is pointing to so that it can be passed to a plumbing command which only accepts SHA1 values for the commit.
  • a revision range A..B for git log or git diff into the equivalent arguments for the underlying plumbing command as B ^A

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

How to set delay in vbscript

As stated in this answer:

Application.Wait (Now + TimeValue("0:00:01"))

will wait for 1 second

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER and possibly _MSC_FULL_VER is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples.

Some values for the more recent versions of the compiler are:

MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2  _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1  _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0  _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0  _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0  _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0  _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0   _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0   _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0   _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1   _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0   _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0   _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0   _MSC_VER == 1100 (Visual Studio 97 version 5.0)

The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found here. Starting recently, Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.

cl.exe /? will give a hint of the used version, e.g.:

c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....

Remove a folder from git tracking

This works for me:

git rm -r --cached --ignore-unmatch folder_name

--ignore-unmatch is important here, without that option git will exit with error on the first file not in the index.

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

How to compare dates in datetime fields in Postgresql?

@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

Highlight text similar to grep, but don't filter out text

If you want to print "all" lines, there is a simple working solution:

grep "test" -A 9999999 -B 9999999
  • A => After
  • B => Before

CUDA incompatible with my gcc version

Gearoid Murphy's solution works like a charm. For me I had two directories for cuda -

/usr/local/cuda 
/usr/local/cuda-5.0

The soft links had to be added only to the directory mentioned below -

/usr/local/cuda 

Also, both g++ and gcc soft links were required as mentioned by SchighSchagh.

Listing information about all database files in SQL Server

The query will error if multiple data files (e.g. ".ndf" file types) are used in one of the databases.

Here's a version of your query using joins instead of the sub-queries.

Cheers!

SELECT
    db.name AS DBName,
    db.database_id,
    mfr.physical_name AS DataFile,
    mfl.physical_name AS LogFile
FROM sys.databases db
    JOIN sys.master_files mfr ON db.database_id=mfr.database_id AND mfr.type_desc='ROWS'
    JOIN sys.master_files mfl ON db.database_id=mfl.database_id AND mfl.type_desc='LOG'
ORDER BY db.database_id

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

Converting 'ArrayList<String> to 'String[]' in Java

in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:

import java.util.ArrayList; import java.lang.reflect.Array;

public class Test {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<>();
    al.add(1);
    al.add(2);
    Integer[] arr = convert(al, Integer.class);
    for (int i=0; i<arr.length; i++)
      System.out.println(arr[i]);
  }

  public static <T> T[] convert(ArrayList<T> al, Class clazz) {
    return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
  }
}

Reset all changes after last commit in git

How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?

  1. You can undo changes to tracked files with:

    git reset HEAD --hard
    
  2. You can remove untracked files with:

    git clean -f
    
  3. You can remove untracked files and directories with:

    git clean -fd
    

    but you can't undo change to untracked files.

  4. You can remove ignored and untracked files and directories

    git clean -fdx
    

    but you can't undo change to ignored files.

You can also set clean.requireForce to false:

git config --global --add clean.requireForce false

to avoid using -f (--force) when you use git clean.

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How to make <input type="file"/> accept only these types?

for powerpoint and pdf files:

<html>
<input type="file" placeholder="Do you have a .ppt?" name="pptfile" id="pptfile" accept="application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
</html>

How to enable CORS in ASP.net Core WebAPI

below is the settings which works for me: enter image description here

SelectedValue vs SelectedItem.Value of DropDownList

In droupDown list there are two item add property.

1) Text 2) value

If you want to get text property then u use selecteditem.text

and If you want to select value property then use selectedvalue property

In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text

If both are different then they give us different results

How to make picturebox transparent?

I've had a similar problem like this. You can not make Transparent picturebox easily such as picture that shown at top of this page, because .NET Framework and VS .NET objects are created by INHERITANCE! (Use Parent Property).

I solved this problem by RectangleShape and with the below code I removed background, if difference between PictureBox and RectangleShape is not important and doesn't matter, you can use RectangleShape easily.

private void CreateBox(int X, int Y, int ObjectType)
{
    ShapeContainer canvas = new ShapeContainer();
    RectangleShape box = new RectangleShape();
    box.Parent = canvas;
    box.Size = new System.Drawing.Size(100, 90);
    box.Location = new System.Drawing.Point(X, Y);
    box.Name = "Box" + ObjectType.ToString();
    box.BackColor = Color.Transparent;
    box.BorderColor = Color.Transparent;
    box.BackgroundImage = img.Images[ObjectType];// Load from imageBox Or any resource
    box.BackgroundImageLayout = ImageLayout.Stretch;
    box.BorderWidth = 0;
    canvas.Controls.Add(box);   // For feature use 
}

The difference between sys.stdout.write and print?

Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:

import sys
temp = sys.stdout                 # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123")               # nothing appears at interactive prompt
print("another line")             # again nothing appears. it's written to log file instead
sys.stdout.close()                # ordinary file object
sys.stdout = temp                 # restore print commands to interactive prompt
print("back to normal")           # this shows up in the interactive prompt

Opening log.txt in a text editor will reveal the following:

testing123
another line

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Global variables in header file

The currently-accepted answer to this question is wrong. C11 6.9.2/2:

If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

So the original code in the question behaves as if file1.c and file2.c each contained the line int i = 0; at the end, which causes undefined behaviour due to multiple external definitions (6.9/5).

Since this is a Semantic rule and not a Constraint, no diagnostic is required.

Here are two more questions about the same code with correct answers:

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan

Run bash command on jenkins pipeline

I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)

Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps

pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

enter image description here

Is a DIV inside a TD a bad idea?

Two ways of dealing with it

  1. put div inside tbody tag
  2. put div inside tr tag

Both approaches are valid, if you see feference: https://stackoverflow.com/a/23440419/2305243

JavaScript split String with white space

You can just split on the word boundary using \b. See MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red" still work:

var stringArray = str.split(/\b(\s)/);

The initial \b is required to take multiple spaces into account, e.g. my car is red

EDIT: Added grouping

highlight the navigation menu for the current page

You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...

That probably didn't make much sense, so here's an example:

<body id="index">
<div id="menu">
 <ul>
  <li class="index"     ><a href="index.html">Index page</a></li>
  <li class="page1"     ><a href="page1.html">Page 1</a></li>
 </ul>
</div> <!-- menu -->
</body>

In the page1.html, you would set the id of the body to: id="page1".

Finally in your CSS you have something like the following:

#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.

It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.

Can't escape the backslash with regex?

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.

\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.

ref : http://www.regular-expressions.info/reference.html

How to set the timezone in Django?

Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:

Area is a continent or ocean name. Area currently includes:

  • Africa
  • America (both North America and South America)
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Etc (administrative zone. For example, “Etc/UTC” represents Coordinated Universal Time.)
  • Indian
  • Pacific

Location is the city, island, or other regional name.

The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).

Here is a list all valid timezones

You can change time zone in your settings.py as follows

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Better way to check variable for null or empty string?

to be more robust (tabulation, return…), I define:

function is_not_empty_string($str) {
    if (is_string($str) && trim($str, " \t\n\r\0") !== '')
        return true;
    else
        return false;
}

// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    var_export($value);
    if (is_not_empty_string($value)) 
        print(" is a none empty string!\n");
    else
        print(" is not a string or is an empty string\n");
}

sources:

List comprehension on a nested list?

If you don't like nested list comprehensions, you can make use of the map function as well,

>>> from pprint import pprint

>>> l = l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] 

>>> pprint(l)
[['40', '20', '10', '30'],
['20', '20', '20', '20', '20', '30', '20'],
['30', '20', '30', '50', '10', '30', '20', '20', '20'],
['100', '100'],
['100', '100', '100', '100', '100'],
['100', '100', '100', '100']]

>>> float_l = [map(float, nested_list) for nested_list in l]

>>> pprint(float_l)
[[40.0, 20.0, 10.0, 30.0],
[20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0],
[30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0],
[100.0, 100.0],
[100.0, 100.0, 100.0, 100.0, 100.0],
[100.0, 100.0, 100.0, 100.0]]

AJAX cross domain call

JSONP is the best option, in my opinion. Try to figure out why you get the syntax error - are you sure the received data is not JSON? Then maybe you're using the API wrong somehow.

Another way you could use, but I don't think that it applies in your case, is have an iFrame in the page which src is in the domain you want to call. Have it do the calls for you, and then use JS to communicate between the iFrame and the page. This will bypass the cross domain, but only if you can have the iFrame's src in the domain you want to call.

Type List vs type ArrayList in Java

Out of the following two:

(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();

First is generally preferred. As you will be using methods from List interface only, it provides you the freedom to use some other implementation of List e.g. LinkedList in future. So it decouples you from specific implementation. Now there are two points worth mentioning:

  1. We should always program to interface. More here.
  2. You will almost always end up using ArrayList over LinkedList. More here.

I am wondering if anyone uses (2)

Yes sometimes (read rarely). When we need methods that are part of implementation of ArrayList but not part of the interface List. For example ensureCapacity.

Also, how often (and can I please get an example) does the situation actually require using (1) over (2)

Almost always you prefer option (1). This is a classical design pattern in OOP where you always try to decouple your code from specific implementation and program to the interface.

Javascript Get Element by Id and set the value

Coming across this question, no answer brought up the possibility of using .setAttribute() in addition to .value()

document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");

Though unlikely helpful for the original questioner, this addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset()-proof.

I hope this may help others.

(Or me in half a year when I've forgotten about js quirks...)

Image is not showing in browser?

the easy way to do it to place the image in Web Content and then right click on it and then open it by your eclipse or net beans web Browser it will show the page where you can see the URL which is the exact path then copy the URL and place it on src=" paste URL " ;

Comparing floating point number to zero

Like @Exceptyon pointed out, this function is 'relative' to the values you're comparing. The Epsilon * abs(x) measure will scale based on the value of x, so that you'll get a comparison result as accurately as epsilon, irrespective of the range of values in x or y.

If you're comparing zero(y) to another really small value(x), say 1e-8, abs(x-y) = 1e-8 will still be much larger than epsilon *abs(x) = 1e-13. So unless you're dealing with extremely small number that can't be represented in a double type, this function should do the job and will match zero only against +0 and -0.

The function seems perfectly valid for zero comparison. If you're planning to use it, I suggest you use it everywhere there're floats involved, and not have special cases for things like zero, just so that there's uniformity in the code.

ps: This is a neat function. Thanks for pointing to it.

Why doesn't Git ignore my specified file?

I tried most commands above on VS Code terminal and I got errors like:

fatal: pathspec '[dir]/[file]' did not match any files

I opened the project on GitHub Desktop and ignored from there and it worked.

PHPExcel auto size column width

Come late, but after searching everywhere, I've created a solution that seems to be "the one".

Being known that there is a column iterator on last API versions, but not knowing how to atuoadjust the column object it self, basically I've created a loop to go from real first used column to real last used one.

Here it goes:

//Just before saving de Excel document, you do this:

PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);

//We get the util used space on worksheet. Change getActiveSheet to setActiveSheetIndex(0) to choose the sheet you want to autosize. Iterate thorugh'em if needed.
//We remove all digits from this string, which cames in a form of "A1:G24".
//Exploding via ":" to get a 2 position array being 0 fisrt used column and 1, the last used column.
$cols = explode(":", trim(preg_replace('/\d+/u', '', $objPHPExcel->getActiveSheet()->calculateWorksheetDimension())));

$col = $cols[0]; //first util column with data
$end = ++$cols[1]; //last util column with data +1, to use it inside the WHILE loop. Else, is not going to use last util range column.
while($col != $end){
    $objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);

    $col++;
}

//Saving.
$objWriter->save('php://output');

How can I store HashMap<String, ArrayList<String>> inside a list?

First you need to define the List as :

List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :

list.add(map);

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Try to add the path to tnsnames.ora to the config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <oracle.manageddataaccess.client>
    <version number="4.112.3.60">
      <settings>
        <setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
      </settings>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

How to check if an int is a null

A primitive int cannot be null. If you need null, use Integer instead.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I know this is a somewhat old thread, but I had this problem too with a c#/WPF app I was creating. The app worked fine on the development machine, but would not start on the test machine. The Application Log in the Event Viewer gave a somewhat nebulous .NET Runtime error of System.IO.DirectoryNotFoundException.

I tried using some debugging software but the app would not stay running long enough to attach the debugger to the process. After banging my head against my desk for a day and looking at many web pages like this one, what I wound up doing to troubleshoot this was to install VS2019 on my test machine. I then dragged the .exe file from its folder (it was deep in the Users[user]\AppData\Apps\2.0... folder) to the open VS2019 instance and went to start it from there. Immediately, it came up with a dialog box giving the exception and the cause.

In my case, when I added an icon to one of the forms, the complete path to the icon was placed into the XAML instead of just the icon name. I had copied the icon file into the project folder, but since the project folder does not exist on the test machine, this was the root cause of the error. I then removed the path from the XAML, leaving just the icon name one, rebuilt the solution and re-published it, and it ran just fine on the test machine now. Of course there are many causes besides what gave me the error, but this method of troubleshooting should hopefully identify the root cause of the error, since the Windows Event Viewer gives a somewhat vague answer.

To summarize, use Visual Studio on the test machine as a debugger of sorts. But, to get it to work right, I had to drag the .exe file into the IDE and Start (run) it from there. I believe this will also work with VS2017 as well as VS2019. Hopefully this helps someone who is still having this issue.

Convert String into a Class Object

Much easier way of doing it: you will need com.google.gson.Gson for converting the object to json string for streaming

to convert object to json string for streaming use below code

Gson gson = new Gson();
String jsonString = gson.toJson(MyObject);

To convert back the json string to object use below code:

Gson gson = new Gson();
MyObject = gson.fromJson(decodedString , MyObjectClass.class);

Much easier way to convert object for streaming and read on the other side. Hope this helps. - Vishesh

How to remove element from an array in JavaScript?

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

Is there a TRY CATCH command in Bash

As everybody says, bash doesn't have a proper language-supported try/catch syntax. You can launch bash with the -e argument or use set -e inside the script to abort the entire bash process if any command has a non-zero exit code. (You can also set +e to temporarily allow failing commands.)

So, one technique to simulate a try/catch block is to launch a sub-process to do the work with -e enabled. Then in the main process, check the return code of the sub-process.

Bash supports heredoc strings, so you don't have to write two separate files to handle this. In the below example, the TRY heredoc will run in a separate bash instance, with -e enabled, so the sub-process will crash if any command returns a non-zero exit code. Then, back in the main process, we can check the return code to handle a catch block.

#!/bin/bash

set +e
bash -e <<TRY
  echo hello
  cd /does/not/exist
  echo world
TRY
if [ $? -ne 0 ]; then
  echo caught exception
fi

It's not a proper language-supported try/catch block, but it may scratch a similar itch for you.

Execute combine multiple Linux commands in one line

You can use as the following code;

cd /my_folder && \
rm *.jar && \
svn co path to repo && \
mvn compile package install

It works...

Show hide divs on click in HTML and CSS without jQuery

Of course! jQuery is just a library that utilizes javascript after all.

You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.

elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';

Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.

MySQL timestamp select date range

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

MD5 hashing in Android

If using Apache Commons Codec is an option, then this would be a shorter implementation:

String md5Hex = new String(Hex.encodeHex(DigestUtils.md5(data)));

Or SHA:

String shaHex= new String(Hex.encodeHex(DigestUtils.sha("textToHash")));

Source for above.

Please follow the link and upvote his solution to award the correct person.


Maven repo link: https://mvnrepository.com/artifact/commons-codec/commons-codec

Current Maven dependency (as of 6 July 2016):

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

How to merge 2 List<T> and removing duplicate values from it in C#

    List<int> first_list = new List<int>() {
        1,
        12,
        12,
        5
    };

    List<int> second_list = new List<int>() {
        12,
        5,
        7,
        9,
        1
    };

    var result = first_list.Union(second_list);

String replacement in batch file

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I'm a little late to this party, but I think I have something useful to add.

Kekoa's answer is great but, as RonLugge mentions, it can make the button no longer respect sizeToFit or, more importantly, can cause the button to clip its content when it is intrinsically sized. Yikes!

First, though,

A brief explanation of how I believe imageEdgeInsets and titleEdgeInsets work:

The docs for imageEdgeInsets have the following to say, in part:

Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge.

I believe that this documentation was written imagining that the button has no title, just an image. It makes a lot more sense thought of this way, and behaves how UIEdgeInsets usually do. Basically, the frame of the image (or the title, with titleEdgeInsets) is moved inwards for positive insets and outwards for negative insets.

OK, so what?

I'm getting there! Here's what you have by default, setting an image and a title (the button border is green just to show where it is):

Starting image; no space between title and image.

When you want spacing between an image and a title, without causing either to be crushed, you need to set four different insets, two on each of the image and title. That's because you don't want to change the sizes of those elements' frames, but just their positions. When you start thinking this way, the needed change to Kekoa's excellent category becomes clear:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
}

@end

But wait, you say, when I do that, I get this:

Spacing is good, but the image and title are outside the view's frame.

Oh yeah! I forgot, the docs warned me about this. They say, in part:

This property is used only for positioning the image during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits:.

But there is a property that can help, and that's contentEdgeInsets. The docs for that say, in part:

The button uses this property to determine intrinsicContentSize and sizeThatFits:.

That sounds good. So let's tweak the category once more:

@implementation UIButton(ImageTitleCentering)

- (void)centerButtonAndImageWithSpacing:(CGFloat)spacing {
    CGFloat insetAmount = spacing / 2.0;
    self.imageEdgeInsets = UIEdgeInsetsMake(0, -insetAmount, 0, insetAmount);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, -insetAmount);
    self.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
}

@end

And what do you get?

Spacing and frame are now correct.

Looks like a winner to me.


Working in Swift and don't want to do any thinking at all? Here's the final version of the extension in Swift:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Releasing memory in Python

Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList(). This can be called indirectly by doing a full gc.collect.

Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.

import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

Output:

Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%

Edit:

I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.

The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free.

In 3.x range doesn't create a list, so the test above won't create 10 million int objects. Even if it did, the int type in 3.x is basically a 2.x long, which doesn't implement a freelist.

Chrome says my extension's manifest file is missing or unreadable

Some permissions issue for default sample.

I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.

Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip

which can be found at
https://developer.chrome.com/extensions/samples

this worked great, hope it helps

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

Missing visible-** and hidden-** in Bootstrap v4

i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs                { display:table !important; }
tr.visible-xs                   { display:table-row !important; }
th.visible-xs, td.visible-xs    { display:table-cell !important; }

.visible-xs                 { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}

@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }

.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}

@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }

.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}

@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }

.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}

@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }

.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}

@media (max-width:575px)                        { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px)  { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px)  { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px)                       { .hidden-xl{display:none !important;} }
</pre>

Remove blank lines with grep

egrep -v "^\s\s+"

egrep already do regex, and the \s is white space.

The + duplicates current pattern.

The ^ is for the start

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You are facing a double-encoding issue.

¦ and &#8226; are absolutely equivalent to each other. Both refer to the Unicode character 'BULLET' (U+2022) and can exist side-by-side in HTML source code.

However, if that source-code is HTML-encoded again at some point, it will contain ¦ and &amp;#8226;. The former is rendered unchanged, the latter will come out as "&#8226;" on the screen.

This is correct behavior under these circumstances. You need to find the point where the superfluous second HTML-encoding occurs and get rid of it.

IN-clause in HQL or Java Persistence Query Language

Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.

String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

How to convert LINQ query result to List?

You need to use the select new LINQ keyword to explicitly convert your tbcourseentity into the custom type course. Example of select new:

var q = from o in db.Orders
        where o.Products.ProductName.StartsWith("Asset") && 
              o.PaymentApproved == true
        select new { name   = o.Contacts.FirstName + " " +
                              o.Contacts.LastName, 
                     product = o.Products.ProductName, 
                     version = o.Products.Version + 
                              (o.Products.SubVersion * 0.1)
                   };

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

Receiver not registered exception error?

For anybody who will come upon this problem and they tried all that was suggested and nothing still works, this is how I sorted my problem, instead of doing LocalBroadcastManager.getInstance(this).registerReceiver(...) I first created a local variable of type LocalBroadcastManager,

private LocalBroadcastManager lbman;

And used this variable to carry out the registering and unregistering on the broadcastreceiver, that is

lbman.registerReceiver(bReceiver);

and

lbman.unregisterReceiver(bReceiver);

What is the best IDE to develop Android apps in?

Eclipse and Netbeans are both horrible slow, and I'ts a miracle that even the serious developers has been sticking with it for years, not even try to stick with a better product.

Java as platform is a shame when it comes to non-handheld platforms (win,mac,linux) and if anyone are going to develop on the platform I say do what else but do not use Java at all. For mobility it's probably has a kind of good luck here, as the systems are more down-scaled.

As far I know, there aren't any existing IDE for Java which aren't iself written in a Java environment. This is horrible because Java is messing up the desktop environment.

I'm willing to spend hours on google to find an Java IDE/Editor which are capable for android projects but will use a native environment for itself.

Download file through an ajax call php

I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

$('iframe_dl').src="/app?download=1&filename=" + the_filename

Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

Works like a charm.

How to change angular port from 4200 to any other

  • For Permanent:

    Goto nodel_modules/angular-cli/commands/server.js Search for var defaultPort = process.env.PORT || 4200; and change 4200 to anything else you want.

  • To Run Now:

    ng serve --port 4500 (You an change 4500 to any number you want to use as your port)

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

git config --global core.autocrlf false works well for global settings.

But if you are using Visual Studio, might also need to modify .gitattributes for some type of projects (e.g c# class library application):

  • remove line * text=auto

Where does Console.WriteLine go in ASP.NET?

Unless you are in a strict console application, I wouldn't use it, because you can't really see it. I would use Trace.WriteLine() for debugging-type information that can be turned on and off in production.

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

How to group subarrays by a column value?

There is no native one, just use a loop.

$result = array();
foreach ($data as $element) {
    $result[$element['id']][] = $element;
}

CSS class for pointer cursor

You can assign "button" to role attribute of any html tag/element to make pointer over it. i.e

<html-element role="button" />

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

Set folder browser dialog start location

Set the SelectedPath property before you call ShowDialog ...

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

Will start them at C:\Temp

file_get_contents() how to fix error "Failed to open stream", "No such file"

The actual problem of this error has nothing to do with file_get_content, the problem is the requested url if the url is not throwing content of the page and redirecting the request to some where else file_get_content says "Failed to open stream", just before file_get_contents check whether the url is working and not redirecting, here is the code:

function checkRedirect404($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            //echo "Redirects: $target<br>";

            return true;
        }   
    }   

    return false;

}

How can I strip all punctuation from a string in JavaScript using regex?

str = str.replace(/[^\w\s]|_/g, "")
         .replace(/\s+/g, " ");

Removes everything except alphanumeric characters and whitespace, then collapses multiple adjacent characters to single spaces.

Detailed explanation:

  1. \w is any digit, letter, or underscore.
  2. \s is any whitespace.
  3. [^\w\s] is anything that's not a digit, letter, whitespace, or underscore.
  4. [^\w\s]|_ is the same as #3 except with the underscores added back in.

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Another way without using Modal

Database: stocks Columns:id,name,company_name,exchange_name,status enter image description here

  $name ='aa'
  $stocks = DB::table('stocks')
            ->select('name', 'company_name', 'exchange_name')
            ->where(function($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                ->orWhere('company_name', 'like', '%' . $name . '%');
            })
            ->Where('status', '=', 1)
            ->limit(20)
            ->get();

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

Merge (with squash) all changes from another branch as a single commit

Another option is git merge --squash <feature branch> then finally do a git commit.

From Git merge

--squash

--no-squash

Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

What is the difference between private and protected members of C++ classes?

private = accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)

protected = accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

public = accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)

How can apply multiple background color to one div

You could apply both background-color and border to make it look like 2 colors.

div.A { width: 50px; background-color: #9c9e9f; border-right: 50px solid #f6f6f6; }

The border should have the same size as the width.

Nginx: Job for nginx.service failed because the control process exited

This worked for me:

First, go to

cd /etc/nginx

and make the changes in nginx.conf and make the default port to listen from 80 to any of your choice 85 or something.

Then use this command to bind that port type for nginx to use it:

semanage port -a -t PORT_TYPE -p tcp 85

where PORT_TYPE is one of the following: http_cache_port_t, http_port_t, jboss_management_port_t, jboss_messaging_port_t, ntop_port_t, puppet_port_t.

Then run:

sudo systemctl start nginx; #sudo systemctl status nginx

[you should see active status]; #sudo systemctl enable nginx

How do I capitalize first letter of first name and last name in C#?

I like this way:

using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());

Lifted from this MSDN article.

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

Resize image in the wiki of GitHub using Markdown

I have used methods described above. Now I am using the method which is a way similiar but more simple to me.

  1. First create add README.md file to your project.
  2. Then upload screenshoots or whatever description images needed to your project main directory.
  3. After uploading image Assets use html to refer these assets directly without using link like below

Like this:

<img src="icon.jpg" width="324" height="324">

<p align="center">
  <img src="screen1.png" width="256" height="455">
  <img src="screen2.png" width="256" height="455">
  <img src="screen3.png" width="256" height="455">
</p>

On above example I have used paragraph to align images side by side. If you are going to use single image just use the code as below

<img src="icon.jpg" width="324" height="324">

Have a nice day!

What's the key difference between HTML 4 and HTML 5?

You might be interested in this list of HTML5 elements and attributes.

Also, please note that it's "HTML 4", not "HTML4". Indeed, for HTML 5, both variants are used, but there is an important difference in meaning. HTML 5 refers to the name of the W3C specification, whereas "HTML5" is the document type of those HTML files with a text/html MIME type that follow this spec. The same goes for XHTML 5 vs. XHTML5.

How to check if a file is empty in Bash?

To check if file is empty or has only white spaces, you can use grep:

if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
  echo "Empty file" 
  ...
fi

How do I share variables between different .c files?

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

npm install doesn't create node_modules directory

I ran into this trying to integrate React Native into an existing swift project using cocoapods. The FB docs (at time of writing) did not specify that npm install react-native wouldn't work without first having a package.json file. Per the RN docs set your entry point: (index.js) as index.ios.js

How do I set the eclipse.ini -vm option?

Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.

What's the HTML to have a horizontal space between two objects?

I think what you mean is putting 2 paragraphs (for example) in 2 columns instead of one below the other? In that case, I think float is your solution.

<div style="float: left"> <!-- would cause this to hang on the left -->
<div style="float: right"> <!-- would cause this to hang on the right-->

Here's an example: http://jsfiddle.net/XPfLA/1

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

How do I find out what keystore my JVM is using?

In addition to all answers above:

If updating the cacerts file in JRE directory doesn't help, try to update it in JDK.

C:\Program Files\Java\jdk1.8.0_192\jre\lib\security

Delete rows with blank values in one particular column

An easy approach would be making all the blank cells NA and only keeping complete cases. You might also look for na.omit examples. It is a widely discussed topic.

df[df==""]<-NA
df<-df[complete.cases(df),]

How to create a date object from string in javascript

Very simple:

var dt=new Date("2011/11/30");

Date should be in ISO format yyyy/MM/dd.

latex large division sign in a math formula

A possible soluttion that requires tweaking, but is very flexible is to use one of \big, \Big, \bigg,\Bigg in front of your division sign - these will make it progressively larger. For your formula, I think

  $\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$

looks nicer than \middle\ which is automatically sized and IMHO is a bit too large.

Reading PDF content with itextsharp dll in VB.NET or C#

Public Sub PDFTxtToPdf(ByVal sTxtfile As String, ByVal sPDFSourcefile As String)
        Dim sr As StreamReader = New StreamReader(sTxtfile)
    Dim doc As New Document()
    PdfWriter.GetInstance(doc, New FileStream(sPDFSourcefile, FileMode.Create))
    doc.Open()
    doc.Add(New Paragraph(sr.ReadToEnd()))
    doc.Close()
End Sub

What is the --save option for npm install?

npm v6.x update ?

now you can be using one of npm i or npm i -S or npm i -P to install and save module as a dependency.

npm i is the alias of npm install

  1. npm i is equal to npm install, means default save module as a dependency;
  2. npm i -S is equal to npm install --save (npm v5-)
  3. npm i -P is equal to npm install --save-prod (npm v5+)

check your npm version

$ npm -v
6.14.4

get npm help

?  ~ npm -h

Usage: npm <command>

where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, fund, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm <command> -h  quick help on <command>
npm -l            display full usage info
npm help <term>   search for help on <term>
npm help npm      involved overview

Specify configs in the ini-formatted file:
    /Users/xgqfrms-mbp/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

[email protected] /Users/xgqfrms-mbp/.nvm/versions/node/v12.18.0/lib/node_modules/npm

get npm install help

npm -h i / npm help install

$ npm -h i  

npm install (with no args, in package dir)
npm install [<@scope>/]<pkg>
npm install [<@scope>/]<pkg>@<tag>
npm install [<@scope>/]<pkg>@<version>
npm install [<@scope>/]<pkg>@<version range>
npm install <alias>@npm:<name>
npm install <folder>
npm install <tarball file>
npm install <tarball url>
npm install <git:// url>
npm install <github username>/<github project>

aliases: i, isntall, add
common options: [--save-prod|--save-dev|--save-optional] [--save-exact] [--no-save]
?  ~ 

refs

https://docs.npmjs.com/cli/install

enter image description here

Sending HTTP Post request with SOAP action using org.apache.http

It was giving 415 Http response Code as error,

So I added

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

Everything alright now, Http: 200

Random "Element is no longer attached to the DOM" StaleElementReferenceException

FirefoxDriver _driver = new FirefoxDriver();

// create webdriverwait
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));

// create flag/checker
bool result = false;

// wait for the element.
IWebElement elem = wait.Until(x => x.FindElement(By.Id("Element_ID")));

do
{
    try
    {
        // let the driver look for the element again.
        elem = _driver.FindElement(By.Id("Element_ID"));

        // do your actions.
        elem.SendKeys("text");

        // it will throw an exception if the element is not in the dom or not
        // found but if it didn't, our result will be changed to true.
        result = !result;
    }
    catch (Exception) { }
} while (result != true); // this will continue to look for the element until
                          // it ends throwing exception.

How do I redirect to the previous action in ASP.NET MVC?

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

Notice: Undefined offset: 0 in

If you are using dompdf/dompdf and error occure in vendor/dompdf/dompdf/src/Cellmap.php then It looks like we're using the wrong frame id in the update_row_group method. Initial testing seems to confirm this. Though that may be because this is strictly a paged table issue and not too many of the documents in my test bed have paged tables.

Can you try changing line 800 to:

$r_rows = $this->_frames[$g_key]["rows"];
($g_key instead of $r_key)

https://github.com/dompdf/dompdf/issues/1295

How to add image to canvas

In my case, I was mistaken the function parameters, which are:

context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);

If you expect them to be

context.drawImage(image, width, height);

you will place the image just outside the canvas with the same effects as described in the question.

Test if characters are in a string

Similar problem here: Given a string and a list of keywords, detect which, if any, of the keywords are contained in the string.

Recommendations from this thread suggest stringr's str_detect and grepl. Here are the benchmarks from the microbenchmark package:

Using

map_keywords = c("once", "twice", "few")
t = "yes but only a few times"

mapper1 <- function (x) {
  r = str_detect(x, map_keywords)
}

mapper2 <- function (x) {
  r = sapply(map_keywords, function (k) grepl(k, x, fixed = T))
}

and then

microbenchmark(mapper1(t), mapper2(t), times = 5000)

we find

Unit: microseconds
       expr    min     lq     mean  median      uq      max neval
 mapper1(t) 26.401 27.988 31.32951 28.8430 29.5225 2091.476  5000
 mapper2(t) 19.289 20.767 24.94484 23.7725 24.6220 1011.837  5000

As you can see, over 5,000 iterations of the keyword search using str_detect and grepl over a practical string and vector of keywords, grepl performs quite a bit better than str_detect.

The outcome is the boolean vector r which identifies which, if any, of the keywords are contained in the string.

Therefore, I recommend using grepl to determine if any keywords are in a string.

How to listen to the window scroll event in a VueJS component?

I think the best approach is just add ".passive"

v-on:scroll.passive='handleScroll'

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Finding first blank row, then writing to it

Update

Inspired by Daniel's code above and the fact that this is WAY! more interesting to me now then the actual work I have to do, i created a hopefully full-proof function to find the first blank row in a sheet. Improvements welcome! Otherwise, this is going to my library :) Hopefully others benefit as well.

    Function firstBlankRow(ws As Worksheet) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it

    Dim rngSearch As Range, cel As Range

    With ws

        Set rngSearch = .UsedRange.Columns(1).Find("") '-> does blank exist in the first column of usedRange

        If Not rngSearch Is Nothing Then

            Set rngSearch = .UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks)

            For Each cel In rngSearch

                If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then

                    firstBlankRow = cel.Row
                    Exit For

                End If

            Next

        Else '-> no blanks in first column of used range

            If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then '-> is the last row of the sheet blank?

                '-> yeap!, then no blank rows!
                MsgBox "Whoa! All rows in sheet are used. No blank rows exist!"


            Else

                '-> okay, blank row exists
                firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).Row + 1

            End If

        End If

    End With

End Function

Original Answer

To find the first blank in a sheet, replace this part of your code:

Cells(1, 1).Select
For Each Cell In ws.UsedRange.Cells
    If Cell.Value = "" Then Cell = Num
    MsgBox "Checking cell " & Cell & " for value."
Next

With this code:

With ws

    Dim rngBlanks As Range, cel As Range

    Set rngBlanks = Intersect(.UsedRange, .Columns(1)).Find("")

    If Not rngBlanks Is Nothing Then '-> make sure blank cell exists in first column of usedrange
        '-> find all blank rows in column A within the used range
        Set rngBlanks = Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeBlanks)

        For Each cel In rngBlanks '-> loop through blanks in column A

            '-> do a countA on the entire row, if it's 0, there is nothing in the row
            If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then
                num = cel.Row
                Exit For
            End If

        Next
    Else

        num = usedRange.SpecialCells(xlCellTypeLastCell).Offset(1).Row                 

    End If


End With

How to implement drop down list in flutter?

For the solution, scroll to the end of the answer.

First of all, let's investigate what the error says (I have cited the error that's thrown with Flutter 1.2, but the idea is the same):

Failed assertion: line 560 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.

There are four or conditions. At least one of them must be fulfilled:

  • Items (a list of DropdownMenuItem widgets) were provided. This eliminates items == null.
  • Non-empty list was provided. This eliminates items.isEmpty.
  • A value (_selectedLocation) was also given. This eliminates value == null. Note that this is DropdownButton's value, not DropdownMenuItem's value.

Hence only the last check is left. It boils down to something like:

Iterate through DropdownMenuItem's. Find all that have a value that's equal to _selectedLocation. Then, check how many items matching it were found. There must be exactly one widget that has this value. Otherwise, throw an error.

The way code is presented, there is not a DropdownMenuItem widget that has a value of _selectedLocation. Instead, all the widgets have their value set to null. Since null != _selectedLocation, last condition fails. Verify this by setting _selectedLocation to null - the app should run.

To fix the issue, we first need to set a value on each DropdownMenuItem (so that something could be passed to onChanged callback):

return DropdownMenuItem(
    child: new Text(location),
    value: location,
);

The app will still fail. This is because your list still does not contain _selectedLocation's value. You can make the app work in two ways:

  • Option 1. Add another widget that has the value (to satisfy items.where((DropdownMenuItem<T> item) => item.value == value).length == 1). Might be useful if you want to let the user re-select Please choose a location option.
  • Option 2. Pass something to hint: paremter and set selectedLocation to null (to satisfy value == null condition). Useful if you don't want Please choose a location to remain an option.

See the code below that shows how to do it:

import 'package:flutter/material.dart';

void main() {
  runApp(Example());
}

class Example extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
//  List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D']; // Option 1
//  String _selectedLocation = 'Please choose a location'; // Option 1
  List<String> _locations = ['A', 'B', 'C', 'D']; // Option 2
  String _selectedLocation; // Option 2

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: DropdownButton(
            hint: Text('Please choose a location'), // Not necessary for Option 1
            value: _selectedLocation,
            onChanged: (newValue) {
              setState(() {
                _selectedLocation = newValue;
              });
            },
            items: _locations.map((location) {
              return DropdownMenuItem(
                child: new Text(location),
                value: location,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

"Debug certificate expired" error in Eclipse Android plugins

After you install the Android SDK in Eclipse, it generates a debug signing certificate for you in a keystore called debug.keystore. The Eclipse plug-in uses this certificate to sign each application build that is generated.

Now, the problem with this debug certificate is that it is only valid for a year, or 365 days. If your Eclipse IDE uses an expired debug certificate, you will not be able to create and/or deploy an Android app.

To fix this problem all you need to do is delete the debug.keystore file.

  1. Go to Preferences
  2. Android
  3. Build
  4. Default debug keystore

There you should see the folder where the file is located. Simply delete that file and you are good to go.

For more info. you can visit

http://developer.android.com/tools/publishing/app-signing.html

HTML Canvas Full Screen

Because it was not posted yet and is a simple css fix:

#canvas {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
}

Works great if you want to apply a fullscreen canvas background (for example with Granim.js).

How to fix "Referenced assembly does not have a strong name" error?

I was searching for solution to the very same problem and un-ticking "Sign the assembly" option works for me:

enter image description here

(as you may notice screenshot comes from VS2010 but hopefully it will help someone)

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

How to use WebRequest to POST some data and read response?

From MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

Take into account that the information must be sent in the format key1=value1&key2=value2

How To Include CSS and jQuery in my WordPress plugin?

Just to append to @pixeline's answer (tried to add a simple comment but the site said I needed 50 reputation).

If you are writing your plugin for the admin section then you should use:

add_action('admin_enqueue_scripts', "add_my_css_and_my_js_files");

The admin_enqueueu_scripts is the correct hook for the admin section, use wp_enqueue_scripts for the front end.

AssertNull should be used or AssertNotNull

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Why both no-cache and no-store should be used in HTTP response?

Under certain circumstances, IE6 will still cache files even when Cache-Control: no-cache is in the response headers.

The W3C states of no-cache:

If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server.

In my application, if you visited a page with the no-cache header, then logged out and then hit back in your browser, IE6 would still grab the page from the cache (without a new/validating request to the server). Adding in the no-store header stopped it doing so. But if you take the W3C at their word, there's actually no way to control this behavior:

History buffers MAY store such responses as part of their normal operation.

General differences between browser history and the normal HTTP caching are described in a specific sub-section of the spec.

Display text on MouseOver for image in html

You can use title attribute.

<img src="smiley.gif"  title="Smiley face"/>

You can change the source of image as you want.

And as @Gray commented:

You can also use the title on other things like <a ... anchors, <p>, <div>, <input>, etc. See: this

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is:

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

And StreamReader is:

public override void Close()
{
    this.Dispose(true);
}

The Dispose(bool disposing) override in StreamReader is:

protected override void Dispose(bool disposing)
{
    try
    {
        if ((this.Closable && disposing) && (this.stream != null))
        {
            this.stream.Close();
        }
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            this.stream = null;
            /* deleted for brevity */
            base.Dispose(disposing);
        }
    }
}

The StreamWriter method is similar.

So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }.

My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors".

But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?

So I think it is best to do this:

using (var stream = ...)
{
    /* code */

    stream.Close();
}

It doesn't affect the behaviour of the code, but it does aid readability.

How to reverse an animation on mouse out after hover

we can use requestAnimationFrame to reset animation and reverse it when browser paints in next frame.

Also use onmouseenter and onmouseout event handlers to reverse animation direction

As per

Any rAFs queued in your event handlers will be executed in the ?same frame?. Any rAFs queued in a rAF will be executed in the next frame?.

_x000D_
_x000D_
function fn(el, isEnter) {_x000D_
  el.className = "";_x000D_
   requestAnimationFrame(() => {_x000D_
    requestAnimationFrame(() => {_x000D_
        el.className = isEnter? "in": "out";_x000D_
    });_x000D_
  });  _x000D_
}
_x000D_
.in{_x000D_
  animation: k 1s forwards;_x000D_
}_x000D_
_x000D_
.out{_x000D_
  animation: k 1s forwards;_x000D_
  animation-direction: reverse;_x000D_
}_x000D_
_x000D_
@keyframes k_x000D_
{_x000D_
from {transform: rotate(0deg);}_x000D_
to   {transform: rotate(360deg);}_x000D_
}
_x000D_
<div style="width:100px; height:100px; background-color:red" _x000D_
  onmouseenter="fn(this, true)"_x000D_
   onmouseleave="fn(this, false)"  _x000D_
     ></div>
_x000D_
_x000D_
_x000D_

Nullable types: better way to check for null or zero in c#

I agree with using the ?? operator.

If you're dealing with strings use if(String.IsNullOrEmpty(myStr))

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Iif equivalent in C#

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)

Blah.a=Blah.a<5?1:8;

(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
or
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

Is there a typical state machine implementation pattern?

I prefer to use a table driven approach for most state machines:

typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;
typedef struct instance_data instance_data_t;
typedef state_t state_func_t( instance_data_t *data );

state_t do_state_initial( instance_data_t *data );
state_t do_state_foo( instance_data_t *data );
state_t do_state_bar( instance_data_t *data );

state_func_t* const state_table[ NUM_STATES ] = {
    do_state_initial, do_state_foo, do_state_bar
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
    return state_table[ cur_state ]( data );
};

int main( void ) {
    state_t cur_state = STATE_INITIAL;
    instance_data_t data;

    while ( 1 ) {
        cur_state = run_state( cur_state, &data );

        // do other program logic, run other state machines, etc
    }
}

This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well:

typedef void transition_func_t( instance_data_t *data );

void do_initial_to_foo( instance_data_t *data );
void do_foo_to_bar( instance_data_t *data );
void do_bar_to_initial( instance_data_t *data );
void do_bar_to_foo( instance_data_t *data );
void do_bar_to_bar( instance_data_t *data );

transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = {
    { NULL,              do_initial_to_foo, NULL },
    { NULL,              NULL,              do_foo_to_bar },
    { do_bar_to_initial, do_bar_to_foo,     do_bar_to_bar }
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
    state_t new_state = state_table[ cur_state ]( data );
    transition_func_t *transition =
               transition_table[ cur_state ][ new_state ];

    if ( transition ) {
        transition( data );
    }

    return new_state;
};

The table driven approach is easier to maintain and extend and simpler to map to state diagrams.

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

No connection could be made because the target machine actively refused it (PHP / WAMP)

You might need:

  • In wamp\bin\mysql\mysqlX.X.XX\my.ini find these lines:

    [client] ... port = 3308 ... [wampmysqld64] ... port = 3308

As you see, the port number is 3308. You should :

  • use that port in applications, like WordPress: define('DB_HOST', 'localhost:3308')

or

  • change it globally in wamp\bin\apache\apache2.X.XXX\bin\php.ini change mysqli.default_port = ... to 3308

ASP.NET strange compilation error

The answers provided are not the solution. The .NET 6# stuff is pretty different from what we used to. A lot has changed, from having to deal with portable libraries to Visual Studio 2015 installing an old compiler (it cost me four hours cracking my head).

The long story short: Stack Overflow question How do I use C# 6 with a Web Site project type?

You need to install the C# .NET compiler (now runs as a service bla bla bla). and you need to run updates on NuGet to get the latest everything (before trying anything else).

The compiler must be installed on the project your solution runs from (so your website or your main project your application starts from (if you have multiple projects)).

Once you install that then sort out your web.config referencing any portable libraries, and delete both the bin and obj folder (to avoid works on my computer nightmare), It should just run. But be patient; what happens on your machine may vary as much as the answers above. Most of the answers above hide other problems. It may work for a while, then boom: compiler error. I had a few pages working, then some pages started failing because of some packages that have started using portable libraries.

Query EC2 tags from within instance

Download and run a standalone executable to do that.

Sometimes one cannot install awscli that depends on python. docker might be out of the picture too.

Here is my implementation in golang: https://github.com/hmalphettes/go-ec2-describe-tags

How to get only the date value from a Windows Forms DateTimePicker control?

@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

public MyClass()
{
    // Create a new DateTimePicker
    DateTimePicker dateTimePicker1 = new DateTimePicker();
    Controls.Add(dateTimePicker1);
    MessageBox.Show(dateTimePicker1.Value.ToString());

    dateTimePicker1.Value = DateTime.Now.AddDays(1);
    MessageBox.Show(dateTimePicker1.Value.ToString());
 } 

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Some useful extensions:

extension String {
    func substring(from: Int, to: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        let end = index(start, offsetBy: to - from)
        return String(self[start ..< end])
    }

    func substring(range: NSRange) -> String {
        return substring(from: range.lowerBound, to: range.upperBound)
    }
}

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

MSDN Documentation Here

To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code

   SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')

If that doesn't work check to make sure you have entered a valid GUID

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

How do I loop through or enumerate a JavaScript object?

Preface:

  • Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).
  • Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.
  • Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.

Here in 2018, your options for looping through an object's properties are (some examples follow the list):

  1. for-in [MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
  2. Object.keys [MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
  3. Object.values [MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
  4. Object.entries [MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties (each entry in the array is a [name, value] array).
  5. Object.getOwnPropertyNames [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
  6. Object.getOwnPropertySymbols [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
  7. Reflect.ownKeys [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.
  8. If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and Object.getPrototypeOf [MDN, spec] and use Object.getOwnPropertyNames, Object.getOwnPropertySymbols, or Reflect.ownKeys on each object in the prototype chain (example at the bottom of this answer).

With all of them except for-in, you'd use some kind of looping construct on the array (for, for-of, forEach, etc.).

Examples:

for-in:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name in o) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.keys (with a for-of loop, but you can use any looping construct):

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.keys(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.values:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const value of Object.values(o)) {_x000D_
    console.log(`${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.entries:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const [name, value] of Object.entries(o)) {_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.getOwnPropertyNames:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.getOwnPropertyNames(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${name} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Object.getOwnPropertySymbols:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Object.getOwnPropertySymbols(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${String(name)} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

Reflect.ownKeys:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (const name of Reflect.ownKeys(o)) {_x000D_
    const value = o[name];_x000D_
    console.log(`${String(name)} = ${value}`);_x000D_
}
_x000D_
_x000D_
_x000D_

All properties, including inherited non-enumerable ones:

_x000D_
_x000D_
// A prototype object to inherit from, with a string-named property_x000D_
const p = {answer: 42};_x000D_
// The object we'll look at, which inherits from `p`_x000D_
const o = Object.create(p);_x000D_
// A string-named property_x000D_
o.question = "Life, the Universe, and Everything";_x000D_
// A symbol-named property_x000D_
o[Symbol("author")] = "Douglas Adams";_x000D_
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {_x000D_
    for (const name of Reflect.ownKeys(current)) {_x000D_
        const value = o[name];_x000D_
        console.log(`[${depth}] ${String(name)} = ${String(value)}`);_x000D_
    }_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

Android - Center TextView Horizontally in LinearLayout

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

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

Sharing link on WhatsApp from mobile website (not application) for Android

Just saw it on a website and seems to work on latest Android with latest chrome and whatsapp now too! Give the link a new shot!

<a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">Share via Whatsapp</a>

Rechecked it today (17th April 2015):
Works for me on iOS 8 (iPhone 6, latest versions) Android 5 (Nexus 5, latest versions).

It also works on Windows Phone.

Set the value of a variable with the result of a command in a Windows batch file

Set "dateTime="
For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
echo %dateTime%
pause

enter image description here Official Microsoft docs for for command

Python: json.loads returns items prefixing with 'u'

Unicode is an appropriate type here. The JSONDecoder docs describe the conversion table and state that json string objects are decoded into Unicode objects

https://docs.python.org/2/library/json.html#encoders-and-decoders

JSON                    Python
==================================
object                  dict
array                   list
string                  unicode
number (int)            int, long
number (real)           float
true                    True
false                   False
null                    None

"encoding determines the encoding used to interpret any str objects decoded by this instance (UTF-8 by default)."

Open Url in default web browser

Try this:

import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
  Linking.openURL(url);
};

const App = () => {
  return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};

Hope this will solve your problem.

Delete a row from a table by id

From this post, try this javascript:

function removeRow(id) {
  var tr = document.getElementById(id);
  if (tr) {
    if (tr.nodeName == 'TR') {
      var tbl = tr; // Look up the hierarchy for TABLE
      while (tbl != document && tbl.nodeName != 'TABLE') {
        tbl = tbl.parentNode;
      }

      if (tbl && tbl.nodeName == 'TABLE') {
        while (tr.hasChildNodes()) {
          tr.removeChild( tr.lastChild );
        }
      tr.parentNode.removeChild( tr );
      }
    } else {
      alert( 'Specified document element is not a TR. id=' + id );
    }
  } else {
    alert( 'Specified document element is not found. id=' + id );
  }
}

I tried this javascript in a test page and it worked for me in Firefox.

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

Find all special characters in a column in SQL Server 2008

The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.

DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}

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

Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking "Add Path". E.g: 'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'
  3. Click "Synchronize..." to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

What should a JSON service return on failure / error

I would definitely return a 500 error with a JSON object describing the error condition, similar to how an ASP.NET AJAX "ScriptService" error returns. I believe this is fairly standard. It's definitely nice to have that consistency when handling potentially unexpected error conditions.

Aside, why not just use the built in functionality in .NET, if you're writing it in C#? WCF and ASMX services make it easy to serialize data as JSON, without reinventing the wheel.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Advantages of std::for_each over for loop

The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled.

I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this

for(auto it = collection.begin(); it != collection.end() ; ++it)
{
   foo(*it);
}

Or this

for_each(collection.begin(), collection.end(), [](Element& e)
{
   foo(e);
});

when the range-based for loop syntax is available:

for(Element& e : collection)
{
   foo(e);
}

This kind of syntax has been available in Java and C# for some time now, and actually there are way more foreach loops than classical for loops in every recent Java or C# code I saw.

AngularJS : ng-click not working

For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.