Programs & Examples On #Factory method

A design pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. One of the Gang of Four's creational design patterns.

What are the differences between Abstract Factory and Factory design patterns?

Difference between AbstractFactory and Factory design patterns are as follows:

  • Factory Method is used to create one product only but Abstract Factory is about creating families of related or dependent products.
  • Factory Method pattern exposes a method to the client for creating the object whereas in the case of Abstract Factory they expose a family of related objects which may consist of these Factory methods.
  • Factory Method pattern hides the construction of a single object whereas Abstract Factory hides the construction of a family of related objects. Abstract factories are usually implemented using (a set of) factory methods.
  • Abstract Factory pattern uses composition to delegate the responsibility of creating an object to another class while Factory Method design pattern uses inheritance and relies on a derived class or subclass to create an object.
  • The idea behind the Factory Method pattern is that it allows for the case where a client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job while Abstract Factory pattern is best utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.!

Factory Method Pattern Implementation: Factory Method UML

Abstract Factory Pattern Implementation:

Abstract Factory UML

How to implement the factory method pattern in C++ correctly

extern std::pair<std::string_view, Base*(*)()> const factories[2];

decltype(factories) factories{
  {"blah", []() -> Base*{return new Blah;}},
  {"foo", []() -> Base*{return new Foo;}}
};

What is the difference between Builder Design pattern and Factory Design pattern?

Both are very much similar , but if you have a large number of parameters for object creation with some of them optional with some default values , go for Builder pattern.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

The Abstract Factory Pattern

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

  • The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

  • Actually, the delegated object frequently uses factory methods to perform the instantiation!

Factory pattern

  • Factory patterns are examples of creational patterns

  • Creational patterns abstract the object instantiation process. They hide how objects are created and help make the overall system independent of how its objects are created and composed.

  • Class creational patterns focus on the use of inheritance to decide the object to be instantiated Factory Method

  • Object creational patterns focus on the delegation of the instantiation to another object Abstract Factory

Reference: Factory vs Abstract Factory

What are static factory methods?

A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.

For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.

If you want to implement database pooling, then that would also be done without affecting the rest of the application.

It protects the rest of the application from changes that you may make to the factory, which is the purpose.

The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.

Factory Pattern. When to use factory methods?

Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern.

I have mentioned in detail in an another answer at https://stackoverflow.com/a/49110001/504133

Iterate over a Javascript associative array in sorted order

<script type="text/javascript">
    var a = {
        b:1,
        z:1,
        a:1
    }; // your JS Object
    var keys = [];
    for (key in a) {
        keys.push(key);
    }
    keys.sort();
    var i = 0;
    var keyslen = keys.length;
    var str = '';
    //SORTED KEY ITERATION
    while (i < keyslen) {
        str += keys[i] + '=>' + a[keys[i]] + '\n';
        ++i;
    }
    alert(str);
    /*RESULT:
    a=>1
    b=>1
    z=>1
    */
</script>

Grouping switch statement cases together?

You can't remove keyword case. But your example can be written shorter like this:

switch ((Answer - 1) / 4)                                      
{
   case 0:
      cout << "You need more cars.";
      break;                                        
   case 1:
      cout << "Now you need a house.";
      break;                                        
   default:
      cout << "What are you? A peace-loving hippie freak?";
}

UIWebView open links in Safari

The accepted answer does not work.

If your page loads URLs via Javascript, the navigationType will be UIWebViewNavigationTypeOther. Which, unfortunately, also includes background page loads such as analytics.

To detect page navigation, you need to compare the [request URL] to the [request mainDocumentURL].

This solution will work in all cases:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
    if ([[request URL] isEqual:[request mainDocumentURL]])
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    else
    {       
        return YES;
    }
}

Entity Framework Migrations renaming tables and columns

Nevermind. I was making this way more complicated than it really needed to be.

This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.

public override void Up()
{
    RenameTable("ReportSections", "ReportPages");
    RenameTable("ReportSectionGroups", "ReportSections");
    RenameColumn("ReportPages", "Group_Id", "Section_Id");
}

public override void Down()
{
    RenameColumn("ReportPages", "Section_Id", "Group_Id");
    RenameTable("ReportSections", "ReportSectionGroups");
    RenameTable("ReportPages", "ReportSections");
}

No Multiline Lambda in Python: Why not?

I am starting with python but coming from Javascript the most obvious way is extract the expression as a function....

Contrived example, multiply expression (x*2) is extracted as function and therefore I can use multiline:

def multiply(x):
  print('I am other line')
  return x*2

r = map(lambda x : multiply(x), [1, 2, 3, 4])
print(list(r))

https://repl.it/@datracka/python-lambda-function

Maybe it does not answer exactly the question if that was how to do multiline in the lambda expression itself, but in case somebody gets this thread looking how to debug the expression (like me) I think it will help

Retrofit 2: Get JSON from Response body

you can change your interface with code given below, if you need json String response..

@FormUrlEncoded
@POST("/api/level")
Call<JsonObject> checkLevel(@Field("id") int id);  

and retrofit function with this

Call<JsonObject> call = api.checkLevel(1);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            Log.d("res", response.body().toString());
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.d("error",t.getMessage());
        }
    });

How to set "style=display:none;" using jQuery's attr method?

Based on the comment we are removing one property from style attribute.

Here this was not affect, but when more property are used within the style it helpful.

$('#msform').css('display', '')

After this we use

$("#msform").show();

Fastest way to download a GitHub project

You say:

To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.

And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".

It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:

$ git clone git://github.com/SpringSource/spring-data-graph-examples.git

The git:-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.

I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.

Using % for host when creating a MySQL user

Let's just test.

Connect as superuser, and then:

SHOW VARIABLES LIKE "%version%"; 
+-------------------------+------------------------------+ 
| Variable_name           | Value                        | 
+-------------------------+------------------------------+ 
| version                 | 10.0.23-MariaDB-0+deb8u1-log | 

and then

USE mysql;

Setup

Create a user foo with password bar for testing:

CREATE USER foo@'%' IDENTIFIED BY 'bar'; FLUSH PRIVILEGES;

Connect

To connect to the Unix Domain Socket (i.e. the I/O pipe that is named by the filesystem entry /var/run/mysqld/mysqld.sock or some such), run this on the command line (use the --protocol option to make doubly sure)

mysql -pbar -ufoo
mysql -pbar -ufoo --protocol=SOCKET

One expects that the above matches "user comes from localhost" but certainly not "user comes from 127.0.0.1".

To connect to the server from "127.0.0.1" instead, run this on the command line

mysql -pbar -ufoo --bind-address=127.0.0.1 --protocol=TCP

If you leave out --protocol=TCP, the mysql command will still try to use the Unix domain socket. You can also say:

mysql -pbar -ufoo --bind-address=127.0.0.1 --host=127.0.0.1

The two connection attempts in one line:

export MYSQL_PWD=bar; \
mysql -ufoo --protocol=SOCKET --execute="SELECT 1"; \
mysql -ufoo --bind-address=127.0.0.1 --host=127.0.0.1 --execute="SELECT 1"

(the password is set in the environment so that it is passed to the mysql process)

Verification In Case Of Doubt

To really check whether the connection goes via a TCP/IP socket or a Unix Domain socket

  1. get the PID of the mysql client process by examining the output of ps faux
  2. run lsof -n -p<yourpid>.

You will see something like:

mysql [PID] quux 3u IPv4 [code] 0t0 TCP 127.0.0.1:[port]->127.0.0.1:mysql (ESTABLISHED)

or

mysql [PID] quux 3u unix [code] 0t0 [code] socket

So:

Case 0: Host = '10.10.10.10' (null test)

update user set host='10.10.10.10' where user='foo'; flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Case 1: Host = '%'

update user set host='%' where user='foo'; flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

Case 2: Host = 'localhost'

update user set host='localhost' where user='foo';flush privileges;

Behaviour varies and this apparently depends on skip-name-resolve. If set, causes lines with localhost to be ignored according to the log. The following can be seen in the error log: "'user' entry 'root@localhost' ignored in --skip-name-resolve mode.". This means no connecting through the Unix Domain Socket. But this is empirically not the case. localhost now means ONLY the Unix Domain Socket, and no longer matched 127.0.0.1.

skip-name-resolve is off:

  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

skip-name-resolve is on:

  • Connect using socket: OK
  • Connect from 127.0.0.1: FAILURE

Case 3: Host = '127.0.0.1'

update user set host='127.0.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: OK

Case 4: Host = ''

update user set host='' where user='foo';flush privileges;
  • Connect using socket: OK
  • Connect from 127.0.0.1: OK

(According to MySQL 5.7: 6.2.4 Access Control, Stage 1: Connection Verification, The empty string '' also means “any host” but sorts after '%'. )

Case 5: Host = '192.168.0.1' (extra test)

