Programs & Examples On #Workload

How to download Visual Studio 2017 Community Edition for offline installation?

All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.

[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
    --lang en-US
    --layout ".\Visual Studio Cummunity 2017"
    --add Microsoft.VisualStudio.Workload.NativeDesktop 
    --includeRecommended

I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).

The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.

"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.

HTTP 1.0 vs 1.1

One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).

If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET and POST verbs at least.

Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.

If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.

Vim autocomplete for Python

I found a good choice to be coc.nvim with the python language server.

It takes a bit of effort to set up. I got frustrated with jedi-vim, because it would always freeze vim for a bit when completing. coc.nvim doesn't do it because it's asyncronous, meaning that . It also gives you linting for your code. It supports many other languages and is highly configurable.

The python language server uses jedi so you get the same completion as you would get from jedi.

CSS technique for a horizontal line with words in the middle

For me this solution works perfectly fine...

HTML

<h2 class="strikethough"><span>Testing Text</span></h2>

CSS

.strikethough {
 width:100%; 
 text-align:left; 
 border-bottom: 1px solid #bcbcbc; 
 overflow: inherit;
 margin:0px 0 30px;
 font-size: 16px;
 color:#757575;
 }
.strikethough span {
 background:#fff; 
 padding:0 20px 0px 0px;
 position: relative;
 top: 10px;
}

How to get system time in Java without creating a new Date

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

JavaScript/jQuery to download file via POST with JSON data

With HTML5, you can just create an anchor and click on it. There is no need to add it to the document as a child.

const a = document.createElement('a');
a.download = '';
a.href = urlForPdfFile;
a.click();

All done.

If you want to have a special name for the download, just pass it in the download attribute:

const a = document.createElement('a');
a.download = 'my-special-name.pdf';
a.href = urlForPdfFile;
a.click();

Sending simple message body + file attachment using Linux Mailx

The usual way is to use uuencode for the attachments and echo for the body:

(uuencode output.txt output.txt; echo "Body of text") | mailx -s 'Subject' [email protected]

For Solaris and AIX, you may need to put the echo statement first:

(echo "Body of text"; uuencode output.txt output.txt) | mailx -s 'Subject' [email protected]

What is the advantage of using REST instead of non-REST HTTP?

Simply put: NONE.

Feel free to downvote, but I still think there are no real benefits over non-REST HTTP. All current answers are invalid. Arguments from the currently most voted answer:

  • Simple.
  • You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application, even if you haven't designed it specifically for them (probably, because they weren't around when you created your app).

1. Simple

With REST you need additional communication layer for your server-side and client-side scripts => it's actually more complicated than use of non-REST HTTP.

2. Caching

Caching can be controlled by HTTP headers sent by server. REST does not add any features missing in non-REST.

3. Organization

REST does not help you organize things. It forces you to use API supported by server-side library you are using. You can organize your application the same way (or better) when you are using non-REST approach. E.g. see Model-View-Controller or MVC routing.

4. Easy to use/implement

Not true at all. It all depends on how well you organize and document your application. REST will not magically make your application better.

Remove last character of a StringBuilder?

With Java-8 you can use static method of String class,

String#join(CharSequence delimiter,Iterable<? extends CharSequence> elements).


public class Test {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();
        names.add("James");
        names.add("Harry");
        names.add("Roy");
        System.out.println(String.join(",", names));
    }
}

OUTPUT

James,Harry,Roy

Java generics - why is "extends T" allowed but not "implements T"?

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

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

There might two issues

1) $blogs may be a stdObject

or

2) The properties of the array might be the stdObject

Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this

$blog->id;
$blog->content;
$blog->title;

Connection refused on docker container

You need to publish the exposed ports by using the following options:

-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.

-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.

The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo and check which random ports are being used from your host at the Ports section.

Just run the following command:

docker run -it -p 8080:8080 demo

After that your url will work.

How to go back last page

in angular 4 use preserveQueryParams, ex:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

When clicking the link, you are redirected edit/10?page=1, preserving params

ref: https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

Maximum packet size for a TCP connection

There're no packets in TCP API.

There're packets in underlying protocols often, like when TCP is done over IP, which you have no interest in, because they have nothing to do with the user except for very delicate performance optimizations which you are probably not interested in (according to the question's formulation).

If you ask what is a maximum number of bytes you can send() in one API call, then this is implementation and settings dependent. You would usually call send() for chunks of up to several kilobytes, and be always ready for the system to refuse to accept it totally or partially, in which case you will have to manually manage splitting into smaller chunks to feed your data into the TCP send() API.

What is the difference between C# and .NET?

C# is a programming language, .NET is a blanket term that tends to cover both the .NET Framework (an application framework library) and the Common Language Runtime which is the runtime in which .NET assemblies are run.

Microsoft's implementation of C# is heavily integrated with the .NET Framework so it is understandable that the two concepts would be confused. However it is important to understand that they are two very different things.

Here is a class written in C#:

class Example { }

Here is a class written in C# that explicitly uses a .NET framework assembly, type, and method:

class Example
{
    static void Main()
    {
        // Here we call into the .NET framework to 
        // write to the output console
        System.Console.Write("hello, world");
    }
}

As I mentioned before, it is very difficult to use Microsoft's implementation of C# without using the .NET framework as well. My first Example implementation above even uses the .NET framework (implicitly, yes, but it does use it nonetheless) because Example inherits from System.Object.

Also, the reason I use the phrase Microsoft's implementation of C# is because there are other implementations of C# available.

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

UILabel font size?

very simple, yet effective method to adjust the size of label text progmatically :-

label.font=[UIFont fontWithName:@"Chalkduster" size:36];

:-)

Change the current directory from a Bash script

When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.

Instead, you can start your script like this:

. myscript.sh

The . will evaluate the script in the current environment, so it might be altered

What is the easiest way to install BLAS and LAPACK for scipy?

The SciPy installation page already recommends several ways of installing python with SciPy already included, such as WinPython.

Another way is to use wheels (a built-package format):

pip install SomePackage-1.0-py2.py3-none-any.whl

The wheel packages you can find on: http://www.lfd.uci.edu/~gohlke/pythonlibs/

For SciPy you need:

How do I create delegates in Objective-C?

Ok, this is not really an answer to the question, but if you are looking up how to make your own delegate maybe something far simpler could be a better answer for you.

I hardly implement my delegates because I rarely need. I can have ONLY ONE delegate for a delegate object. So if you want your delegate for one way communication/passing data than you are much better of with notifications.

NSNotification can pass objects to more than one recipients and it is very easy to use. It works like this:

MyClass.m file should look like this

#import "MyClass.h"
@implementation MyClass 

- (void) myMethodToDoStuff {
//this will post a notification with myClassData (NSArray in this case)  in its userInfo dict and self as an object
[[NSNotificationCenter defaultCenter] postNotificationName:@"myClassUpdatedData"
                                                    object:self
                                                  userInfo:[NSDictionary dictionaryWithObject:selectedLocation[@"myClassData"] forKey:@"myClassData"]];
}
@end

To use your notification in another classes: Add class as an observer:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherClassUpdatedItsData:) name:@"myClassUpdatedData" object:nil];

Implement the selector:

- (void) otherClassUpdatedItsData:(NSNotification *)note {
    NSLog(@"*** Other class updated its data ***");
    MyClass *otherClass = [note object];  //the object itself, you can call back any selector if you want
    NSArray *otherClassData = [note userInfo][@"myClassData"]; //get myClass data object and do whatever you want with it
}

Don't forget to remove your class as an observer if

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

How to get function parameter names/values dynamically?

I don't know how to get a list of the parameters but you can do this to get how many it expects.

alert(doSomething.length);

Android - set TextView TextStyle programmatically?

This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it's relevant in this thread as well (since i ended up here when I was searching for an answer).

There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will:

  1. Define an attribute
  2. Create a style that you want to use
  3. Apply a style for that attribute on our theme
  4. Create new instances of our view with that attribute

In 'res/values/attrs.xml', define a new attribute:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

In res/values/styles.xml' I'm going to create the style I want to use on my custom TextView

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

In 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
       super(context, null, R.attr.customTextView);
    }
}

It's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

Unable to cast object of type 'System.DBNull' to type 'System.String`

A shorter form can be used:

return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()

EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:

return (accountNumber == null) ? string.Empty : accountNumber.ToString() 

Run a script in Dockerfile

Try to create script with ADD command and specification of working directory Like this("script" is the name of script and /root/script.sh is where you want it in the container, it can be different path:

ADD script.sh /root/script.sh

In this case ADD has to come before CMD, if you have one BTW it's cool way to import scripts to any location in container from host machine

In CMD place [./script]

It should automatically execute your script

You can also specify WORKDIR as /root, then you'l be automatically placed in root, upon starting a container

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I had the same its because of version incompatibility check for version or remove version if using spring boot

How to Merge Two Eloquent Collections?

All do not work for me on eloquent collections, laravel eloquent collections use the key from the items I think which causes merging issues, you need to get the first collection back as an array, put that into a fresh collection and then push the others into the new collection;

public function getFixturesAttribute()
{
    $fixtures = collect( $this->homeFixtures->all() );
    $this->awayFixtures->each( function( $fixture ) use ( $fixtures ) {
        $fixtures->push( $fixture );
    });
    return $fixtures;
}

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

Checking the equality of two slices

In case that you are interested in writing a test, then github.com/stretchr/testify/assert is your friend.

Import the library at the very beginning of the file:

import (
    "github.com/stretchr/testify/assert"
)

Then inside the test you do:


func TestEquality_SomeSlice (t * testing.T) {
    a := []int{1, 2}
    b := []int{2, 1}
    assert.Equal(t, a, b)
}

The error prompted will be:

                Diff:
                --- Expected
                +++ Actual
                @@ -1,4 +1,4 @@
                 ([]int) (len=2) {
                + (int) 1,
                  (int) 2,
                - (int) 2,
                  (int) 1,
Test:           TestEquality_SomeSlice

How do I vertically center text with CSS?

Try this solution:

_x000D_
_x000D_
.EXTENDER {_x000D_
    position: absolute;_x000D_
    top: 0px;_x000D_
    left: 0px;_x000D_
    bottom: 0px;_x000D_
    right: 0px;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow-y: hidden;_x000D_
    overflow-x: hidden;_x000D_
}_x000D_
_x000D_
.PADDER-CENTER {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: -webkit-box;_x000D_
    display: -moz-box;_x000D_
    display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -webkit-box-pack: center;_x000D_
    -moz-box-pack: center;_x000D_
    -ms-flex-pack: center;_x000D_
    -webkit-justify-content: center;_x000D_
    justify-content: center;_x000D_
    -webkit-box-align: center;_x000D_
    -moz-box-align: center;_x000D_
    -ms-flex-align: center;_x000D_
    -webkit-align-items: center;_x000D_
    align-items: center;_x000D_
}
_x000D_
<div class="EXTENDER">_x000D_
  <div class="PADDER-CENTER">_x000D_
    <div contentEditable="true">Edit this text...</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Built using CSS+.

When do I need to do "git pull", before or after "git add, git commit"?

I think git pull --rebase is the cleanest way to set your locally recent commits on top of the remote commits which you don't have at a certain point.

So this way you don't have to pull every time you want to start making changes.

Instantly detect client disconnection from server socket

This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.

//open or receive a server socket - TODO your code here
socket = new Socket(....);

//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
    DateTime nextCheckTime = DateTime.Now.AddSeconds(5);

    while (!exitSystem) {
        if (nextCheckTime < DateTime.Now) {
            try {
                if (socket!=null) {
                    if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
                        //socket not connected, close it if it's still running
                        socket.Close();
                        socket = null;    
                    } else {
                        //socket still connected
                    }    
               }
           } catch {
               socket.Close();
            } finally {
                nextCheckTime = DateTime.Now.AddSeconds(5);
            }
        }
        Thread.Sleep(1000);
    }
}

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

How to insert DECIMAL into MySQL database

MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.

The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.

Thus, (4,2) can be anything from -99.99 to 99.99.

As for why you're getting 99.99 instead of the desired 3.80, the value you're inserting must be interpreted as larger than 99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.

Edit

Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.

Getting Python error "from: can't read /var/mail/Bio"

I got same error because I was trying to run on

XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass

from: can't read /var/mail/classDemo

To solve this, type command python and when you get these >>> then run any python commands

>>>from classDemo import MyClass
>>>f = MyClass()

How to create EditText accepts Alphabets only in android?

EditText state = (EditText) findViewById(R.id.txtState);


                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(state.getText().toString());
                boolean bs = ms.matches();
                if (bs == false) {
                    if (ErrorMessage.contains("invalid"))
                        ErrorMessage = ErrorMessage + "state,";
                    else
                        ErrorMessage = ErrorMessage + "invalid state,";

                }

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

How do I install the babel-polyfill library?

For Babel version 7, if your are using @babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.

With this flag specified, babel@7 will optimize and only include the polyfills you needs.

To use this flag, after installation:

npm install --save-dev  @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

Simply add the flag:

useBuiltIns: "usage" 

to your babel configuration file called "babel.config.js" (also new to Babel@7), under the "@babel/env" section:

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage"  // <-----------------*** add this
         }
      ]
   ];

   return { presets };
};

Reference:


Update Aug 2019:

With the release of Babel 7.4.0 (March 19, 2019) @babel/polyfill is deprecated. Instead of installing @babe/polyfill, you will install core-js:

npm install --save core-js@3

A new entry corejs is added to your babel.config.js

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage",
             corejs: 3  // <----- specify version of corejs used
         }
      ]
   ];

   return { presets };
};

see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3

Reference:

How to write lists inside a markdown table?

Yes, you can merge them using HTML. When I create tables in .md files from Github, I always like to use HTML code instead of markdown.

Github Flavored Markdown supports basic HTML in .md file. So this would be the answer:

Markdown mixed with HTML:

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|

Or pure HTML:

<table>
  <tbody>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
    <tr>
      <td>
        <ul>
          <li>item1</li>
          <li>item2</li>
        </ul>
      </td>
      <td align="center">See the list</td>
      <td align="right">from the first column</td>
    </tr>
  </tbody>
</table>

This is how it looks on Github:

Config Error: This configuration section cannot be used at this path

In my case, it was something else.

When I loaded the solution in a new version of Visual Studio, VS apparently created a new project-specific applicationhost.config file:

MySolutionDir\.vs\config\applicationhost.config

It started using the settings from the new config, instead of my already customized global IIS Express settings. (\Users\%USER%\Documents\IISExpress\config\applicationhost.config)

In my case this was the setting that needed to be set. Of course it could be something else for you:

<section name="ipSecurity" overrideModeDefault="Allow" />

How to set width of mat-table column in angular?

we can add attribute width directly to th

eg:

<ng-container matColumnDef="position" >
    <th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

The type arguments for method cannot be inferred from the usage

Get<S, T> takes two type arguments. When you call service.Get(new Signatur()); how does the compiler know what T is? You'll have to pass it explicitly or change something else about your type hierarchies. Passing it explicitly would look like:

service.Get<Signatur, bool>(new Signatur());

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

Cannot push to GitHub - keeps saying need merge

Sometimes we forgot the pulling and did lots of works in the local environment.

If someone want to push without pull,

git push --force

is working. This is not recommended when working with other people, but when your work is a simple thing or a personal toy project, it will be a quick solution.

Cell spacing in UICollectionView

Try playing around with this method:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout*)collectionViewLayout
    insetForSectionAtIndex:(NSInteger)section {

    UIEdgeInsets insets = UIEdgeInsetsMake(?, ?, ?, ?);

    return insets;
}