('192.168.0.1' is one of my machine's IP addresses, change appropriately in your case)

update user set host='192.168.0.1' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

but

  • Connect using mysql -pbar -ufoo -h192.168.0.1: OK (!)

The latter because this is actually TCP connection coming from 192.168.0.1, as revealed by lsof:

TCP 192.168.0.1:37059->192.168.0.1:mysql (ESTABLISHED)

Edge Case A: Host = '0.0.0.0'

update user set host='0.0.0.0' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case B: Host = '255.255.255.255'

update user set host='255.255.255.255' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Edge Case C: Host = '127.0.0.2'

(127.0.0.2 is perfectly valid loopback address equivalent to 127.0.0.1 as defined in RFC6890)

update user set host='127.0.0.2' where user='foo';flush privileges;
  • Connect using socket: FAILURE
  • Connect from 127.0.0.1: FAILURE

Interestingly:

  • mysql -pbar -ufoo -h127.0.0.2 connects from 127.0.0.1 and is FAILURE
  • mysql -pbar -ufoo -h127.0.0.2 --bind-address=127.0.0.2 is OK

Cleanup

delete from user where user='foo';flush privileges;

Addendum

To see what is actually in the mysql.user table, which is one of the permission tables, use:

SELECT SUBSTR(password,1,6) as password, user, host,
Super_priv AS su,
Grant_priv as gr,
CONCAT(Select_priv, Lock_tables_priv) AS selock,
CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif,
CONCAT(References_priv, Index_priv, Alter_priv) AS ria,
CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views,
CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) AS funcs,
CONCAT(Repl_slave_priv, Repl_client_priv) AS replic,
CONCAT(Shutdown_priv, Process_priv, File_priv, Show_db_priv, Reload_priv, Create_user_priv) AS admin
FROM user ORDER BY user, host;

this gives:

+----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | password | user     | host      | su | gr | selock | modif | ria | views | funcs | replic | admin  |
    +----------+----------+-----------+----+----+--------+-------+-----+-------+-------+--------+--------+
    | *E8D46   | foo      |           | N  | N  | NN     | NNNNN | NNN | NNN   | NNNNN | NN     | NNNNNN |

Similarly for table mysql.db:

SELECT host,db,user, 
       Grant_priv as gr,
       CONCAT(Select_priv, Lock_tables_priv) AS selock, 
       CONCAT(Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv) AS modif, 
       CONCAT(References_priv, Index_priv, Alter_priv) AS ria, 
       CONCAT(Create_tmp_table_priv, Create_view_priv, Show_view_priv) AS views, 
       CONCAT(Create_routine_priv, Alter_routine_priv, Execute_priv) AS funcs 
       FROM db ORDER BY user, db, host;

How to get EditText value and display it on screen through TextView?

Use the following code when clicked on the button :

 String value = edittext.getText().toString().trim(); //get text from editText 
 textView.setText(value); //setText in a textview

Hope to be useful to you.

What's the use of "enum" in Java?

You use an enum instead of a class if the class should have a fixed enumerable number of instances.

Examples:

  • DayOfWeek  = 7 instances ? enum
  • CardSuit    = 4 instances ? enum
  • Singleton  = 1 instance   ? enum

  • Product      = variable number of instances ? class
  • User            = variable number of instances ? class
  • Date            = variable number of instances ? class

When to use in vs ref vs out

Extra notes regarding C# 7:
In C# 7 there's no need to predeclare variables using out. So a code like this:

public void PrintCoordinates(Point p)
{
  int x, y; // have to "predeclare"
  p.GetCoordinates(out x, out y);
  WriteLine($"({x}, {y})");
}

Can be written like this:

public void PrintCoordinates(Point p)
{
  p.GetCoordinates(out int x, out int y);
  WriteLine($"({x}, {y})");
}

Source: What's new in C# 7.

Download JSON object as a file from browser

    downloadJsonFile(data, filename: string){
        // Creating a blob object from non-blob data using the Blob constructor
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        // Create a new anchor element
        const a = document.createElement('a');
        a.href = url;
        a.download = filename || 'download';
        a.click();
        a.remove();
      }

You can easily auto download file with using Blob and transfer it in first param downloadJsonFile. filename is name of file you wanna set.

How and where are Annotations used in Java?

Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can't affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.

This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in orer to work with these Libraries or SDKs.Therefore, it's fair to say Annotations and Reflection work hand-in hand in Java.

We also get to limit the availability of an annotation to either compile-time or runtime.Below is a simple example on creating a custom annotation

Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

    public static void main(String[] args) {
        Class<TestAlpha> obj = TestAlpha.class;
        if (obj.isAnnotationPresent(IssueInfo.class)) {

            Annotation annotation = obj.getAnnotation(IssueInfo.class);
            IssueInfo testerInfo = (IssueInfo) annotation;

            System.out.printf("%nType: %s", testerInfo.type());
            System.out.printf("%nReporter: %s", testerInfo.reporter());
            System.out.printf("%nCreated On: %s%n%n",
                    testerInfo.created());
        }
    }
}

TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {

}

IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Hamzeen. H.
 * @created 10/01/2015
 * 
 * IssueInfo annotation definition
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

    public enum Type {
        BUG, IMPROVEMENT, FEATURE
    }

    Type type() default Type.BUG;

    String reporter() default "Vimesh";

    String created() default "10/01/2015";
}

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert a float number to a whole number in JavaScript?

There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:

intval = floatval - floatval%1;

This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:

> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

Pass array to where in Codeigniter Active Record

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

It's a very late answer but I resolved the issue turning off the lazy loading:

db.Configuration.LazyLoadingEnabled = false;

Adding values to a C# array

To add the list values to string array using C# without using ToArray() method

        List<string> list = new List<string>();
        list.Add("one");
        list.Add("two");
        list.Add("three");
        list.Add("four");
        list.Add("five");
        string[] values = new string[list.Count];//assigning the count for array
        for(int i=0;i<list.Count;i++)
        {
            values[i] = list[i].ToString();
        }

Output of the value array contains:

one

two

three

four

five

Append TimeStamp to a File Name

Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Setting the tz attribute of the index explicitly seems to work:

ts_utc = ts.tz_convert("UTC")
ts_utc.index.tz = None

Read file from resources folder in Spring Boot

if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful

File file = ResourceUtils.getFile("classpath:config/sample.txt")

//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

How do I set the default locale in the JVM?

In the answers here, up to now, we find two ways of changing the JRE locale setting:

  • Programatically, using Locale.setDefault() (which, in my case, was the solution, since I didn't want to require any action of the user):

    Locale.setDefault(new Locale("pt", "BR"));
    
  • Via arguments to the JVM:

    java -jar anApp.jar -Duser.language=pt-BR
    

But, just as reference, I want to note that, on Windows, there is one more way of changing the locale used by the JRE, as documented here: changing the system-wide language.

Note: You must be logged in with an account that has Administrative Privileges.

  1. Click Start > Control Panel.

  2. Windows 7 and Vista: Click Clock, Language and Region > Region and Language.

    Windows XP: Double click the Regional and Language Options icon.

    The Regional and Language Options dialog box appears.

  3. Windows 7: Click the Administrative tab.

    Windows XP and Vista: Click the Advanced tab.

    (If there is no Advanced tab, then you are not logged in with administrative privileges.)

  4. Under the Language for non-Unicode programs section, select the desired language from the drop down menu.

  5. Click OK.

    The system displays a dialog box asking whether to use existing files or to install from the operating system CD. Ensure that you have the CD ready.

  6. Follow the guided instructions to install the files.

  7. Restart the computer after the installation is complete.

Certainly on Linux the JRE also uses the system settings to determine which locale to use, but the instructions to set the system-wide language change from distro to distro.

Angular 4 img src is not found

in your component assign a variable like,

export class AppComponent {
  netImage:any = "../assets/network.jpg";
  title = 'app';
}

use this netImage in your src to get the image, as given below,

<figure class="figure">
  <img [src]="netImage" class="figure-img img-fluid rounded" alt="A generic square placeholder image with rounded corners in a figure.">
  <figcaption class="figure-caption">A caption for the above image.</figcaption>
</figure>

ExecJS and could not find a JavaScript runtime

I installed node via nvm and encountered this issue when deploying with Capistrano. Capistrano didn't load nvm automatically because it runs non-interactively.

To fix, simply move the lines that nvm adds to your ~/.bashrc up to the top. The file will then look something like this:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Just to add to the other options, I was trying to access a nested object within the main object through the dot method as in: this.state.arrayData.CompleteAdress.Location In this case Location is a nested object inside Complete address which is why i cant simply access it with the dot notation.

  • So if you're facing this same issue, try JSON.parse so that you access the nested object and then manipulate accordingly.

PHP function to generate v4 UUID

Use Symfony Polyfill / Uuid
Then you can just generate uuid as native php function:

$uuid = uuid_create(UUID_TYPE_RANDOM);

More about it, read in official Symfony blop post - https://symfony.com/blog/introducing-the-new-symfony-uuid-polyfill

Retrieve CPU usage and memory usage of a single process on Linux?

Launch a program and monitor it

This form is useful if you want to benchmark an executable easily:

topp() (
  $* &>/dev/null &
  pid="$!"
  trap ':' INT
  echo 'CPU  MEM'
  while sleep 1; do ps --no-headers -o '%cpu,%mem' -p "$pid"; done
  kill "$pid"
)
topp ./myprog arg1 arg2

Now when you hit Ctrl + C it exits the program and stops monitoring. Sample output:

CPU  MEM
20.0  1.3
35.0  1.3
40.0  1.3

Related: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

Tested on Ubuntu 16.04.

READ_EXTERNAL_STORAGE permission for Android

http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html

Try changing the line contentResolver.query

//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA}; 
Cursor cursor = contentResolver.query(uri, columns, null, null, null);

public static final String MEDIA_CONTENT_CONTROL

Not for use by third-party applications due to privacy of media consumption

http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL

try to remove the <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/> first and try again?

Simple bubble sort c#

I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.

consider what would happen in this case:

int[] arr = {1,2,3,4,5,6,7,8};

here's something that makes more sense:

int[] arr = {1,2,3,4,5,6,7,8};

int temp = 0;
int loopCount=0;
bool doBreak=true;

for (int write = 0; write < arr.Length; write++)
{
    doBreak=true;
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
            doBreak=false;
        }
        loopCount++;
    }
    if(doBreak){ break; /*early escape*/ }
}

Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");