Rails - Could not find a JavaScript runtime?

Note from Michael 12/28/2011 - I have changed my accept from this (rubytheracer) to above (nodejs) as therubyracer has code size issues. Heroku now strongly discourage it. It will 'work' but may have size/performance issues.

If you add a runtime, such as therubyracer to your Gemfile and run bundle then try and start the server it should work.

gem 'therubyracer'

A javascript runtime is required for compiling coffeescript and also for uglifier.

Update, 12/12/2011: Some folks found issues with rubytheracer (I think it was mostly code size). They found execjs (or nodejs) worked just as well (if not better) and were much smaller.

n.b. Coffeescript became a standard for 3.1+

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

I recommend rbenv* https://github.com/rbenv/rbenv

* If this meets your criteria: https://github.com/rbenv/rbenv/wiki/Why-rbenv?:

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv's shim approach works by adding a directory to your $PATH.
  • Override shell commands like cd or require prompt hacks. That's dangerous and error-prone.
  • Have a configuration file. There's nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets. Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it's in your $PATH, nothing else needs to know about it.

INSTALLATION

Install Homebrew http://brew.sh

Then:

$ brew update
$ brew install rbenv 
$ brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

UPDATE
There's one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window […] SGI Sep 30 at 12:01 —https://stackoverflow.com/users/119770

$ rbenv install --list
Available versions:
 1.8.5-p113
 1.8.5-p114
 […]
 2.3.1
 2.4.0-dev
 jruby-1.5.6
 […]
$ rbenv install 2.3.1
[…]

Set the global version:

$ rbenv global 2.3.1
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Set the local version of your repo by adding .ruby-version to your repo's root dir:

$ cd ~/whatevs/projects/new_repo
$ echo "2.3.1" > .ruby-version

For MacOS visit this link

Instagram API - How can I retrieve the list of people a user is following on Instagram

The REST API of Instagram has been discontinued. But you can use GraphQL to get the desired data. Here you can find an overview: https://developers.facebook.com/docs/instagram-api

size of struct in C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Find current directory and file's directory

If you're using Python 3.4, there is the brand new higher-level pathlib module which allows you to conveniently call pathlib.Path.cwd() to get a Path object representing your current working directory, along with many other new features.

More info on this new API can be found here.

Get city name using geolocation

You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {
            console.log(position.coords.latitude)
            console.log(position.coords.longitude)

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                console.log(location)
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

and to display this data on the page using jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>

    <p>Country: <span id="country"></span></p>
    <p>State: <span id="state"></span></p>
    <p>City: <span id="city"></span></p>
    <p>Address: <span id="address"></span></p>

    <p>Latitude: <span id="latitude"></span></p>
    <p>Longitude: <span id="longitude"></span></p>

    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

How can I resolve the error: "The command [...] exited with code 1"?

For me : I have a white space in my path's folder name G:\Other Imp Projects\Mi.....

Solution 1 :

Remove white space from folder

Example: Other Imp Projects ->> Other_Imp_Projects

Solution 2:

add Quote ("") for your path.

Example: mkdir "$(ProjectDir)$(OutDir)Configurations" //see double quotes

sudo in php exec()

I had a similar situation trying to exec() a backend command and also getting no tty present and no askpass program specified in the web server error log. Original (bad) code:

$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);

A bash wrapper solved this issue, such as:

$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);

Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command portion.

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

How about head ?

echo alonglineoftext | head -c 9

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

unable to set private key file: './cert.pem' type PEM

After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.

So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.

Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!

How they are concatenated? It is quite easy. Put them one after another in the same file.

You can get more help on this here.

I believe this might help you.

How do I set the timeout for a JAX-WS webservice client?

Not sure if this will help in your context...

Can the soap object be cast as a BindingProvider ?

MyWebServiceSoap soap;
MyWebService service = new MyWebService("http://www.google.com");
soap = service.getMyWebServiceSoap();
// set timeouts here
((BindingProvider)soap).getRequestContext().put("com.sun.xml.internal.ws.request.timeout", 10000);
    soap.sendRequestToMyWebService();

On the other hand if you are wanting to set the timeout on the initialization of the MyWebService object then this will not help.

This worked for me when wanting to timeout the individual WebService calls.

Convert seconds value to hours minutes seconds?

You should have more luck with

hours = roundThreeCalc.divide(var3600, BigDecimal.ROUND_FLOOR);
myremainder = roundThreeCalc.remainder(var3600);
minutes = myremainder.divide(var60, BigDecimal.ROUND_FLOOR);
seconds = myremainder.remainder(var60);

This will drop the decimal values after each division.

Edit: If that didn't work, try this. (I just wrote and tested it)

public static int[] splitToComponentTimes(BigDecimal biggy)
{
    long longVal = biggy.longValue();
    int hours = (int) longVal / 3600;
    int remainder = (int) longVal - hours * 3600;
    int mins = remainder / 60;
    remainder = remainder - mins * 60;
    int secs = remainder;

    int[] ints = {hours , mins , secs};
    return ints;
}

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

SQL update fields of one table from fields of another one

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

How to use table variable in a dynamic sql statement?

You can't do this because the table variables are out of scope.

You would have to declare the table variable inside the dynamic SQL statement or create temporary tables.

I would suggest you read this excellent article on dynamic SQL.

http://www.sommarskog.se/dynamic_sql.html

Parsing Json rest api response in C#

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

Do I really need to encode '&' as '&amp;'?

A couple of years ago, we got a report that one of our web apps wasn't displaying correctly in Firefox. It turned out that the page contained a tag that looked like

<div style="..." ... style="...">

When faced with a repeated style attribute, IE combines both of the styles, while Firefox only uses one of them, hence the different behavior. I changed the tag to

<div style="...; ..." ...>

and sure enough, it fixed the problem! The moral of the story is that browsers have more consistent handling of valid HTML than of invalid HTML. So, fix your damn markup already! (Or use HTML Tidy to fix it.)

Get most recent row for given ID

Simple Way To Achieve

I know it's an old question You can also do something like

SELECT * FROM Table WHERE id=1 ORDER BY signin DESC

In above, query the first record will be the most recent record.

For only one record you can use something like

SELECT top(1) * FROM Table WHERE id=1 ORDER BY signin DESC

Above query will only return one latest record.

Cheers!

Blurry text after using CSS transform: scale(); in Chrome

Try using zoom: 101%; for complex designs when you can't use a combination of zoom + scale.

How does the vim "write with sudo" trick work?

FOR NEOVIM

Due to problems with interactive calls (https://github.com/neovim/neovim/issues/1716), I am using this for neovim, based on Dr Beco's answer:

cnoremap w!! execute 'silent! write !SUDO_ASKPASS=`which ssh-askpass` sudo tee % >/dev/null' <bar> edit!

This will open a dialog using ssh-askpass asking for the sudo password.

Add views in UIStackView programmatically

It is really not recommended to set a height constraint... If you can, never, never, never set a height! You need to check all the constraints of the views inside your UIStackView and be sure that there is constraints for bottom, top, leading and trailing. Someone said to me: it is like a guy pushing on walls. If he don't push on 4 sides, one of the wall will fall on him.

How can I make a countdown with NSTimer?

Make Countdown app Xcode 8.1, Swift 3

import UIKit
import Foundation

class ViewController: UIViewController, UITextFieldDelegate {

    var timerCount = 0
    var timerRunning = false

    @IBOutlet weak var timerLabel: UILabel! //ADD Label
    @IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown

    override func viewDidLoad() {
        super.viewDidLoad()

        //Reset
        timerLabel.text = ""
        if timerCount == 0 {
            timerRunning = false
        }
}

       //Figure out Count method
    func Counting() {
        if timerCount > 0 {
        timerLabel.text = "\(timerCount)"
            timerCount -= 1
        } else {
            timerLabel.text = "GO!"

        }

    }

    //ADD Action Button
    @IBAction func startButton(sender: UIButton) {

        //Figure out timer
        if timerRunning == false {
         _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
            timerRunning = true
        }

        //unwrap textField and Display result
        if let countebleNumber = Int(textField.text!) {
            timerCount = countebleNumber
            textField.text = "" //Clean Up TextField
        } else {
            timerCount = 3 //Defoult Number to Countdown if TextField is nil
            textField.text = "" //Clean Up TextField
        }

    }

    //Dismiss keyboard
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }

}