Count records for every month in a year

Try This query:

SELECT 
  SUM(CASE datepart(month,ARR_DATE) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ARR_DATE) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ARR_DATE) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ARR_DATE) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ARR_DATE) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ARR_DATE) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ARR_DATE) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ARR_DATE) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ARR_DATE) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,ARR_DATE) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,ARR_DATE) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,ARR_DATE) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,ARR_DATE) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    sometable
WHERE
  ARR_DATE BETWEEN '2012/01/01' AND '2012/12/31' 

Getting the object's property name

for direct access a object property by position... generally usefull for property [0]... so it holds info about the further... or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.

Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]

How do I calculate the normal vector of a line segment?

m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1

then

m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line.. 

b is something if you want to pass it from a point you defined

Make elasticsearch only return certain fields?

response_filtering

All REST APIs accept a filter_path parameter that can be used to reduce the response returned by elasticsearch. This parameter takes a comma separated list of filters expressed with the dot notation.

https://stackoverflow.com/a/35647027/844700

Jackson serialization: ignore empty values (or null)

You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

mysql.h file can't be found

The mysql.h file from the libmysqlclient-dev Ubuntu package is located at /usr/include/mysql/mysql.h.

This is not a standard search path for compilers, however /usr/include is.

You'd typically use the mysql.h header in your code like this:

#include <mysql/mysql.h>

If you don't want to specify the directory offset in your source, you can pass the -I flag to gcc (If that's what you are using) to specify an additional include search directory, and then you wouldn't need to change your existing code.

eg.

gcc -I/usr/include/mysql ...

How can I pretty-print JSON in a shell script?

Or, with Ruby:

echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

Jenkins, specifying JAVA_HOME

I just wanted to add a solution for Windows machines.

  • Windows Server 2008 R2 Standard, SP1
  • Jenkins 2.89.4
  • Java version 8.171

Symptom: Jenkins service starts and immediately stops.
Jenkins.wrapper.log has a line indicating the incorrect path to Java:

- Starting C:\Program Files\Java\jre1.8.0_141\bin\java -Xrs -Xmx6g -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "C:\Program Files (x86)\Jenkins\jenkins.war" --httpPort=8080 --webroot="C:\Program Files (x86)\Jenkins\war"

The fix: Jenkins has the path hard-coded in jenkins.xml. Change the path to the new Java location.

<env name="JENKINS_HOME" value="%BASE%"/>
<!--
if you'd like to run Jenkins with a specific version of Java, specify a full path to java.exe.
The following value assumes that you have java in your PATH.
-->
<executable>C:\Program Files\Java\jre1.8.0_171\bin\java</executable>
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8080 --webroot="%BASE%\war"</arguments>

You can also use Windows Environment Variables, but I wasn't successful with that and I don't think the Java installer updates those, so you'd need to update that by hand every time anyway.

<env name="JENKINS_HOME" value="%BASE%"/>
<!--
if you'd like to run Jenkins with a specific version of Java, specify a full path to java.exe.
The following value assumes that you have java in your PATH.
-->
<executable>%JAVA_HOME%\bin\java</executable>
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8080 --webroot="%BASE%\war"</arguments>

Easy pretty printing of floats in python?

First, elements inside a collection print their repr. you should learn about __repr__ and __str__.

This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:

numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)

Android ViewPager with bottom dots

ViewPagerIndicator has not been updated since 2012 and got several bugs that were never fixed.

I finally found an alternative with this light library that displays nice dots for the viewpager, here is the link:

https://github.com/ongakuer/CircleIndicator

Easy to implement!

test if display = none

Try this instead to only select the visible elements under the tbody:

$('tbody :visible').highlight(myArray[i]);

How can I combine multiple rows into a comma-delimited list in Oracle?

I needed a similar thing and found the following solution.

select RTRIM(XMLAGG(XMLELEMENT(e,country_name || ',')).EXTRACT('//text()'),',') country_name from  

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Multiple Inheritance in C#

I created a C# post-compiler that enables this kind of thing:

using NRoles;

public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }

public class RFirst : IFirst, Role {
  public void FirstMethod() { Console.WriteLine("First"); }
}

public class RSecond : ISecond, Role {
  public void SecondMethod() { Console.WriteLine("Second"); }
}

public class FirstAndSecond : Does<RFirst>, Does<RSecond> { }

You can run the post-compiler as a Visual Studio post-build-event:

C:\some_path\nroles-v0.1.0-bin\nutate.exe "$(TargetPath)"

In the same assembly you use it like this:

var fas = new FirstAndSecond();
fas.As<RFirst>().FirstMethod();
fas.As<RSecond>().SecondMethod();

In another assembly you use it like this:

var fas = new FirstAndSecond();
fas.FirstMethod();
fas.SecondMethod();

Javamail Could not convert socket to TLS GMail

Yes, it works for me on localhost:

props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

The error is only thrown on localhost, so you should try on remote servers too. Usually, it is the snippet of code mentioned above that works well without ssl.trust property

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Get random sample from list while maintaining ordering of items?

Apparently random.sample was introduced in python 2.3

so for version under that, we can use shuffle (example for 4 items):

myRange =  range(0,len(mylist)) 
shuffle(myRange)
coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]

PHP decoding and encoding json with unicode characters

Judging from everything you've said, it seems like the original Odómetro string you're dealing with is encoded with ISO 8859-1, not UTF-8.

Here's why I think so:

  • json_encode produced parseable output after you ran the input string through utf8_encode, which converts from ISO 8859-1 to UTF-8.
  • You did say that you got "mangled" output when using print_r after doing utf8_encode, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3 in UTF-8, but that sequence is ó in ISO 8859-1.
  • Your htmlentities hackaround solution worked. htmlentities needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)
  • You said you had the same problem in Python, which would seem to exclude PHP from being the issue.

PHP will use the \uXXXX escaping, but as you noted, this is valid JSON.

So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8' to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode, but this will only support characters that are part of ISO 8859-1).

Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r testing).

Turn a string into a valid filename?

In one line:

valid_file_name = re.sub('[^\w_.)( -]', '', any_string)

you can also put '_' character to make it more readable (in case of replacing slashs, for example)

Polling the keyboard (detect a keypress) in python

Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt 

def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret

How to uninstall with msiexec using product id guid without .msi file present

There's no reason for the {} command not to work. The semi-obvious questions are:

  1. You are sure that the product is actually installed! There's something in ARP/Programs&Features.

  2. The original install is in fact visible in the current context. It looks as if it might have been a per-user install, and if you are logged in as somebody else now then it won't know about it - you'd need to log in under the same account as the original install.

  3. If the \windows\installer directory was damaged the cached file would be missing, and that's used to do the uninstall.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

React Js conditionally applying class attributes

Expending on @spitfire109's fine answer, one could do something like this:

rootClassNames() {
  let names = ['my-default-class'];
  if (this.props.disabled) names.push('text-muted', 'other-class');

  return names.join(' ');
}

and then within the render function:

<div className={this.rootClassNames()}></div>

keeps the jsx short

Browse for a directory in C#

Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.

If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.

The FolderBrowserDialog UI is very minimal:

enter image description here

But you can have this instead:

enter image description here

Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).

using System;
using System.Reflection;
using System.Windows.Forms;

namespace MyCoolCompany.Shuriken {
    /// <summary>
    /// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
    /// </summary>
    public class FolderSelectDialog {
        private string _initialDirectory;
        private string _title;
        private string _fileName = "";

        public string InitialDirectory {
            get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
            set { _initialDirectory = value; }
        }
        public string Title {
            get { return _title ?? "Select a folder"; }
            set { _title = value; }
        }
        public string FileName { get { return _fileName; } }

        public bool Show() { return Show(IntPtr.Zero); }

        /// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
        /// <returns>true if the user clicks OK</returns>
        public bool Show(IntPtr hWndOwner) {
            var result = Environment.OSVersion.Version.Major >= 6
                ? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
                : ShowXpDialog(hWndOwner, InitialDirectory, Title);
            _fileName = result.FileName;
            return result.Result;
        }

        private struct ShowDialogResult {
            public bool Result { get; set; }
            public string FileName { get; set; }
        }

        private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
            var folderBrowserDialog = new FolderBrowserDialog {
                Description = title,
                SelectedPath = initialDirectory,
                ShowNewFolderButton = false
            };
            var dialogResult = new ShowDialogResult();
            if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
                dialogResult.Result = true;
                dialogResult.FileName = folderBrowserDialog.SelectedPath;
            }
            return dialogResult;
        }

        private static class VistaDialog {
            private const string c_foldersFilter = "Folders|\n";

            private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
            private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
            private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
            private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
            private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
            private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
            private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
                .GetType("System.Windows.Forms.FileDialogNative+FOS")
                .GetField("FOS_PICKFOLDERS")
                .GetValue(null);
            private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
                .GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
                .GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
            private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
            private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
            private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");

            public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
                var openFileDialog = new OpenFileDialog {
                    AddExtension = false,
                    CheckFileExists = false,
                    DereferenceLinks = true,
                    Filter = c_foldersFilter,
                    InitialDirectory = initialDirectory,
                    Multiselect = false,
                    Title = title
                };

                var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
                s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
                s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
                var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
                s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);

                try {
                    int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
                    return new ShowDialogResult {
                        Result = retVal == 0,
                        FileName = openFileDialog.FileName
                    };
                }
                finally {
                    s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
                }
            }
        }

        // Wrap an IWin32Window around an IntPtr
        private class WindowWrapper : IWin32Window {
            private readonly IntPtr _handle;
            public WindowWrapper(IntPtr handle) { _handle = handle; }
            public IntPtr Handle { get { return _handle; } }
        }
    }
}

I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog class is so that its static reflection variables don't try to get populated if the Show method is never called.

It is used like so in a Windows Form:

var dialog = new FolderSelectDialog {
    InitialDirectory = musicFolderTextBox.Text,
    Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
    musicFolderTextBox.Text = dialog.FileName;
}

You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.

Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!

Class 'DOMDocument' not found

I'm using CentOS 7 with virtualmin and three PHP versions. I also have REMI repo enabled. it worked for me:

Step 1:

Just append PHP major version number like this php{version number}-xml. And run yum install

yum install php70-php-xml
yum install php71-php-xml
yum install php72-php-xml

Step 2:

Don't forget to restart Apache:

service httpd restart

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Displaying a flash message after redirect in Codeigniter

In Your Controller set this

<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Please check below link for Displaying a flash message after redirect in Codeigniter

Spring Boot JPA - configuring auto reconnect

I just moved to Spring Boot 1.4 and found these properties were renamed:

spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.time-between-eviction-runs-millis=3600000
spring.datasource.dbcp.validation-query=SELECT 1

Prevent jQuery UI dialog from setting focus to first textbox

I had a similar problem and solved it by focusing on the dialog after open:

var $dialog = $("#pnlFiltros")
    .dialog({
        autoOpen: false,
        hide: "puff",                   
        width: dWidth,
        height: 'auto',
        draggable: true,
        resizable: true,
        closeOnScape : true,
        position: [x,y]                    
    });
$dialog.dialog('open');
$("#pnlFiltros").focus(); //focus on the div being dialogued (is that a word?)

But in my case the first element is an anchor, so I don't know if in your case that will leave the datepicker opened.

EDIT: only works on IE

javascript: using a condition in switch case

if the possible values are integers you can bunch up cases. Otherwise, use ifs.

var api, tem;

switch(liCount){
    case 0:
    tem= 'start';
    break;
    case 1: case 2: case 3: case 4: case 5:
    tem= 'upload1Row';
    break;
    case 6: case 7: case 8: case 9: case 10:
    tem= 'upload2Rows';
    break;
    default:
    break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();

How do I script a "yes" response for installing programs?

You just need to put -y with the install command.

For example: yum install <package_to_install> -y

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

INSERT INTO eSSLSmartOfficeSource2.[dbo].DeviceLogs  (DeviceId,UserId,LogDate,UpdateFlag) 
SELECT DL1.DeviceId ,DL1.UserId COLLATE DATABASE_DEFAULT,DL1.LogDate 
,0 FROM eSSLSmartOffice.[dbo].DeviceLogs DL1 
WHERE  NOT EXISTS 
(SELECT DL2.DeviceId ,DL2.UserId COLLATE DATABASE_DEFAULT
,DL2.LogDate ,DL2.UpdateFlag 
FROM eSSLSmartOfficeSource2.[dbo].DeviceLogs DL2    
WHERE  DL1.DeviceId =DL2.DeviceId
 and DL1.UserId collate  Latin1_General_CS_AS=DL2.UserId collate  Latin1_General_CS_AS
  and DL1.LogDate =DL2.LogDate )

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

How to make a class property?

Here's how I would do this:

class ClassPropertyDescriptor(object):

    def __init__(self, fget, fset=None):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        return self.fget.__get__(obj, klass)()

    def __set__(self, obj, value):
        if not self.fset:
            raise AttributeError("can't set attribute")
        type_ = type(obj)
        return self.fset.__get__(obj, type_)(value)

    def setter(self, func):
        if not isinstance(func, (classmethod, staticmethod)):
            func = classmethod(func)
        self.fset = func
        return self

def classproperty(func):
    if not isinstance(func, (classmethod, staticmethod)):
        func = classmethod(func)

    return ClassPropertyDescriptor(func)


class Bar(object):

    _bar = 1

    @classproperty
    def bar(cls):
        return cls._bar

    @bar.setter
    def bar(cls, value):
        cls._bar = value


# test instance instantiation
foo = Bar()
assert foo.bar == 1

baz = Bar()
assert baz.bar == 1

# test static variable
baz.bar = 5
assert foo.bar == 5

# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50

The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.

Adding a metaclass definition solves this:

class ClassPropertyMetaClass(type):
    def __setattr__(self, key, value):
        if key in self.__dict__:
            obj = self.__dict__.get(key)
        if obj and type(obj) is ClassPropertyDescriptor:
            return obj.__set__(self, value)

        return super(ClassPropertyMetaClass, self).__setattr__(key, value)

# and update class define:
#     class Bar(object):
#        __metaclass__ = ClassPropertyMetaClass
#        _bar = 1

# and update ClassPropertyDescriptor.__set__
#    def __set__(self, obj, value):
#       if not self.fset:
#           raise AttributeError("can't set attribute")
#       if inspect.isclass(obj):
#           type_ = obj
#           obj = None
#       else:
#           type_ = type(obj)
#       return self.fset.__get__(obj, type_)(value)

Now all will be fine.

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Stacked Tabs in Bootstrap 3

To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.

https://github.com/dbtek/bootstrap-vertical-tabs

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

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

Select row with most recent date per user

select b.* from 

    (select 
        `lms_attendance`.`user` AS `user`,
        max(`lms_attendance`.`time`) AS `time`
    from `lms_attendance` 
    group by 
        `lms_attendance`.`user`) a

join

    (select * 
    from `lms_attendance` ) b

on a.user = b.user
and a.time = b.time

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."

I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "&ntilde ;"

Alex

Is there a function to round a float in C or do I need to write my own?

Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf().

I think there is another way to do it, though. You can try ceil() and floor() to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil() and floor() only work on doubles though.

EDIT: Also, for floats, you can use truncf() to truncate floats. The same +0.5 trick should work to do accurate rounding.

VS 2017 Git Local Commit DB.lock error on every commit

My automatically generated .gitignore file contained /.vs instead of .vs/. Fixing this typo fixed the problem!

"Debug only" code that should run only when "turned on"

If you want to know whether if debugging, everywhere in program. Use this.

Declare global variable.

bool isDebug=false;

Create function for checking debug mode

[ConditionalAttribute("DEBUG")]
    public static void isDebugging()
    {
        isDebug = true;
    }

In the initialize method call the function

isDebugging();

Now in the entire program. You can check for debugging and do the operations. Hope this Helps!

How can I detect when the mouse leaves the window?

See mouseover and mouseout.

_x000D_
_x000D_
var demo = document.getElementById('demo');_x000D_
document.addEventListener("mouseout", function(e){demo.innerHTML="";});_x000D_
document.addEventListener("mouseover", function(e){demo.innerHTML="";});
_x000D_
div { font-size:80vmin; position:absolute;_x000D_
      left:50%; top:50%; transform:translate(-50%,-50%); }
_x000D_
<div id='demo'></div>
_x000D_
_x000D_
_x000D_

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

How to use a App.config file in WPF applications?

This also works

WpfApplication1.Properties.Settings.Default["appsetting"].ToString()

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

Setting button text via javascript

Use textContent instead of value to set the button text.

Typically the value attribute is used to associate a value with the button when it's submitted as form data.

Note that while it's possible to set the button text with innerHTML, using textContext should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.

JS:

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');  
b.textContent = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Produces this in the DOM:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

Demo: https://jsfiddle.net/13ucp6ob/

Build a basic Python iterator

If you looking for something short and simple, maybe it will be enough for you:

class A(object):
    def __init__(self, l):
        self.data = l

    def __iter__(self):
        return iter(self.data)

example of usage:

In [3]: a = A([2,3,4])

In [4]: [i for i in a]
Out[4]: [2, 3, 4]

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

When the user starts making changes to the form, a boolean flag will be set. If the user then tries to navigate away from the page, you check that flag in the window.onunload event. If the flag is set, you show the message by returning it as a string. Returning the message as a string will popup a confirmation dialog containing your message.

If you are using ajax to commit the changes, you can set the flag to false after the changes have been committed (i.e. in the ajax success event).

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

Absolute Positioning & Text Alignment

Try this:

http://jsfiddle.net/HRz6X/2/

You need to add left: 0 and right: 0 (not supported by IE6). Or specify a width

Create a temporary table in a SELECT statement without a separate CREATE TABLE

In addition to psparrow's answer if you need to add an index to your temporary table do:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

It also works with PRIMARY KEY

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

CSS3 transform: rotate; in IE9

Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:

  -ms-transform: rotate(10deg);

It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.

I can also confirm that the IE-specific filter property has been dropped in IE9.

[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.

But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.

However I have done some independant tests using -ms-transform:rotate() in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.

Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation

[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.

The hack implements support for the standard CSS transform for for old versions of IE. So now you can add the following to your CSS:

-sand-transform: rotate(10deg);

...and have it work in IE 6/7/8, without having to use the filter syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

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

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

jQuery SVG vs. Raphael

Another svg javascript library you might want to look at is d3.js. http://d3js.org/

What JSON library to use in Scala?

Jawn is a very flexible JSON parser library in Scala. It also allows generation of custom ASTs; you just need to supply it with a small trait to map to the AST.

Worked great for a recent project that needed a little bit of JSON parsing.

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

Lazy Method for Reading Big File in Python?

To process line by line, this is an elegant solution:

  def stream_lines(file_name):
    file = open(file_name)
    while True:
      line = file.readline()
      if not line:
        file.close()
        break
      yield line

As long as there're no blank lines.

Show / hide div on click with CSS

Although a bit unstandard, a possible solution is to contain the content you want to show/hide inside the <a> so it can be reachable through CSS:

http://jsfiddle.net/Jdrdh/2/

_x000D_
_x000D_
a .hidden {_x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
a:visited .hidden {_x000D_
  visibility: visible;_x000D_
}
_x000D_
<div id="container">_x000D_
  <a href="#">_x000D_
        A_x000D_
        <div class="hidden">hidden content</div>_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

changing textbox border colour using javascript

If the users enter an incorrect value, apply a 1px red color border to the input field:

document.getElementById('fName').style.border ="1px solid red";

If the user enters a correct value, remove the border from the input field:

document.getElementById('fName').style.border ="";

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

Where can I find php.ini?

For SAPI: php-fpm

There is no need to create a php.info file (it is not a good policy to leave it for the world to read anyway). On the command line:

php-fpm -i | more

Somewhere in its output, it will show this line:

Configuration File (php.ini) Path => /etc

Here is a more complete explanation: https://www.cloudinsidr.com/content/how-to-figure-out-your-php-configuration-parameters-without-info-php/

How to convert hex strings to byte values in Java

You can try something similar to this :

String s = "65";

byte value = Byte.valueOf(s);

Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

Had the same issue and in my case it was a problem with a vs code extension. Try running code as:

$ code --disable-extensions

Once in the editor, I ran my program in the debug mode and worked, and then started code with

$ code

And it continued working fine.

Hope it works for you.

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

How to rename JSON key

As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,

_x000D_
_x000D_
var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}];_x000D_
    _x000D_
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));_x000D_
_x000D_
document.write(JSON.stringify(json));
_x000D_
_x000D_
_x000D_