https://github.com/nikae/CountDown-

Export data from R to Excel

Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

Example usage:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

Adding gif image in an ImageView in android

with latest Glide library

use Gradle:

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.8.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
}

in activity or fragment:

ImageView imageView = findViewById(R.id.imageView);

/* from internet*/
Glide.with(this)
        .load("https://media.giphy.com/media/98uBZTzlXMhkk/giphy.gif")
        .into(imageView);

/*from raw folder*/
Glide.with(this)
        .load(R.raw.giphy)
        .into(imageView);

Set the location in iPhone Simulator

In my delegate callback, I check to see if I'm running in a simulator (#if TARGET_ IPHONE_SIMULATOR) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.

JQuery .on() method with multiple event handlers to one selector

And you can combine same events/functions in this way:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    'click blur paste' : function() {
        // Handle click...
    }
}, "input");

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Works for me, has nothing to do with PHP 5.3. Just like many such options it cannot be overriden via ini_set() when safe_mode is enabled. Check your updated php.ini (and better yet: change the memory_limit there too).

Changing font size and direction of axes text in ggplot2

Use theme():

d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))

Obtain form input fields using jQuery?

http://api.jquery.com/serializearray/

$('#form').on('submit', function() {
    var data = $(this).serializeArray();
});

This can also be done without jQuery using the XMLHttpRequest Level 2 FormData object

http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface

var data = new FormData([form])

Pointers in Python?

Yes! there is a way to use a variable as a pointer in python!

I am sorry to say that many of answers were partially wrong. In principle every equal(=) assignation shares the memory address (check the id(obj) function), but in practice it is not such. There are variables whose equal("=") behaviour works in last term as a copy of memory space, mostly in simple objects (e.g. "int" object), and others in which not (e.g. "list","dict" objects).

Here is an example of pointer assignation

dict1 = {'first':'hello', 'second':'world'}
dict2 = dict1 # pointer assignation mechanism
dict2['first'] = 'bye'
dict1
>>> {'first':'bye', 'second':'world'}

Here is an example of copy assignation

a = 1
b = a # copy of memory mechanism. up to here id(a) == id(b)
b = 2 # new address generation. therefore without pointer behaviour
a
>>> 1

Pointer assignation is a pretty useful tool for aliasing without the waste of extra memory, in certain situations for performing comfy code,

class cls_X():
   ...
   def method_1():
      pd1 = self.obj_clsY.dict_vars_for_clsX['meth1'] # pointer dict 1: aliasing
      pd1['var4'] = self.method2(pd1['var1'], pd1['var2'], pd1['var3'])
   #enddef method_1
   ...
#endclass cls_X

but one have to be aware of this use in order to prevent code mistakes.

To conclude, by default some variables are barenames (simple objects like int, float, str,...), and some are pointers when assigned between them (e.g. dict1 = dict2). How to recognize them? just try this experiment with them. In IDEs with variable explorer panel usually appears to be the memory address ("@axbbbbbb...") in the definition of pointer-mechanism objects.

I suggest investigate in the topic. There are many people who know much more about this topic for sure. (see "ctypes" module). I hope it is helpful. Enjoy the good use of the objects! Regards, José Crespo

Simple way to encode a string according to a password?

If you want to be safe, you can use Fernet, which is cryptographically sound. You can use a static "salt" if you don't want to store it separately - you will only lose dictionary and rainbow attack prevention. I chose it because I can pick long or short passwords´, which is not so easy with AES.

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64

#set password
password = "mysecretpassword"
#set message
message = "secretmessage"

kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt="staticsalt", iterations=100000, backend=default_backend())
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)

#encrypt
encrypted = f.encrypt(message)
print encrypted

#decrypt
decrypted = f.decrypt(encrypted)
print decrypted

If that's too complicated, someone suggested simplecrypt

from simplecrypt import encrypt, decrypt
ciphertext = encrypt('password', plaintext)
plaintext = decrypt('password', ciphertext)

How to get request URL in Spring Boot RestController

Allows getting any URL on your system, not just a current one.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

How to check if an alert exists using WebDriver?

The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait object.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}

Accessing constructor of an anonymous class

It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

jQuery UI tabs. How to select a tab based on its id not based on index

This is the answer

var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Mostly in Hibernate , need to add the Entity class in hibernate.cfg.xml like-

<hibernate-configuration>
  <session-factory>

    ....
    <mapping class="xxx.xxx.yourEntityName"/>
 </session-factory>
</hibernate-configuration>

Setting unique Constraint with fluent API?

modelBuilder.Property(x => x.FirstName).IsUnicode().IsRequired().HasMaxLength(50);

File path issues in R using Windows ("Hex digits in character string" error)

readClipboard() works directly too. Copy the path into your clipboard

C:\Users\surfcat\Desktop\2006_dissimilarity.csv

Then

readClipboard()

appears as

[1] "C:\\Users\\surfcat\\Desktop\\2006_dissimilarity.csv"

Send email by using codeigniter library via localhost

$insert = $this->db->insert('email_notification', $data);
                $this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");

                //require ("plugins/mailer/PHPMailerAutoload.php");
                $mail = new PHPMailer;
                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ),
                );

                $message="
                     Your Account Has beed created successfully by Admin:
                    Username: ".$this->input->post('username')." <br><br>
                    Email: ".$this->input->post('sender_email')." <br><br>
                    Regargs<br>
                    <div class='background-color:#666;color:#fff;padding:6px;
                    text-align:center;'>
                         Bookly Admin.
                    </div>
                ";
                $mail->isSMTP(); // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
                $mail->SMTPAuth = true; 
                $subject = "Hello  ".$this->input->post('username');
                $mail->SMTDebug=2;
                $email = $this->input->post('sender_email'); //this email is user email
                $from_label = "Account Creation";
                $mail->Username = 'your email'; // SMTP username
                $mail->Password = 'password'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 465;
                $mail->setFrom($from_label);
                $mail->addAddress($email, 'Bookly Admin');
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
             if($mail->send()){

                  }

How can I solve equations in Python?

If you only want to solve the extremely limited set of equations mx + c = y for positive integer m, c, y, then this will do:

import re
def solve_linear_equation ( equ ):
    """
    Given an input string of the format "3x+2=6", solves for x.
    The format must be as shown - no whitespace, no decimal numbers,
    no negative numbers.
    """
    match = re.match(r"(\d+)x\+(\d+)=(\d+)", equ)
    m, c, y = match.groups()
    m, c, y = float(m), float(c), float(y) # Convert from strings to numbers
    x = (y-c)/m
    print ("x = %f" % x)

Some tests:

>>> solve_linear_equation("2x+4=12")
x = 4.000000
>>> solve_linear_equation("123x+456=789")
x = 2.707317
>>> 

If you want to recognise and solve arbitrary equations, like sin(x) + e^(i*pi*x) = 1, then you will need to implement some kind of symbolic maths engine, similar to maxima, Mathematica, MATLAB's solve() or Symbolic Toolbox, etc. As a novice, this is beyond your ken.

JUnit Eclipse Plugin?


Maybe you're in the wrong perspective?

Eclipse has a construct called a "perspective"; it's a task-oriented arrangement of windows, toolbar buttons, and menus. There's a Java perspective, a Debug perspective, there's probably a PHP perspective, etc. If you're not in the Java perspective, you won't see some of the buttons you expect (like New Class).

To switch perspectives, see the long-ish buttons on the right side of the toolbar, or use the Window menu.