This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

What exactly is OAuth (Open Authorization)?

OAuth is a protocol that is used from Resource Owner(facebook, google, tweeter, microsoft live and so on) to provide a needed information, or to provide a permission for write success to third party system(your site for example). Most likely without OAuth protocol the credentials should be available for the third part systems which will be inappropriate way of communication between those systems.

IIS7 folder permissions for web application

  1. Working on IIS 7.5 and Windows 7 i couldnt give permission APPPOOL/Mypool
  2. IUSR and IIS_IUSRS permissions not working for me
  3. I got to problem this way:

    -Created console application with C#
    -This appliaction using createeventsource like this

    if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);

    -Build solution and get .exe file

    -Run exe as administator.This create log file.

NOTE: Dont remember Event viewer must be refresh for see the log.

I hope this solution helps someone :)

Python - difference between two strings

What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj and zlib.decompressobj with the zdict parameter set to your "base word", e.g. afrykanerskojezyczny.

Caveats are zdict is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.

How do I add to the Windows PATH variable using setx? Having weird problems

This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:

If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
    CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
    WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True

Advantages of this approach:

1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.

Wait 5 seconds before executing next line

using angularjs:

$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

webpack command not working

The quickest way, just to get this working is to use the web pack from another location, this will stop you having to install it globally or if npm run webpack fails.

When you install webpack with npm it goes inside the "node_modules\.bin" folder of your project.

in command prompt (as administrator)

  1. go to the location of the project where your webpack.config.js is located.
  2. in command prompt write the following
"C:\Users\..\ProjectName\node_modules\.bin\webpack" --config webpack.config.vendor.js

Input jQuery get old value before onchange and get value after on change

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

File content into unix variable with newlines

The assignment does not remove the newline characters, it's actually the echo doing this. You need simply put quotes around the string to maintain those newlines:

echo "$testvar"

This will give the result you want. See the following transcript for a demo:

pax> cat num1.txt ; x=$(cat num1.txt)
line 1
line 2

pax> echo $x ; echo '===' ; echo "$x"
line 1 line 2
===
line 1
line 2

The reason why newlines are replaced with spaces is not entirely to do with the echo command, rather it's a combination of things.

When given a command line, bash splits it into words according to the documentation for the IFS variable:

IFS: The Internal Field Separator that is used for word splitting after expansion ... the default value is <space><tab><newline>.

That specifies that, by default, any of those three characters can be used to split your command into individual words. After that, the word separators are gone, all you have left is a list of words.

Combine that with the echo documentation (a bash internal command), and you'll see why the spaces are output:

echo [-neE] [arg ...]: Output the args, separated by spaces, followed by a newline.

When you use echo "$x", it forces the entire x variable to be a single word according to bash, hence it's not split. You can see that with:

pax> function count {
...>    echo $#
...> }
pax> count 1 2 3
3
pax> count a b c d
4
pax> count $x
4
pax> count "$x"
1

Here, the count function simply prints out the number of arguments given. The 1 2 3 and a b c d variants show it in action.

Then we try it with the two variations on the x variable. The one without quotes shows that there are four words, "test", "1", "test" and "2". Adding the quotes makes it one single word "test 1\ntest 2".

How to select records from last 24 hours using SQL?

In Oracle (For last 24 hours):

SELECT  *
FROM    my_table
WHERE   date_column >= SYSDATE - 24/24

In case, for any reason, you have rows with future dates, you can use between, like this:

SELECT  *
FROM    my_table
WHERE   date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

Creating an empty bitmap and drawing though canvas in Android

Do not use Bitmap.Config.ARGB_8888

Instead use int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.

How to make div go behind another div?

http://jsfiddle.net/f2znvn4f/


HTML

<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>

CSS

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}

The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

Calling a JavaScript function named in a variable

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

eval(variable + '();');

Standard dry-code warning applies.

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

How to create a density plot in matplotlib?

Option 1:

Use pandas dataframe plot (built on top of matplotlib):

import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()

enter image description here

Option 2:

Use distplot of seaborn:

import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)

enter image description here

List of all unique characters in a string?

Store Unique characters in list

Method 1:

uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']

Method 2: By Loop ( Complex )

uniue_char = []
for c in 'aaabcabccd':
    if not c in uniue_char:
        uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']

Show two digits after decimal point in c++

cout << fixed << setprecision(2) << total;

setprecision specifies the minimum precision. So

cout << setprecision (2) << 1.2; 

will print 1.2

fixed says that there will be a fixed number of decimal digits after the decimal point

cout << setprecision (2) << fixed << 1.2;

will print 1.20

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

How to check if a string "StartsWith" another string?

  1. The question is a bit old, but I wanted to write this answer to show you some benchmarks I made based on all the answers provided here and the jsperf shared by Jim Buck.

I basically needed a fast way to find if a long needle is within a long haystack and they are very similar except for the last characters.

Here's the code I have written which for each function (splice, substring, startsWith, etc.) tests both when they return false and true against a haystack string (nestedString) of 1.000.0001 characters and a falsy or truthy needle string of 1.000.000 chars (testParentStringFalse and testParentStringTrue, respectively):

// nestedString is made of 1.000.001 '1' repeated characters.
var nestedString = '...'

// testParentStringFalse is made of 1.000.000 characters,
// all characters are repeated '1', but the last one is '2',
// so for this string the test should return false.
var testParentStringFalse = '...'

// testParentStringTrue is made of 1.000.000 '1' repeated characters,
// so for this string the test should return true.
var testParentStringTrue = '...'

// You can make these very long strings by running the following bash command
// and edit each one as needed in your editor
// (NOTE: on OS X, `pbcopy` copies the string to the clipboard buffer,
//        on Linux, you would probably need to replace it with `xclip`):
// 
//     printf '1%.0s' {1..1000000} | pbcopy
// 

function testString() {
    let dateStart
    let dateEnd
    let avg
    let count = 100000
    const falseResults = []
    const trueResults = []

    /* slice */
    console.log('========> slice')
    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.slice(0, testParentStringFalse.length) === testParentStringFalse
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    falseResults[falseResults.length] = {
        label: 'slice',
        avg
    }
    console.log(`testString() slice = false`, res, 'avg: ' + avg + 'ms')

    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.slice(0, testParentStringTrue.length) === testParentStringTrue
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    trueResults[trueResults.length] = {
        label: 'slice',
        avg
    }
    console.log(`testString() slice = true`, res, 'avg: ' + avg + 'ms')
    console.log('<======== slice')
    console.log('')
    /* slice END */

    /* lastIndexOf */
    console.log('========> lastIndexOf')
    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.lastIndexOf(testParentStringFalse, 0) === 0
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    falseResults[falseResults.length] = {
        label: 'lastIndexOf',
        avg
    }
    console.log(`testString() lastIndexOf = false`, res, 'avg: ' + avg + 'ms')

    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.lastIndexOf(testParentStringTrue, 0) === 0
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    trueResults[trueResults.length] = {
        label: 'lastIndexOf',
        avg
    }
    console.log(`testString() lastIndexOf = true`, res, 'avg: ' + avg + 'ms')
    console.log('<======== lastIndexOf')
    console.log('')
    /* lastIndexOf END */

    /* indexOf */
    console.log('========> indexOf')
    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.indexOf(testParentStringFalse) === 0
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    falseResults[falseResults.length] = {
        label: 'indexOf',
        avg
    }
    console.log(`testString() indexOf = false`, res, 'avg: ' + avg + 'ms')

    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.indexOf(testParentStringTrue) === 0
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    trueResults[trueResults.length] = {
        label: 'indexOf',
        avg
    }
    console.log(`testString() indexOf = true`, res, 'avg: ' + avg + 'ms')
    console.log('<======== indexOf')
    console.log('')
    /* indexOf END */

    /* substring */
    console.log('========> substring')
    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.substring(0, testParentStringFalse.length) === testParentStringFalse
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    falseResults[falseResults.length] = {
        label: 'substring',
        avg
    }
    console.log(`testString() substring = false`, res, 'avg: ' + avg + 'ms')

    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.substring(0, testParentStringTrue.length) === testParentStringTrue
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    trueResults[trueResults.length] = {
        label: 'substring',
        avg
    }
    console.log(`testString() substring = true`, res, 'avg: ' + avg + 'ms')
    console.log('<======== substring')
    console.log('')
    /* substring END */

    /* startsWith */
    console.log('========> startsWith')
    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.startsWith(testParentStringFalse)
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    falseResults[falseResults.length] = {
        label: 'startsWith',
        avg
    }
    console.log(`testString() startsWith = false`, res, 'avg: ' + avg + 'ms')

    dateStart = +new Date()
    var res
    for (let j = 0; j < count; j++) {
        res = nestedString.startsWith(testParentStringTrue)
    }
    dateEnd = +new Date()
    avg = (dateEnd - dateStart)/count
    trueResults[trueResults.length] = {
        label: 'startsWith',
        avg
    }
    console.log(`testString() startsWith = true`, res, 'avg: ' + avg + 'ms')
    console.log('<======== startsWith')
    console.log('')
    /* startsWith END */

    falseResults.sort((a, b) => a.avg - b.avg)
    trueResults.sort((a, b) => a.avg - b.avg)

    console.log('false results from fastest to slowest avg:', falseResults)
    console.log('true results from fastest to slowest avg:', trueResults)
}

I runned this benchmark test on Chrome 75, Firefox 67, Safari 12 and Opera 62.

I haven't included Edge and IE because I do not have them on this machine, but if someone of you wants to run the script against Edge and at least IE 9 and share the output here I would be very curious to see the results.

Just remember that you need to recreate the 3 long strings and save the script in a file which you then open in your browser as copy/paste on the browser's console will block it as each string's length is >= 1.000.000).

Here are the outputs:

Chrome 75 (substring wins):

false results from fastest to slowest avg:
1)  {"label":"substring","avg":0.08271}
2)  {"label":"slice","avg":0.08615}
3)  {"label":"lastIndexOf","avg":0.77025}
4)  {"label":"indexOf","avg":1.64375}
5)  {"label":"startsWith","avg":3.5454}

true results from fastest to slowest avg:
1)  {"label":"substring","avg":0.08213}
2)  {"label":"slice","avg":0.08342}
3)  {"label":"lastIndexOf","avg":0.7831}
4)  {"label":"indexOf","avg":0.88988}
5)  {"label":"startsWith","avg":3.55448}

Firefox 67 (indexOf wins):

false results from fastest to slowest avg
1)  {"label":"indexOf","avg":0.1807}
2)  {"label":"startsWith","avg":0.74621}
3)  {"label":"substring","avg":0.74898}
4)  {"label":"slice","avg":0.78584}
5)  {"label":"lastIndexOf","avg":0.79668}

true results from fastest to slowest avg:
1)  {"label":"indexOf","avg":0.09528}
2)  {"label":"substring","avg":0.75468}
3)  {"label":"startsWith","avg":0.76717}
4)  {"label":"slice","avg":0.77222}
5)  {"label":"lastIndexOf","avg":0.80527}

Safari 12 (slice wins for false results, startsWith wins for true results, also Safari is the fastest in terms of total time to to execute the whole test):

false results from fastest to slowest avg:
1) "{\"label\":\"slice\",\"avg\":0.0362}"
2) "{\"label\":\"startsWith\",\"avg\":0.1141}"
3) "{\"label\":\"lastIndexOf\",\"avg\":0.11512}"
4) "{\"label\":\"substring\",\"avg\":0.14751}"
5) "{\"label\":\"indexOf\",\"avg\":0.23109}"

true results from fastest to slowest avg:
1) "{\"label\":\"startsWith\",\"avg\":0.11207}"
2) "{\"label\":\"lastIndexOf\",\"avg\":0.12196}"
3) "{\"label\":\"substring\",\"avg\":0.12495}"
4) "{\"label\":\"indexOf\",\"avg\":0.33667}"
5) "{\"label\":\"slice\",\"avg\":0.49923}"

Opera 62 (substring wins. Results are similar to Chrome and I am not surprised as Opera is based on Chromium and Blink):

false results from fastest to slowest avg:
{"label":"substring","avg":0.09321}
{"label":"slice","avg":0.09463}
{"label":"lastIndexOf","avg":0.95347}
{"label":"indexOf","avg":1.6337}
{"label":"startsWith","avg":3.61454}

true results from fastest to slowest avg:
1)  {"label":"substring","avg":0.08855}
2)  {"label":"slice","avg":0.12227}
3)  {"label":"indexOf","avg":0.79914}
4)  {"label":"lastIndexOf","avg":1.05086}
5)  {"label":"startsWith","avg":3.70808}

It turns out every browser has its own implementation details (apart Opera, which is based on Chrome's Chromium and Blink).

Of course, further test with different use cases could and should be performed (e.g. when needle is really short compared to haystack, when haystack is shorter than needle, etc...), but in my case I needed to compare very long strings and wanted to share it here.

How can I set a css border on one side only?

You can specify border separately for all borders, for example:

#testdiv{
  border-left: 1px solid #000;
  border-right: 2px solid #FF0;
}

You can also specify the look of the border, and use separate style for the top, right, bottom and left borders. for example:

#testdiv{
  border: 1px #000;
  border-style: none solid none solid;
}

Change private static final field using Java reflection

Even in spite of being final a field can be modified outside of static initializer and (at least JVM HotSpot) will execute the bytecode perfectly fine.

The problem is that Java compiler does not allow this, but this can be easily bypassed using objectweb.asm. Here is p?e?r?f?e?c?t?l?y? ?v?a?l?i?d? ?c?l?a?s?s?f?i?l?e? an invalid classfile from the JVMS specification standpoint, but it passes bytecode verification and then is successfully loaded and initialized under JVM HotSpot OpenJDK12:

ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Cl", null, "java/lang/Object", null);
{
    FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "fld", "I", null, null);
    fv.visitEnd();
}
{
    // public void setFinalField1() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField1", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_5);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
{
    // public void setFinalField2() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField2", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
cw.visitEnd();

In Java, the class looks roughly speaking as follows:

public class Cl{
    private static final int fld;

    public static void setFinalField1(){
        fld = 5;
    }

    public static void setFinalField2(){
        fld = 2;
    }
}

which cannot be compiled with javac, but can be loaded and executed by JVM.

JVM HotSpot has special treatment of such classes in the sense that it prevents such "constants" from participating in constant folding. This check is done on the bytecode rewriting phase of class initialization:

// Check if any final field of the class given as parameter is modified
// outside of initializer methods of the class. Fields that are modified
// are marked with a flag. For marked fields, the compilers do not perform
// constant folding (as the field can be changed after initialization).
//
// The check is performed after verification and only if verification has
// succeeded. Therefore, the class is guaranteed to be well-formed.
InstanceKlass* klass = method->method_holder();
u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);
constantPoolHandle cp(method->constants());
Symbol* ref_class_name = cp->klass_name_at(cp->klass_ref_index_at(bc_index));
if (klass->name() == ref_class_name) {
   Symbol* field_name = cp->name_ref_at(bc_index);
   Symbol* field_sig = cp->signature_ref_at(bc_index);

   fieldDescriptor fd;
   if (klass->find_field(field_name, field_sig, &fd) != NULL) {
      if (fd.access_flags().is_final()) {
         if (fd.access_flags().is_static()) {
            if (!method->is_static_initializer()) {
               fd.set_has_initialized_final_update(true);
            }
          } else {
            if (!method->is_object_initializer()) {
              fd.set_has_initialized_final_update(true);
            }
          }
        }
      }
    }
}

The only restriction that JVM HotSpot checks is that the final field should not be modified outside of the class that the final field is declared at.

How does the stack work in assembly language?

You are correct that a stack is a data structure. Often, data structures (stacks included) you work with are abstract and exist as a representation in memory.

The stack you are working with in this case has a more material existence- it maps directly to real physical registers in the processor. As a data structure, stacks are FILO (first in, last out) structures that ensure data is removed in the reverse order it was entered. See the StackOverflow logo for a visual! ;)

You are working with the instruction stack. This is the stack of actual instructions you are feeding the processor.

ListBox with ItemTemplate (and ScrollBar!)

Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)

-pom-

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

In my case the same problem was caused because I forgot to add > at the end of my hidden input field, like so: <input type="hidden" name="_token" value="{{ Session::token() }}"

So, I fixed it by adding it:

<input type="hidden" name="_token" value="{{ Session::token() }}">

Constraint Layout Vertical Align Center