Table fixed header and scrollable body

You can place two div where 1st div (Header) will have transparent scroll bar and 2nd div will be have data with visible/auto scroll bar. Sample has angular code snippet for looping through the data.

Below code worked for me -

<div id="transparentScrollbarDiv" class="container-fluid" style="overflow-y: scroll;">
    <div class="row">
        <div class="col-lg-3 col-xs-3"><strong>{{col1}}</strong></div>
        <div class="col-lg-6 col-xs-6"><strong>{{col2}}</strong></div>
        <div class="col-lg-3 col-xs-3"><strong>{{col3}}</strong></div>
    </div>
</div>
<div class="container-fluid" style="height: 150px; overflow-y: auto">
    <div>
        <div class="row" ng-repeat="row in rows">
            <div class="col-lg-3 col-xs-3">{{row.col1}}</div>
            <div class="col-lg-6 col-xs-6">{{row.col2}}</div>
            <div class="col-lg-3 col-xs-3">{{row.col3}}</div>
        </div>
    </div>
</div>

Additional style to hide header scroll bar -

<style>
        #transparentScrollbarDiv::-webkit-scrollbar {
            width: inherit;
        }

        /* this targets the default scrollbar (compulsory) */

        #transparentScrollbarDiv::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* the new scrollbar will have a flat appearance with the set background color */

        #transparentScrollbarDiv::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        /* this will style the thumb, ignoring the track */

        #transparentScrollbarDiv::-webkit-scrollbar-button {
            background-color: transparent;
        }

        /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

        #transparentScrollbarDiv::-webkit-scrollbar-corner {
            background-color: transparent;
        }

        /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */
    </style>

for each loop in Objective-C for accessing NSMutable dictionary

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

Making macOS Installer Packages which are Developer ID ready

Here is a build script which creates a signed installer package out of a build root.

#!/bin/bash
# TRIMCheck build script
# Copyright Doug Richardson 2015
# Usage: build.sh
#
# The result is a disk image that contains the TRIMCheck installer.
#

DSTROOT=/tmp/trimcheck.dst
SRCROOT=/tmp/trimcheck.src

INSTALLER_PATH=/tmp/trimcheck
INSTALLER_PKG="TRIMCheck.pkg"
INSTALLER="$INSTALLER_PATH/$INSTALLER_PKG"

#
# Clean out anything that doesn't belong.
#
echo Going to clean out build directories
rm -rf build $DSTROOT $SRCROOT $INSTALLER_PATH
echo Build directories cleaned out


#
# Build
#
echo ------------------
echo Installing Sources
echo ------------------
xcodebuild -project TRIMCheck.xcodeproj installsrc SRCROOT=$SRCROOT || exit 1

echo ----------------
echo Building Project
echo ----------------
pushd $SRCROOT
xcodebuild -project TRIMCheck.xcodeproj -target trimcheck -configuration Release install || exit 1
popd

echo ------------------
echo Building Installer
echo ------------------
mkdir -p "$INSTALLER_PATH" || exit 1

echo "Runing pkgbuild. Note you must be connected to Internet for this to work as it"
echo "has to contact a time server in order to generate a trusted timestamp. See"
echo "man pkgbuild for more info under SIGNED PACKAGES."
pkgbuild --identifier "com.delicioussafari.TRIMCheck" \
    --sign "Developer ID Installer: Douglas Richardson (4L84QT8KA9)" \
    --root "$DSTROOT" \
    "$INSTALLER" || exit 1


echo Successfully built TRIMCheck
open "$INSTALLER_PATH"

exit 0

How to position two elements side by side using CSS

give your boxes the class foo (or whatever) and add the css

.foo{
    float: left;
}

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())

How to include JavaScript file or library in Chrome console?

I use this to load ko knockout object in console

document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

or host locally

document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

How to copy a folder via cmd?

xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c

should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).

For reference about the arguments: http://ss64.com/nt/xcopy.html

Display Adobe pdf inside a div

You can use the Javascript library PDF.JS to display a PDF inside a div. The size of the PDF can be adjusted according to the size of the div. You can also setup event handlers for moving to next / previous pages of the PDF.

You can checkout PDF.JS Tutorial - How to display a PDF with Javascript to see how PDF.JS can be integrated in your HTML code.

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

iPhone: How to get current milliseconds?

I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime has the least overhead by a small margin. timeIntervalSince1970 is far slower than the others, probably due to NSDate instantiation overhead, though it may not matter for many use cases.

I'd recommend CACurrentMediaTime if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday if portability is a priority for you.

iPhone 4S

CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call

iPad 3

CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call

Change visibility of ASP.NET label with JavaScript

This is the easiest way I found:

        BtnUpload.Style.Add("display", "none");
        FileUploader.Style.Add("display", "none");
        BtnAccept.Style.Add("display", "inherit");
        BtnClear.Style.Add("display", "inherit");

I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.

Populating VBA dynamic arrays

As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve. Brett suggested Mod to do this.

You can also use a user defined Type and Sub to do this. Consider my code below:

Public Type dsIntArrayType
   eElems() As Integer
   eSize As Integer
End Type

Public Sub PushBackIntArray( _
    ByRef dsIntArray As dsIntArrayType, _
    ByVal intValue As Integer)

    With dsIntArray
    If UBound(.eElems) < (.eSize + 1) Then
        ReDim Preserve .eElems(.eSize * 2 + 1)
    End If
    .eSize = .eSize + 1
    .eElems(.eSize) = intValue
    End With

End Sub

This calls ReDim Preserve only when the size has doubled. The member variable eSize keeps track of the actual data size of eElems. This approach has helped me improve performance when final array length is not known until run time.

Hope this helps others too.

When to use in vs ref vs out

You can use the out contextual keyword in two contexts (each is a link to detailed information), as a parameter modifier or in generic type parameter declarations in interfaces and delegates. This topic discusses the parameter modifier, but you can see this other topic for information on the generic type parameter declarations.

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example: C#

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile: C#