It's possible to set the center aligned view as an anchor for other views. In the example below "@+id/stat_2" centered horizontally in parent and it serves as an anchor for other views in this layout.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/stat_1"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="10"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/divider_1" />

    <TextView
        android:id="@+id/stat_detail_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Streak"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_1"
        app:layout_constraintStart_toStartOf="@+id/stat_1"
        app:layout_constraintEnd_toEndOf="@+id/stat_1" />

    <View
        android:id="@+id/divider_1"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginEnd="16dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/stat_2"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2" />

    <TextView
        android:id="@+id/stat_2"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="1"
        android:text="243"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

    <TextView
        android:id="@+id/stat_detail_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Calories Burned"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_2"
        app:layout_constraintStart_toStartOf="@+id/stat_2"
        app:layout_constraintEnd_toEndOf="@+id/stat_2" />

    <View
        android:id="@+id/divider_2"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:background="#ccc"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2"
        app:layout_constraintStart_toEndOf="@+id/stat_2"
        app:layout_constraintTop_toTopOf="@+id/stat_2" />

    <TextView
        android:id="@+id/stat_3"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="3200"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintStart_toEndOf="@+id/divider_2" />

    <TextView
        android:id="@+id/stat_detail_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Steps"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_3"
        app:layout_constraintStart_toStartOf="@+id/stat_3"
        app:layout_constraintEnd_toEndOf="@+id/stat_3" />

</android.support.constraint.ConstraintLayout>

Here's how it works on smallest smartphone (3.7 480x800 Nexus One) vs largest smartphone (5.5 1440x2560 Pixel XL)

Result view

Flattening a shallow list in Python

In Python 2.6, using chain.from_iterable():

>>> from itertools import chain
>>> list(chain.from_iterable(mi.image_set.all() for mi in h.get_image_menu()))

It avoids creating of intermediate list.

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

What's the proper way to install pip, virtualenv, and distribute for Python?

Python 3.4 onward

Python 3.3 adds the venv module, and Python 3.4 adds the ensurepip module. This makes bootstrapping pip as easy as:

python -m ensurepip

Perhaps preceded by a call to venv to do so inside a virtual environment.

Guaranteed pip is described in PEP 453.

Selection with .loc in python

This is using dataframes from the pandas package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html

So the index part specifies a subset of the rows to pull out, and the (optional) column_name specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'

'heroku' does not appear to be a git repository

I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create and heroku git push master again. Of course you must have done git init, as mentioned in StickMaNX answer above, already before the heroku steps.

How to pop an alert message box using PHP?

See this example :

<?php
echo "<div id='div1'>text</div>"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#div1').click(function () {
                alert('I clicked');
            });
        });
</script>
</head>
<body>

</body>
</html>

Regex matching beginning AND end strings

Well, the simple regex is this:

/^dbo\..*_fn$/

It would be better, however, to use the string manipulation functionality of whatever programming language you're using to slice off the first four and the last three characters of the string and check whether they're what you want.

How to compare two date values with jQuery

Once you are able to parse those strings into a Date object comparing them is easy (Using the < operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.

Callback after all asynchronous forEach callbacks are completed

Hope this will fix your problem, i usually work with this when i need to execute forEach with asynchronous tasks inside.

foo = [a,b,c,d];
waiting = foo.length;
foo.forEach(function(entry){
      doAsynchronousFunction(entry,finish) //call finish after each entry
}
function finish(){
      waiting--;
      if (waiting==0) {
          //do your Job intended to be done after forEach is completed
      } 
}

with

function doAsynchronousFunction(entry,callback){
       //asynchronousjob with entry
       callback();
}

Spring 3 RequestMapping: Get path value

Building upon Fabien Kruba's already excellent answer, I thought it would be nice if the ** portion of the URL could be given as a parameter to the controller method via an annotation, in a way which was similar to @RequestParam and @PathVariable, rather than always using a utility method which explicitly required the HttpServletRequest. So here's an example of how that might be implemented. Hopefully someone finds it useful.

Create the annotation, along with the argument resolver:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WildcardParam {

    class Resolver implements HandlerMethodArgumentResolver {

        @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
            return methodParameter.getParameterAnnotation(WildcardParam.class) != null;
        }

        @Override
        public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
            HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
            return request == null ? null : new AntPathMatcher().extractPathWithinPattern(
                    (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
                    (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
        }

    }

}

Register the method argument resolver:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new WildcardParam.Resolver());
    }

}

Use the annotation in your controller handler methods to have easy access to the ** portion of the URL:

@RestController
public class SomeController {

    @GetMapping("/**")
    public void someHandlerMethod(@WildcardParam String wildcardParam) {
        // use wildcardParam here...
    }

}

Show just the current branch in Git

With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current.

See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis).
(Merged by Junio C Hamano -- gitster -- in commit 3710f60, 07 Mar 2019)

branch: introduce --show-current display option

When called with --show-current, git branch will print the current branch name and terminate.
Only the actual name gets printed, without refs/heads.
In detached HEAD state, nothing is output.

Intended both for scripting and interactive/informative use.
Unlike git branch --list, no filtering is needed to just get the branch name.

See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.

jQuery ID starts with

try:

$("td[id^=" + value + "]")

C Programming: How to read the whole file contents into a buffer

A portable solution could use getc.

#include <stdio.h>

char buffer[MAX_FILE_SIZE];
size_t i;

for (i = 0; i < MAX_FILE_SIZE; ++i)
{
    int c = getc(fp);

    if (c == EOF)
    {
        buffer[i] = 0x00;
        break;
    }

    buffer[i] = c;
}

If you don't want to have a MAX_FILE_SIZE macro or if it is a big number (such that buffer would be to big to fit on the stack), use dynamic allocation.

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

c# dictionary one key many values

Use a dictionary of lists (or another type of collection), for example:

var myDictionary = new Dictionary<string, IList<int>>();

myDictionary["My key"] = new List<int> {1, 2, 3, 4, 5};

Getting input values from text box

// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention

function submit()
{
    var userPass = document.getElementById("pass").value;
    var userName = document.getElementById("user").value;
    this.pass = userPass;
    this.name = userName; 
    alert("whatever you want to display"); 
}

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

To check online you can use

http://codebeautify.org/base64-to-image-converter

You can convert string to image like this way

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

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

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

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

How to get all options of a select using jQuery?

$("#id option").each(function()
{
    $(this).prop('selected', true);
});

Although, the CORRECT way is to set the DOM property of the element, like so:

$("#id option").each(function(){
    $(this).attr('selected', true);
});

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:

 var stopPolling;
 var doIframePolling;
 $scope.showIframe = true;
 doIframePolling = $interval(function () {
    if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = true;
    }
},400);

stopPolling = $timeout(function () {
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = false;     
},5000);

 $scope.$on("$destroy",function() {
        $timeout.cancel(stopPolling);
        $interval.cancel(doIframePolling);
 });

Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.

Integer division: How do you produce a double?

double num = 5;

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

How can I execute a PHP function in a form action?

You can put the username() function in another page, and send the form to that page...

Node / Express: EADDRINUSE, Address already in use - Kill server

Kill only node process that uses given PORT. As others mentioned, in bash you could use kill $(lsof -t -i:PORT)

Here is a Windows solution (there's a way!): netstat -bona | findstr ".0:PORT +0.0.0.0:0 +LISTENING" | for /f "tokens=5" %t in ('more') do taskkill /PID:%t /F. You need an elevated terminal for that (in VSCode you'll need to open itself with elevation, as integrated terminal cannot be elevated).

PS: if findstr not available, you can simply use find and replace " +" for spaces (non regex mode)

How to keep the spaces at the end and/or at the beginning of a String?

use "" with the string resource value.

Example :

<string>"value with spaces"</string>

OR

use \u0020 code for spaces.

The type or namespace name could not be found

Other problem that might be causing such behavior are build configurations.

I had two projects with configurations set to be built to specific folders. Like Debug and Any CPU and in second it was Debug and x86.

What I did I went to Solution->Context menu->Properties->Configuration properties->Configuration and I set all my projects to use same configurations Debug and x86 and also checked Build tick mark.

Then projects started to build correctly and were able to see namespaces.

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

Merge DLL into EXE?

I Found The Solution Below are the Stpes:-

  1. Download ILMerge.msi and Install it on your Machine.
  2. Open Command Prompt
  3. type cd C:\Program Files (x86)\Microsoft\ILMerge Preess Enter
  4. C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName.dll

For Multiple Dll :-

C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName1.dll DllName2.dll DllName3.dll

npm throws error without sudo

In my case,it's because of the permission of ~/tmp.So I do:

sudo chown -R $USER ~/tmp

And it's OK!

How do I force detach Screen from another SSH session?

try with screen -d -r or screen -D -RR

Post multipart request with Android SDK

More easy, light (32k), and many more performance:

Android Asynchronous Http Client library: http://loopj.com/android-async-http/

Implementation:

How to send a “multipart/form-data” POST in Android with Volley

dispatch_after - GCD in Swift?

I use dispatch_after so often that I wrote a top-level utility function to make the syntax simpler:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

And now you can talk like this:

delay(0.4) {
    // do stuff
}

Wow, a language where you can improve the language. What could be better?


Update for Swift 3, Xcode 8 Seed 6

Seems almost not worth bothering with, now that they've improved the calling syntax:

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

Set up Python 3 build system with Sublime Text 3

Steps to Make Sublime Text a Python IDE (Windows)