class CS0663_Example
{
    // Compiler error CS0663: "Cannot define overloaded 
    // methods that differ only on ref and out".
    public void SampleMethod(out int i) { }
    public void SampleMethod(ref int i) { }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this: C#

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

Properties are not variables and therefore cannot be passed as out parameters.

For information about passing arrays, see Passing Arrays Using ref and out (C# Programming Guide).

You can't use the ref and out keywords for the following kinds of methods:

Async methods, which you define by using the async modifier.

Iterator methods, which include a yield return or yield break statement.

Example

Declaring an out method is useful when you want a method to return multiple values. The following example uses out to return three variables with a single method call. Note that the third argument is assigned to null. This enables methods to return values optionally. C#

class OutReturnExample
{
    static void Method(out int i, out string s1, out string s2)
    {
        i = 44;
        s1 = "I've been returned";
        s2 = null;
    }
    static void Main()
    {
        int value;
        string str1, str2;
        Method(out value, out str1, out str2);
        // value is now 44
        // str1 is now "I've been returned"
        // str2 is (still) null;
    }
}

Only variables should be passed by reference

save the array from explode() to a variable, and then call end() on this variable:

$tmp = explode('.', $file_name);
$file_extension = end($tmp);

btw: I use this code to get the file extension:

$ext = substr( strrchr($file_name, '.'), 1);

where strrchr extracts the string after the last . and substr cuts off the .

Excel CSV - Number cell format

The Text Import Wizard method does NOT work when the CSV file being imported has line breaks within a cell. This method handles this scenario(at least with tab delimited data):

  1. Create new Excel file
  2. Ctrl+A to select all cells
  3. In Number Format combobox, select Text
  4. Open tab delimited file in text editor
  5. Select all, copy and paste into Excel

Enable UTF-8 encoding for JavaScript

I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.

"Full screen" <iframe>

Impossible to say without seeing a live example, but try giving both bodies margin: 0px

CSS: styled a checkbox to look like a button, is there a hover?

Do what Kelly said...

BUT. Instead of having the input positioned absolute and top -20px (just hiding it off the page), make the input box hidden.

example:

<input type="checkbox" hidden> 

Works better and can put it anywhere on the page.

How to do ToString for a possibly null object?

I had the same problem and solved it by simply casting the object to string. This works for null objects too because strings can be nulls. Unless you absolutely don't want to have a null string, this should work just fine:

string myStr = (string)myObj; // string in a object disguise or a null

How to make shadow on border-bottom?

funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:

<h3>Your Text</h3><div class="border-shadow"></div>

and the css:

    .shadow {
        width:100%;
        height:1px; // = "border height (without the shadow)!"
        background:#000; // = "border color!"
        -webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        -moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"

}

Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow

jquery ui Dialog: cannot call methods on dialog prior to initialization

The new jQuery UI version will not allow you to call UI methods on dialog which is not initialized. As a workaround, you can use the below check to see if the dialog is alive.

if (modalDialogObj.hasClass('ui-dialog-content')) {
    // call UI methods like modalDialogObj.dialog('isOpen')
} else {
    // it is not initialized yet
}

npm ERR! Error: EPERM: operation not permitted, rename

I had the same problem after updating to npm to 5.4.2, npm start giving the same error for most npm commands. Some solution suggest to run it with --no-optional, but it didn't always work.

Others suggested to downgrade, but I didn't want to downgrade.

I suspected that there was a problem with the installation, not sure what it was.

So I re-updated my npm:

npm i -g npm

and worked fine since then.

Editing hosts file to redirect url?

You could use the RedirectMatch directive in Apache to do something similar you want.

It's pretty simple.

RedirectMatch / http://222.222.222.222/

Anyway, I can't see any reason to do that thing. Aren't you trying to intercept traffic? There are better ways. For Linux boxes as a router: iptables -j REDIRECT + Squid or Apache. For Cisco routers, you can use WCCP to a Cache or Web Server...

Getting list of lists into pandas DataFrame

Even without pop the list we can do with set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

Update from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

Stop a youtube video with jquery?

for those who are looking javascript solution

let iframeDiv = document.getElementById('demoVideo');
                        let video = iframeDiv.src;
                        iframeDiv.src = "";
                        iframeDiv.src = video;

It perfectly worked for me just put id='demoVideo' in your iframe tag and you are good to go :)

How to play videos in android from assets folder or raw folder?

PlayVideoActivity.java:

public class PlayVideoActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.documentariesandyou));
        videoView.start();
    }
}

activity_play_video.xml:

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

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </VideoView>

</LinearLayout>

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there an easy way to return a string repeated X number of times?

If you're using .NET 4.0, you could use string.Concat together with Enumerable.Repeat.

int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));

Otherwise I'd go with something like Adam's answer.

The reason I generally wouldn't advise using Andrey's answer is simply that the ToArray() call introduces superfluous overhead that is avoided with the StringBuilder approach suggested by Adam. That said, at least it works without requiring .NET 4.0; and it's quick and easy (and isn't going to kill you if efficiency isn't too much of a concern).

Android Fastboot devices not returning device

TLDR - In addition to the previous responses. There might be a problem with the version of the fastboot command. Try to download the newest one via Android SDK Manager instead of default one available in the OS repository.

There is one more thing you can do to fix this issue. I had the similar problem when trying to flash Nexus Player. All the adb commands we working fine while in normal boot mode. However, after switching to fastboot mode I wasn't able to execute fastboot commands. My device was not visible in the output of the fastboot devices command. I've set the right rules in /etc/udev/rules.d/11-android.rules file. The lsusb command showed that the device has been pluged in.

The soultion was quite simple. I've downloaded the the fastboot via Android Studio's SDK Manager instead of using the default one available in Ubuntu packages.

All you need is sdkmanager. Download the Android SDK Platform Tools and replace the default /usr/bin/fastboot with the new one.

Check free disk space for current partition in bash

  1. df command : Report file system disk space usage
  2. du command : Estimate file space usage

Type df -h or df -k to list free disk space:

 $ df -h

OR

 $ df -k

du shows how much space one or more files or directories is using:

 $ du -sh

The -s option summarizes the space a directory is using and -h option provides Human-readable output.

How do I filter ForeignKey choices in a Django ModelForm?

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id)

If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

Replace all spaces in a string with '+'

Here's an alternative that doesn't require regex:

var str = 'a b c';
var replaced = str.split(' ').join('+');

How to logout and redirect to login page using Laravel 5.4?

In Laravel 6.2

Add the following route to : web.php

Route::post('logout', 'Auth\LoginController@logout')->name('logout');

Using Achor tag with logout using a POST form. This way you will also need the CSRF token.

 <a class="log-out-btn" href="#" onclick="event.preventDefault();document.getElementById('logout-form').submit();"> Logout </a>

 <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
          {{ csrf_field() }}
  </form>

How to vertically align label and input in Bootstrap 3?

The problem is that your <label> is inside of an <h2> tag, and header tags have a margin set by the default stylesheet.

Set HTML element's style property in javascript

For me, this works:

function transferAllStyles(elemFrom, elemTo)
{
  var prop;
  for (prop in elemFrom.style)
    if (typeof prop == "string")
      try { elemTo.style[prop] = elemFrom.style[prop]; }
      catch (ex) { /* don't care */ }
}

What is the purpose of Android's <merge> tag in XML layouts?

Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:

public class GridViewAdapter extends BaseAdapter {
     // ... typical Adapter class methods
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        WallpaperView wallpaperView;
        if (convertView == null)
           wallpaperView = new WallpaperView(activity);
        else
            wallpaperView = (WallpaperView) convertView;

        wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
        return wallpaperView;
    }
}

here is the custom viewgroup:

public class WallpaperView extends RelativeLayout {

    public WallpaperView(Context context) {
        super(context);
        init(context);
    }
    // ... typical constructors

    private void init(Context context) {
        View.inflate(context, R.layout.wallpaper_item, this);
        imageLoader = AppController.getInstance().getImageLoader();
        imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
        thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
        // ...some logic that sets the views
    }
}

and here is the XML:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/imgLoader"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ico_loader" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

Remove characters after specific character in string, then remove substring?

Here's another simple solution. The following code will return everything before the '|' character:

if (path.Contains('|'))
   path = path.Split('|')[0];

In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':

if (path.Contains('|'))
   path = path.Split('|')[1];

(All I changed in the second piece of code was the index of the array.)

Strip double quotes from a string in .NET

if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json. as it's bad json with "quoted" text identifiers.

Add the below method to a class containing your extension methods.

  public static string Remove(this string text, char character)
  {
      var sb = new StringBuilder();
      foreach (char c in text)
      {
         if (c != character)
             sb.Append(c);
      }
      return sb.ToString();
  }

you can then use this extension method:

var text= myString.Remove('"');

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Cross-Origin Request Headers(CORS) with PHP headers

Access-Control-Allow-Headers does not allow * as accepted value, see the Mozilla Documentation here.

Instead of the asterisk, you should send the accepted headers (first X-Requested-With as the error says).

How to get the filename without the extension from a path in Python?

https://docs.python.org/3/library/os.path.html

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c

How to get attribute of element from Selenium?

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:

    • To retrieve any attribute form a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute form an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

All shards failed

first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like

  1. Shards are actually in non-recoverable state, if your cluster and index state are in Yellow and RED, then it is one of the reason.
  2. Due to some shard recovery happening in background, shards didn't respond.
  3. Due to bad syntax of your query, ES responds in all shards failed.

In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.

The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

Parse large JSON file in Nodejs

I wrote a module that can do this, called BFJ. Specifically, the method bfj.match can be used to break up a large stream into discrete chunks of JSON:

const bfj = require('bfj');
const fs = require('fs');

const stream = fs.createReadStream(filePath);