Tested successfully on Sublime Text 3. Assuming Sublime Text and package control are already installed . . .

  1. Install Python (python.org) and pay attention to where it is installed or choose a simple location like the C drive, agreeing to remove character limit at the end of the installation.

  2. Install package SublimeREPL (Cntrl + Shift + P, Package Control - Install Package, SublimeREPL, Enter).

  3. Go to Preferences, Package Settings, SublimeREPL, Settings - User.

  4. Paste in the following, updating the file path to your python installation folder, as needed. You may customize these and choose whatever syntax you like (last line) but I prefer my output in plain text.

    {
      "default_extend_env": {"PATH":"C:\\Program Files\\Python36\\"},
      "repl_view_settings": {
      "translate_tabs_to_spaces": false,
      "auto_indent": false,
      "smart_indent": false,
      "spell_check": false,
      "indent_subsequent_lines": false,
      "detect_indentation": false,
      "auto_complete": true,
      "line_numbers": false,
      "gutter": false,
      "syntax": "Packages/Text/Plain text.tmLanguage"
      }
    }
    
  5. Save and close the file (SublimeREPL.sublime-settings).

  6. Go to Tools, Build System, New Build System.

  7. Replace all existing text with the following:

    {
    "target": "run_existing_window_command", 
    "id": "repl_python_run",
    "file": "config/Python/Main.sublime-menu"
    }
    
  8. Cntrl + S or save as "C:\Users[username]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL-python.sublime-build" updating username or path as needed. This should be wherever your settings and builds are stored by Sublime Text.

  9. Go to Tools, Build System, select SublimeREPL-python.

  10. All done--now to test. Open or create a simple python file, having a *.py extension and save it wherever desired.

  11. Make sure the file is open and selected in Sublime Text. Now, when you press Cntrl + B to build and run it, it will open another tab, titled "REPL [python]", executing and displaying the results of your python code.

If you would like to go a step further, I highly recommend making the follow changes, to allow Sublime to reload your executed python in the same window, when you press Cntrl+B (Build), instead of it opening a new tab each time:

Add the following line in the "repl_python_run" command in (Preferences, Browse Packages) SublimeREPL\config\Python\Main.sublime-menu, right before the "external_id": "python" argument:

"view_id": "*REPL* [python]",

and then to change the line:

if view.id() == view_id

into:

if view.name() == view_id

in SublimeREPL\sublimerepl.py.

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I face the same problem and changing

 $cfg['Servers'][$i]['host'] = 'localhost';

to

 $cfg['Servers'][$i]['host'] = '127.0.0.1';

Solved this issue.

What is the difference between vmalloc and kmalloc?

One of other differences is kmalloc will return logical address (else you specify GPF_HIGHMEM). Logical addresses are placed in "low memory" (in the first gigabyte of physical memory) and are mapped directly to physical addresses (use __pa macro to convert it). This property implies kmalloced memory is continuous memory.

In other hand, Vmalloc is able to return virtual addresses from "high memory". These addresses cannot be converted in physical addresses in a direct fashion (you have to use virt_to_page function).

How to test if a file is a directory in a batch script?

Can't we just test with this :

IF [%~x1] == [] ECHO Directory

It seems to work for me.

Eclipse: Enable autocomplete / content assist

For me, it helped after I changed the theme to 'mac' since I am running on a MacOSX.

Eclipse: >Preferences > General > Appearance > Choose 'Mac' from the menu.

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How can I use numpy.correlate to do autocorrelation?

As I just ran into the same problem, I would like to share a few lines of code with you. In fact there are several rather similar posts about autocorrelation in stackoverflow by now. If you define the autocorrelation as a(x, L) = sum(k=0,N-L-1)((xk-xbar)*(x(k+L)-xbar))/sum(k=0,N-1)((xk-xbar)**2) [this is the definition given in IDL's a_correlate function and it agrees with what I see in answer 2 of question #12269834], then the following seems to give the correct results:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0.,6.12,0.01)
y = np.sin(x)
# y = np.random.uniform(size=300)
yunbiased = y-np.mean(y)
ynorm = np.sum(yunbiased**2)
acor = np.correlate(yunbiased, yunbiased, "same")/ynorm
# use only second half
acor = acor[len(acor)/2:]

plt.plot(acor)
plt.show()

As you see I have tested this with a sin curve and a uniform random distribution, and both results look like I would expect them. Note that I used mode="same" instead of mode="full" as the others did.

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

HTML img tag: title attribute vs. alt attribute?

They are used for different things. The alt attribute is used instead of the image. If the image can't be shown, and in screen readers.

The title attribute is shown along with the image, typically as a hover tooltip.

One should not be used "instead" of the other. Each should be used properly, to do the things they were designed to do.

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

In my case, I messed up the connectionString property in a publish profile, trying to access the wrong database (Initial Catalog). Entity Framework then complains that the entities do not match the database, and rightly so.

Find files containing a given text

egrep -ir --include=*.{php,html,js} "(document.cookie|setcookie)" .

The r flag means to search recursively (search subdirectories). The i flag means case insensitive.

If you just want file names add the l (lowercase L) flag:

egrep -lir --include=*.{php,html,js} "(document.cookie|setcookie)" .

Javascript date regex DD/MM/YYYY

This validates date like dd-mm-yyyy

([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)([0-9][0-9][0-9][0-9])

This can use with javascript like angular reactive forms

How to replace a string in a SQL Server Table Column

You also can replace large text for email template at run time, here is an simple example for that.

DECLARE @xml NVARCHAR(MAX)
SET @xml = CAST((SELECT [column] AS 'td','',        
        ,[StartDate] AS 'td'
         FROM [table] 
         FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
select REPLACE((EmailTemplate), '[@xml]', @xml) as Newtemplate 
FROM [dbo].[template] where id = 1

Java HTML Parsing

The HTMLParser project (http://htmlparser.sourceforge.net/) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:

Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter = 
    new CssSelectorNodeFilter("DIV.targetClassName");
NodeList nodes = parser.parse(cssFilter);

Circular gradient in android

I guess you should add android:centerColor

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="#FFFFFF"
  android:centerColor="#000000"
  android:endColor="#FFFFFF"
  android:angle="0" />
</shape>

This example displays a horizontal gradient from white to black to white.

document.getElementById replacement in angular4 / typescript?

  element: HTMLElement;

  constructor() {}

  fakeClick(){
    this.element = document.getElementById('ButtonX') as HTMLElement;
    this.element.click();
  }

How to insert TIMESTAMP into my MySQL table?

In addition to checking your table setup to confirm that the field is set to NOT NULL with a default of CURRENT_TIMESTAMP, you can insert date/time values from PHP by writing them in a string format compatible with MySQL.

 $timestamp = date("Y-m-d H:i:s");

This will give you the current date and time in a string format that you can insert into MySQL.

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Bash: Echoing a echo command with a variable in bash

You just need to use single quotes:

$ echo "$TEST"
test
$ echo '$TEST'
$TEST

Inside single quotes special characters are not special any more, they are just normal characters.

Android : change button text and background color

Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:

<MaterialButton
  app:backgroundTint="@color/my_color"
  android:textColor="@android:color/white"/>

echo key and value of an array without and with loop

How to echo key and value of an array without and with loop

$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];

Shell script current directory?

The current(initial) directory of shell script is the directory from which you have called the script.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

Slide up/down effect with ng-show and ng-animate

This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

.foo {
    max-height: 0;
}

.foo--open {
    max-height: 1000px; /* some arbitrary big value */
    transition: ...
}

see this fiddle by the excellent Lea Verou

As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

In Python, how do I convert all of the items in a list to floats?

import numpy as np
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', 
'0.55', '0.55', '0.54']
print(type(my_list), type(my_list[0]))   
# <class 'list'> <class 'str'>

which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:

    my_list = np.array(my_list).astype(np.float)

    print(type(my_list), type(my_list[0]))  
    # <class 'numpy.ndarray'> <class 'numpy.float64'>

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

What does the "map" method do in Ruby?

Using ruby 2.4 you can do the same thing using transform_values, this feature extracted from rails to ruby.

h = {a: 1, b: 2, c: 3}

h.transform_values { |v| v * 10 }
 #=> {a: 10, b: 20, c: 30}

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

Android: why is there no maxHeight for a View?

if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/topview"
    android:layout_below="@+id/bottomview" >

SoapUI "failed to load url" error when loading WSDL

Inside the wsdl file look for the import element, which looks like this :

`<import  namespace="nameSpaceValue" location="Users/myname/.../targetxsdName.xsd"/>`

Change the location attribute in the above element to the location of your xsd files stored locally, and it should work.

Rails filtering array of objects by attribute value

You can filter using where

Job.includes(:attachments).where(file_type: ["logo", "image"])

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

Animation fade in and out

FOR FADE add this first line with your animation's object.

.animate().alpha(1).setDuration(2000);

FOR EXAMPLEI USED LottieAnimation

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

Determine whether a key is present in a dictionary

In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.

>>> dis.dis(indict)
  2           0 LOAD_GLOBAL              0 (name)
              3 LOAD_GLOBAL              1 (d)
              6 COMPARE_OP               6 (in)
              9 POP_TOP             


>>> dis.dis(haskey)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_ATTR                1 (haskey)
              6 LOAD_GLOBAL              2 (name)
              9 CALL_FUNCTION            1
             12 POP_TOP             

My feelings are that in is much more readable and is to be preferred in every case that I can think of.

In terms of performance, the timing reflects the opcode

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
 10000000 loops, best of 3: 0.11 usec per loop

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
  1000000 loops, best of 3: 0.205 usec per loop

in is almost twice as fast.

How to completely uninstall Android Studio on Mac?

Run the following commands in the terminal:

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  

To delete all projects:

rm -Rf ~/AndroidStudioProjects