bfj.match(stream, (key, value, depth) => depth === 0, { ndjson: true })
  .on('data', object => {
    // do whatever you need to do with object
  })
  .on('dataError', error => {
    // a syntax error was found in the JSON
  })
  .on('error', error => {
    // some kind of operational error occurred
  })
  .on('end', error => {
    // finished processing the stream
  });

Here, bfj.match returns a readable, object-mode stream that will receive the parsed data items, and is passed 3 arguments:

  1. A readable stream containing the input JSON.

  2. A predicate that indicates which items from the parsed JSON will be pushed to the result stream.

  3. An options object indicating that the input is newline-delimited JSON (this is to process format B from the question, it's not required for format A).

Upon being called, bfj.match will parse JSON from the input stream depth-first, calling the predicate with each value to determine whether or not to push that item to the result stream. The predicate is passed three arguments:

  1. The property key or array index (this will be undefined for top-level items).

  2. The value itself.

  3. The depth of the item in the JSON structure (zero for top-level items).

Of course a more complex predicate can also be used as necessary according to requirements. You can also pass a string or a regular expression instead of a predicate function, if you want to perform simple matches against property keys.

Updates were rejected because the tip of your current branch is behind its remote counterpart

To make sure your local branch FixForBug is not ahead of the remote branch FixForBug pull and merge the changes before pushing.

git pull origin FixForBug
git push origin FixForBug

AngularJS: ng-model not binding to ng-checked for checkboxes

You can use ng-value-true to tell angular that your ng-model is a string.

I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)

ng-true-value="'1'"

Video file formats supported in iPhone

Short answer: H.264 MPEG (MP4)

Long answer from Apple.com:

Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,

Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

http://www.apple.com/iphone/specs.html

VB.NET Empty String Array

Not sure why you'd want to, but the C# way would be

string[] newArray = new string[0];

I'm guessing that VB won't be too dissimilar to this.

If you're building an empty array so you can populate it with values later, you really should consider using

List<string>

and converting it to an array (if you really need it as an array) with

newListOfString.ToArray();

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The docker run command has a --ulimit flag you can use this flag to set the open file limit in your docker container.

Run the following command when spinning up your container to set the open file limit.

docker run --ulimit nofile=<softlimit>:<hardlimit> the first value before the colon indicates the soft file limit and the value after the colon indicates the hard file limit. you can verify this by running your container in interactive mode and executing the following command in your containers shell ulimit -n

PS: check out this blog post for more clarity

How to remove certain characters from a string in C++?

   string str("(555) 555-5555");

   char chars[] = "()-";

   for (unsigned int i = 0; i < strlen(chars); ++i)
   {
      // you need include <algorithm> to use general algorithms like std::remove()
      str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
   }

   // output: 555 5555555
   cout << str << endl;

To use as function:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
}
//example of usage:
removeCharsFromString( str, "()-" );

How to pass parameters to a partial view in ASP.NET MVC?

Use this overload (RenderPartialExtensions.RenderPartial on MSDN):

public static void RenderPartial(
    this HtmlHelper htmlHelper,
    string partialViewName,
    Object model
)

so:

@{Html.RenderPartial(
    "FullName",
    new { firstName = model.FirstName, lastName = model.LastName});
}

How to import an existing project from GitHub into Android Studio

Steps:

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

What key shortcuts are to comment and uncomment code?

I went to menu: ToolsOptions.

EnvironmentKeyboard.

Show command containing and searched: comment

I changed Edit.CommentSelection and assigned Ctrl+/ for commenting.

And I left Ctrl+K then U for the Edit.UncommentSelection.

These could be tweaked to the user's preference as to what key they would prefer for commenting/uncommenting.

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

SQL Server error on update command - "A severe error occurred on the current command"

This seems to happen when there's a generic problem with your data source that it isn't handling.

In my case I had inserted a bunch of data, the indexes had become corrupt on the table, they needed rebuilding. I found a script to rebuild them all, seemed to fix it. To find the error I ran the same query on the database - one that had worked 100+ times previously.

PHP checkbox set to check based on database value

Add this code inside your input tag

<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>

Android and setting alpha for (image) view alpha

There is now an XML alternative:

        <ImageView
        android:id="@+id/example"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        android:alpha="0.7" />

It is: android:alpha="0.7"

With a value from 0 (transparent) to 1 (opaque).

VBA: Convert Text to Number

''Convert text to Number with ZERO Digits and Number convert ZERO Digits  

Sub ZERO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0"
 Set rSelection = Nothing
End Sub

''Convert text to Number with TWO Digits and Number convert TWO Digits  

Sub TWO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.00"
 Set rSelection = Nothing
End Sub

''Convert text to Number with SIX Digits and Number convert SIX Digits  


Sub SIX_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.000000"
 Set rSelection = Nothing
End Sub



std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

add string to String array

you would have to write down some method to create a temporary array and then copy it like

public String[] increaseArray(String[] theArray, int increaseBy)  
{  
    int i = theArray.length;  
    int n = ++i;  
    String[] newArray = new String[n];  
    for(int cnt=0;cnt<theArray.length;cnt++)
    {  
        newArray[cnt] = theArray[cnt];  
    }  
    return newArray;  
}  

or The ArrayList would be helpful to resolve your problem.

PHP filesize MB/KB conversion

function getNiceFileSize($file, $digits = 2){
    if (is_file($file)) {
        $filePath = $file;
        if (!realpath($filePath)) {
            $filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
        }
        $fileSize = filesize($filePath);
        $sizes = array("TB", "GB", "MB", "KB", "B");
        $total = count($sizes);
        while ($total-- && $fileSize > 1024) {
            $fileSize /= 1024;
        }
        return round($fileSize, $digits) . " " . $sizes[$total];
    }
    return false;
}

Show dialog from fragment?

You should use a DialogFragment instead.

C# 'or' operator?

The single " | " operator will evaluate both sides of the expression.

    if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

The double operator " || " will only evaluate the left side if the expression returns true.

    if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

C# has many similarities to C++ but their still are differences between the two languages ;)

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

how to get yesterday's date in C#

You will get yesterday date by this following code snippet.

DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);

Object creation on the stack/heap?

The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

DEMO

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

MyStore.js

const store = createStore(myReducer);
export store;

or

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

or if you used default

import store from './MyStore'
store.dispatch(...)

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

string comparison in batch file

Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.

Works for me...

C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes

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

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

See this MSDN article on how to do that.

How can I kill whatever process is using port 8080 so that I can vagrant up?

try netstat

netstat -vanp tcp | grep 3000

if your netstat doesn't support -p , use lsof

sudo lsof -i tcp:3000 

For Centos 7 use

netstat -vanp --tcp | grep 3000

Detect Route Change with react-router

React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Reversing a String with Recursion in Java

Another Solutions for reversing a String in Java.

Convert you string into a char array using .toCharArray() function.

public static char[] reverse(char in[], int inLength, char out[],
            int tractOut) {

        if (inLength >= 0) {
            out[tractOut] = in[inLength];
            reverse(in, inLength - 1, out, tractOut + 1);
        }

        return null;

    }

What does the keyword "transient" mean in Java?

It means that trackDAO should not be serialized.

How can I make grep print the lines below and above each matching line?

Use -B, -A or -C option

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

Anaconda Installed but Cannot Launch Navigator

I figured out the reason as to why:

1-There seems to be no navigator icon

2-When conducting the above steps of running the "anaconda-navigator" command in prompt (whether cmd or Anaconda) it yields "anaconda navigator is not recognized as an internal or external command"

This was very frustrating to me as I'd installed the proper version multiple times with no avail.

To solve this problem :

  • in the installation process, there will be an advanced options step with 2 selections one of which is unchecked (the top one). Make sure you check it which will add the navigator to the path of your machine variables.

Cheers, Hossam

How do I compare strings in GoLang?

Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:

Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..) seems like the most performant choice):

goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4               10000        182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4        10000        114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4                10000       2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4               10000       3592486 ns/op

BenchmarkStringOps/one_string_in_caps::equality_op-4               10000        417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4        10000        153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4                10000       3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4               10000       3861189 ns/op

BenchmarkStringOps/weird_casing_situation::equality_op-4           10000        619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4    10000        148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4            10000       3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4           10000       3637832 ns/op

Since there are quite a few options, so here's the code to generate benchmarks.

package main

import (
    "fmt"
    "strings"
    "testing"

    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func BenchmarkStringOps(b *testing.B) {
    foldCaser := cases.Fold()
    lowerCaser := cases.Lower(language.English)

    tests := []struct{
        description string
        first, second string
    }{
        {
            description: "both strings equal",
            first: "aaaa",
            second: "aaaa",
        },
        {
            description: "one string in caps",
            first: "aaaa",
            second: "AAAA",
        },
        {
            description: "weird casing situation",
            first: "aAaA",
            second: "AaAa",
        },
    }

    for _, tt := range tests {
        b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringEqualsOperation(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsEqualFold(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
            }
        })

        b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
            }
        })
    }
}

func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.ToLower(first) == strings.ToLower(second)
    }
}

func benchmarkStringsEqualFold(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.EqualFold(first, second)
    }
}

func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

PHP json_encode encoding numbers as strings

So Pascal MARTIN isn't getting enough credit here. Checking for numeric values on every JSON return is not feasable for an existing project with hundreds of server side functions.

I replaced php-mysql with php-mysqlnd, and the problem went away. Numbers are numbers, strings are strings, booleans are boolean.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Set View Width Programmatically

The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.

How Should I Set Default Python Version In Windows?

If you know about Environment variables and the system variable called path, consider that any version of any binary which comes sooner, will be used as default.

Look at the image below, I have 3 different python versions but python 3.8 will be used as default since it came sooner than the other two. (In case of mentioned image, sooner means higher!)

enter image description here

What is the purpose of the var keyword and when should I use it (or omit it)?

Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.

using javascript to detect whether the url exists before display in iframe

Use a XHR and see if it responds you a 404 or not.

var request = new XMLHttpRequest();  
request.open('GET', 'http://www.mozilla.org', true);
request.onreadystatechange = function(){
    if (request.readyState === 4){
        if (request.status === 404) {  
            alert("Oh no, it does not exist!");
        }  
    }
};
request.send();

But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.

Implement an input with a mask

Use this to implement mask:

https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js

<input id="phn-number" class="ant-input" type="text" placeholder="(XXX) XXX-XXXX" data-inputmask-mask="(999) 999-9999">


jQuery( '#phn-number[data-inputmask-mask]' ).inputmask();

Xcode iOS 8 Keyboard types not supported

This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The only thing that worked for me was the accepted answer of

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();

HOWEVER

This brought about new issues, of having <?xml encoding="utf-8" ?> in the output of the document.

The solution for me was then to do

foreach ($doc->childNodes as $xx) {
    if ($xx instanceof \DOMProcessingInstruction) {
        $xx->parentNode->removeChild($xx);
    }
}

Some solutions told me that to remove the xml header, that I had to perform

$dom->saveXML($dom->documentElement);

This didn't work for me as for a partial document (e.g. a doc with two <p> tags), only one of the <p> tags where being returned.

Missing Push Notification Entitlement

This happened to me suddenly because my app's distribution profile had expired. Xcode began using the wildcard profile instead, which did not have the push notification entitlement enabled. I didn't receive any warning. The fix was easy; I just had to generate another distribution profile for my app in the Apple Developer Member Center, download it, and double-click to install in Xcode.

How to run Pip commands from CMD

Newer versions of Python come with py, the Python Launcher, which is always in the PATH.

Here is how to invoke pip via py:

py -m pip install <packagename>

py allows having several versions of Python on the same machine.

As an example, here is how to invoke the pip from Python 2.7:

py -2.7 -m pip install <packagename>

How to print a percentage value in python?

Then you'd want to do this instead:

print str(int(1.0/3.0*100))+'%'

The .0 denotes them as floats and int() rounds them to integers afterwards again.

Prevent flex items from overflowing a container

It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width on the offending element/container can put it back in line.

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

What is the maximum recursion depth in Python, and how to increase it?

It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can check the recursion limit with sys.getrecursionlimit:

import sys
print(sys.getrecursionlimit())

and change the recursion limit with sys.setrecursionlimit:

sys.setrecursionlimit(1500)

but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.

Find closing HTML tag in Sublime Text

I think, you may want to try another approach with folding enabled.

In both ST2 and ST3, if you enable folding in User settings:

{
    ...(previous item)
    "fold_buttons": true,
    ...(next item, thus the comma)
}

You can see the triangle folding button at the left side of the line where the start tag is. Click it to expand/fold. If you want to copy, fold and copy, you get all block.

enter image description here

How to tell CRAN to install package dependencies automatically?

On your own system, try

install.packages("foo", dependencies=...)

with the dependencies= argument is documented as

dependencies: logical indicating to also install uninstalled packages
      which these packages depend on/link to/import/suggest (and so
      on recursively).  Not used if ‘repos = NULL’.  Can also be a
      character vector, a subset of ‘c("Depends", "Imports",
      "LinkingTo", "Suggests", "Enhances")’.

      Only supported if ‘lib’ is of length one (or missing), so it
      is unambiguous where to install the dependent packages.  If
      this is not the case it is ignored, with a warning.

      The default, ‘NA’, means ‘c("Depends", "Imports",
      "LinkingTo")’.

      ‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
      "Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
      ‘c("Depends", "Imports", "LinkingTo")’ for added
      dependencies: this installs all the packages needed to run
      ‘pkgs’, their examples, tests and vignettes (if the package
      author specified them correctly).

so you probably want a value TRUE.

In your package, list what is needed in Depends:, see the Writing R Extensions manual which is pretty clear on this.

Attach a body onload event with JS

jcalfee314's idea worked for me - I had a window.onload = onLoad which meant that the functions in <body onload="..."> were not being called (which I don't have control over).

This fixed it:

oldOnLoad = window.onload
window.onload = onLoad;

function onLoad()
{
oldOnLoad();
...
}

Edit: Firefox didn't like oldOnLoad = document.body.onload;, so replaced with oldOnLoad = window.onload.

Why are primes important in cryptography?

Cryptographic algorithms generally rely for their security on having a "difficult problem". Most modern algorithms seem to use the factoring of very large numbers as their difficult problem - if you multiply two large numbers together, computing their factors is "difficult" (i.e. time-consuming). If those two numbers are prime numbers, then there is only one answer, which makes it even more difficult, and also guarantees that when you find the answer, it's the right one, not some other answer that just happens to give the same result.

Add CSS3 transition expand/collapse

OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.

<script>
        function dostuff() {
            if (document.getElementById('MyBox').style.height == "0px") {

                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;"); 
            }
            else {
                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;"); 
             }
        }
    </script>
    <div id="MyBox" style="height: 0px; width: 0px;">
    </div>

    <input type="button" id="buttontest" onclick="dostuff()" value="Click Me">

Assignment inside lambda expression in Python

If you need a lambda to remember state between calls, I would recommend either a function declared in the local namespace or a class with an overloaded __call__. Now that all my cautions against what you are trying to do is out of the way, we can get to an actual answer to your query.

If you really need to have your lambda to have some memory between calls, you can define it like:

f = lambda o, ns = {"flag":True}: [ns["flag"] or o.name, ns.__setitem__("flag", ns["flag"] and o.name)][0]

Then you just need to pass f to filter(). If you really need to, you can get back the value of flag with the following:

f.__defaults__[0]["flag"]

Alternatively, you can modify the global namespace by modifying the result of globals(). Unfortunately, you cannot modify the local namespace in the same way as modifying the result of locals() doesn't affect the local namespace.

git reset --hard HEAD leaves untracked files behind

Remove all things except .git folder and then run git reset --hard

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat