Programs & Examples On #Jsr172

JSR 172 - J2ME Web Services API specification

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

"Cannot instantiate the type..."

Queue is an Interface not a class.

Input type number "only numeric value" validation

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

Do not want scientific notation on plot axis

You can use the axis() command for that, eg :

x <- 1:100000
y <- 1:100000
marks <- c(0,20000,40000,60000,80000,100000)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=marks)

gives :

enter image description here

EDIT : if you want to have all of them in the same format, you can use the solution of @Richie to get them :

x <- 1:100000
y <- 1:100000
format(y,scientific=FALSE)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=format(marks,scientific=FALSE))

How can I tail a log file in Python?

Another option is the tailhead library that provides both Python versions of of tail and head utilities and API that can be used in your own module.

Originally based on the tailer module, its main advantage is the ability to follow files by path i.e. it can handle situation when file is recreated. Besides, it has some bug fixes for various edge cases.

What is the difference between parseInt() and Number()?

Because none mentioned, when using Number and parseInt with numeric separator, they also behave differently:

const num1 = 5_0; // 50
const num2 = Number(5_0); // 50
const num3 = Number("5_0"); // NaN
const num4 = parseInt(5_0); // 50
const num5 = parseInt("5_0"); // 5

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

How to fix .pch file missing on build?

I was searching for the iOS PCH file having the same problem, if you got here like me too, the solution that I've found is by clearing derived data; Close Simulator(s), go to xCode prefs -> locations -> go to the derived data file path, close xCode, delete the files in the derived data folder, re launch and cheers :)

Why does javascript map function return undefined?

var arr = ['a','b',1];
 var results = arr.filter(function(item){
                if(typeof item ==='string'){return item;}  
               });

What is a daemon thread in Java?

In Java, Daemon Threads are one of the types of the thread which does not prevent Java Virtual Machine (JVM) from exiting. The main purpose of a daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

What is the difference between mocking and spying when using Mockito?

[Test double types]

Mock vs Spy

Mock is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null

Spy is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it

class A {
    String foo1() {
        foo2();
        return "RealString_1";
    }

    String foo2() {
        return "RealString_2";
    }

    void foo3() { foo4(); }

    void foo4() { }
}
@Test
public void testMockA() {
    //given
    A mockA = Mockito.mock(A.class);
    Mockito.when(mockA.foo1()).thenReturn("MockedString");

    //when
    String result1 = mockA.foo1();
    String result2 = mockA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals(null, result2);

    //Case 2
    //when
    mockA.foo3();

    //then
    verify(mockA).foo3();
    verify(mockA, never()).foo4();
}

@Test
public void testSpyA() {
    //given
    A spyA = Mockito.spy(new A());

    Mockito.when(spyA.foo1()).thenReturn("MockedString");

    //when
    String result1 = spyA.foo1();
    String result2 = spyA.foo2();

    //then
    assertEquals("MockedString", result1);
    assertEquals("RealString_2", result2);

    //Case 2
    //when
    spyA.foo3();

    //then
    verify(spyA).foo3();
    verify(spyA).foo4();
}

Creating an instance using the class name and calling constructor

If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.

How can I rename a single column in a table at select?

if you are using sql server, use brackets or single quotes around alias name in a query you have in code.

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

cmd line rename file with date and time

Digging up the old thread because all solutions have missed the simplest fix...

It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.

The simplest solution is to just surround the desired filename in quotes "filename".

Then you can have any date pattern you want (with the exception of those illegal characters such as /,\,...)

I would suggest reverse date order YYYYMMDD-HHMM:

ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I found another solution here, since I ran into both post...

This is from the Myles answer:

<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem"> 
        <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> 
    </Style> 
</ListBox.ItemContainerStyle> 

This worked for me.

How to disassemble a memory range with GDB?

You can force gcc to output directly to assembly code by adding the -S switch

gcc -S hello.c

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls ? more latency time ? decreased application/database performance.

However, ORMs have options to avoid this problem, mainly using JOINs.

how to set default method argument values?

You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Neither the question nor the answers really fit my simple way of thinking about it. I'm a consultant and have synchronized these definitions with a number of Dev teams and DevOps people, but am curious about how it matches with the industry at large:

Basically I think of the agile practice of continuous delivery like a continuum:

Not continuous (everything manual) 0% ----> 100% Continuous Delivery of Value (everything automated)

Steps towards continuous delivery:

Zero. Nothing is automated when devs check in code... You're lucky if they have compiled, run, or performed any testing prior to check-in.

  1. Continuous Build: automated build on every check-in, which is the first step, but does nothing to prove functional integration of new code.

  2. Continuous Integration (CI): automated build and execution of at least unit tests to prove integration of new code with existing code, but preferably integration tests (end-to-end).

  3. Continuous Deployment (CD): automated deployment when code passes CI at least into a test environment, preferably into higher environments when quality is proven either via CI or by marking a lower environment as PASSED after manual testing. I.E., testing may be manual in some cases, but promoting to next environment is automatic.

  4. Continuous Delivery: automated publication and release of the system into production. This is CD into production plus any other configuration changes like setup for A/B testing, notification to users of new features, notifying support of new version and change notes, etc.

EDIT: I would like to point out that there's a difference between the concept of "continuous delivery" as referenced in the first principle of the Agile Manifesto (http://agilemanifesto.org/principles.html) and the practice of Continuous Delivery, as seems to be referenced by the context of the question. The principle of continuous delivery is that of striving to reduce the Inventory waste as described in Lean thinking (http://www.miconleansixsigma.com/8-wastes.html). The practice of Continuous Delivery (CD) by agile teams has emerged in the many years since the Agile Manifesto was written in 2001. This agile practice directly addresses the principle, although they are different things and apparently easily confused.

pull access denied repository does not exist or may require docker login

Try this in your docker-compose.yml file

image: php:rc-zts-alpine

How can I do an UPDATE statement with JOIN in SQL Server?

Another example why SQL isn't really portable.

For MySQL it would be:

update ud, sale
set ud.assid = sale.assid
where sale.udid = ud.id;

For more info read multiple table update: http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

How to check whether input value is integer or float?

Also:

(value % 1) == 0

would work!

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

How to enable curl in Wamp server

Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

Parameter "stratify" from method "train_test_split" (scikit Learn)

Try running this code, it "just works":

from sklearn import cross_validation, datasets 

iris = datasets.load_iris()

X = iris.data[:,:2]
y = iris.target

x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)

y_test

array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
       1, 2, 1, 1, 0, 2, 1])

Creating NSData from NSString in Swift

// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)

// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")

var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!

Generating a random password in php

Here's my take at random plain password generation helper.

It ensures that password has numbers, upper and lower case letters as well as a minimum of 3 special characters.

Length of the password will be between 11 and 30.

function plainPassword(): string
{
    $numbers = array_rand(range(0, 9), rand(3, 9));
    $uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
    $lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
    $special = array_rand(array_flip(['@', '#', '$', '!', '%', '*', '?', '&']), rand(3, 5));

    $password = array_merge(
        $numbers,
        $uppercase,
        $lowercase,
        $special
    );

    shuffle($password);

    return implode($password);
}

How to run vbs as administrator from vbs?

fun lil batch file

@set E=ECHO &set S=SET &set CS=CScript //T:3 //nologo %~n0.vbs /REALTIME^>nul^& timeout 1 /NOBREAK^>nul^& del /Q %~n0.vbs&CLS
@%E%off&color 4a&title %~n0&%S%CX=CLS^&EXIT&%S%BS=^>%~n0.vbs&%S%G=GOTO &%S%H=shell&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    %G%2
) ELSE (
    if not "%minimized%"=="" %G%1
)
%S%minimized=true & start /min cmd /C "%~dpnx0"&%CX%
:1
%E%%S%%H%=CreateObject("%H%.Application"):%H%.%H%Execute "%~dpnx0",,"%CD%", "runas", 1:%S%%H%=nothing%BS%&%CS%&%CX%
:2
%E%%~dpnx0 fvcLing admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"& timeout 3 /NOBREAK>nul
:3
%E%x=msgbox("end of line" ,48, "%~n0")%BS%&%CS%&%CX%

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.

I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.

How to have multiple CSS transitions on an element?

Here's a LESS mixin for transitioning two properties at once:

.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
 -webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
    -moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
      -o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
          transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}

Is Visual Studio Community a 30 day trial?

I'm using Visual Studio Professional licensed over the MAPS Action Pack subscription. Since the new version of the Microsoft Partner Center one have to add the subscribed user to the partner benefit software.

Partner Center->Benefits->Visual Studio Subscriptions->Add user

After that one have to sign out and reenter the credentials in the account settings of VS.

Vertically align text next to an image?

<!DOCTYPE html>
<html>
<head>
<style>
 .block-system-branding-block {
 flex: 0 1 40%;
}
@media screen and (min-width: 48em) {
.block-system-branding-block {
flex: 0 1 420px;
margin: 2.5rem 0;
text-align: left;
}
}
.flex-containerrow {
display: flex;
}
.flex-containerrow > div {
  justify-content: center;
align-items: center;
  }
 .flex-containercolumn {
display: flex;
flex-direction: column;
}
.flex-containercolumn > div {
  width: 300px;
 margin: 10px;
 text-align: left;
 line-height: 20px;
 font-size: 16px;
}
.flex-containercolumn  > site-slogan {font-size: 12px;}
.flex-containercolumn > div > span{ font-size: 12px;}
</style>
</head>
<body>
<div id="block-umami-branding" class="block-system block- 
system-branding-block">
  <div class="flex-containerrow">
 <div>
  <a href="/" rel="home" class="site-logo">
  <img src="https://placehold.it/120x120" alt="Home">
</a>
</div><div class="flex-containerrow"><div class="flex-containercolumn">
  <div class="site-name ">
    <a href="/" title="Home" rel="home">This is my sitename</a>
   </div>
    <div class="site-slogan "><span>Department of Test | Ministry of Test | 
 TGoII</span></div>
 </div></div>
</div>
 </div>
</body>
</html>

How to send a model in jQuery $.ajax() post request to MVC controller method

I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

Have a look at the doc here.. Ajax serialize

OSX - How to auto Close Terminal window after the "exit" command executed.

I've been using

quit -n terminal

at the end of my scripts. You have to have the terminal set to never prompt in preferences

So Terminal > Preferences > Settings > Shell When the shell exits Close the window Prompt before closing Never

Match groups in Python

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.search(pattern, statement) in a variable (let's all it match) in order to both check if it's not None and then re-use it within the body of the condition:

if match := re.search('I love (\w+)', statement):
  print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
  print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
  print(f'Il aime {match.group(1)}')

How to make java delay for a few seconds?

move the System.out statement to finally block.

No connection string named 'MyEntities' could be found in the application config file

If you have multiple projects in solution, then setUp project as started where you have your truth App.config.

Stop embedded youtube iframe?

For a Twitter Bootstrap modal/popup with a video inside, this worked for me:

_x000D_
_x000D_
$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {_x000D_
  $('.video-to-stop', this).each(function() {_x000D_
    this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div id="vid" class="modal stop-video-on-close"_x000D_
  tabindex="-1" role="dialog" aria-labelledby="Title">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">_x000D_
          <span aria-hidden="true">&times;</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title">Title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
       <iframe class="video-to-stop center-block"_x000D_
        src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"_x000D_
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"_x000D_
        frameborder="0" allowfullscreen>_x000D_
       </iframe>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button class="btn btn-danger waves-effect waves-light"_x000D_
          data-dismiss="modal" type="button">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<button class="btn btn-success" data-toggle="modal"_x000D_
 data-target="#vid" type="button">Open video modal</button>
_x000D_
_x000D_
_x000D_

Based on Marco's answer, notice that I just needed to add the enablejsapi=1 parameter to the video URL (rel=0 is just for not displaying related videos at the end). The JS postMessage function is what does all the heavy lifting, it actually stops the video.

The snippet may not display the video due to request permissions, but in a regular browser this should work as of November of 2018.

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

Eclipse change project files location

You can copy your .classpath and .project files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).

Once you find the htaccess file add the following line:

  1. Header set Access-Control-Allow-Origin "*" Just to see if it works. Warning: Do not use this line on a production server

It should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.

  1. Once you do have the above working change the * to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.

How can I manually set an Angular form field as invalid?

For unit test:

spyOn(component.form, 'valid').and.returnValue(true);

How to redirect cin and cout to files?

If your input file is in.txt, you can use freopen to set stdin file as in.txt

freopen("in.txt","r",stdin);

if you want to do the same with your output:

freopen("out.txt","w",stdout);

this will work for std::cin (if using c++), printf, etc...

This will also help you in debugging your code in clion, vscode

Delete with Join in MySQL

Single Table Delete:

In order to delete entries from posts table:

DELETE ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from projects table:

DELETE pj 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from clients table:

DELETE C
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

Multiple Tables Delete:

In order to delete entries from multiple tables out of the joined results you need to specify the table names after DELETE as comma separated list:

Suppose you want to delete entries from all the three tables (posts,projects,clients) for a particular client :

DELETE C,pj,ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I had this exact same problem with a site (Kentico CMS), starting development in 4.5, finding out the production server only supports 4.0, tried going back down to target framework of 4.0. Compiling the other posts in this thread (specifically changing target framework to .Net 4 and .Net 4.5 still being referenced). I searched through my solution and found that a handful of the NuGet packages were still using libraries with targetFramework="net45".

packages.config (before):
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AutoMapper" version="3.1.0" targetFramework="net45" />
  <package id="EntityFramework" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.0.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>

I changed the projects target framework back to 4.5, removed all NuGet libraries, went back down to 4.0 and re-added the libraries (had to use some previous versions that were not dependent on 4.5).

packages.config (after):
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AutoMapper" version="3.1.1" targetFramework="net40" />
  <package id="EntityFramework" version="6.0.2" targetFramework="net40" />
  <package id="Microsoft.AspNet.WebApi.Client" version="4.0.30506.0" targetFramework="net40" />
  <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net40" />
  <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40" />
</packages>

Using Html.ActionLink to call action on different controller

You're hitting the wrong the overload of ActionLink. Try this instead.

<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>

Swift double to string

I would prefer NSNumber and NumberFormatter approach (where need), also u can use extension to avoid bloating code

extension Double {

   var toString: String {
      return NSNumber(value: self).stringValue
   }

}

U can also need reverse approach

extension String {

    var toDouble: Double {
        return Double(self) ?? .nan
    }

}

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

How can I programmatically check whether a keyboard is present in iOS app?

To check weather keyboard is appeared, we can use the Keyboard predefined notifications.

UIKeyboardDidShowNotification ,UIKeyboardDidHideNotification

For example I can use the following code to listen the keyboard notification

// Listen for keyboard appearances and disappearances

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardDidHide:)
                                             name:UIKeyboardDidHideNotification
                                           object:nil];

in the methods I can get notifications

- (void)keyboardDidShow: (NSNotification *) notifyKeyBoardShow{
    // key board is closed
}

- (void)keyboardDidHide: (NSNotification *) notifyKeyBoardHide{
    // key board is opened
}

Fatal error: Class 'ZipArchive' not found in

I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :

sudo apt-get install php7.2-zip

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

For your example, you'd add this:

interface JQuery{
    printArea():void;
}

Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

What exactly is LLVM?

The LLVM Compiler Infrastructure is particularly useful for performing optimizations and transformations on code. It also consists of a number of tools serving distinct usages. llvm-prof is a profiling tool that allows you to do profiling of execution in order to identify program hotspots. Opt is an optimization tool that offers various optimization passes (dead code elimination for instance).

Importantly LLVM provides you with the libraries, to write your own Passes. For instance if you require to add a range check on certain arguments that are passed into certain functions of a Program, writing a simple LLVM Pass would suffice.

For more information on writing your own Pass, check this http://llvm.org/docs/WritingAnLLVMPass.html

CSS: Hover one element, effect for multiple elements?

You don't need JavaScript for this.

Some CSS would do it. Here is an example:

_x000D_
_x000D_
<html>_x000D_
  <style type="text/css">_x000D_
    .section { background:#ccc; }_x000D_
    .layer { background:#ddd; }_x000D_
    .section:hover img { border:2px solid #333; }_x000D_
    .section:hover .layer { border:2px solid #F90; }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
  <div class="section">_x000D_
    <img src="myImage.jpg" />_x000D_
    <div class="layer">Lorem Ipsum</div>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Image library for Python 3

Christoph Gohlke managed to build PIL (for Windows only) for python versions up to 3.3: http://www.lfd.uci.edu/~gohlke/pythonlibs/

I tried his version of PIL with Python 3.2, and image open/create/pixel manipulation/save all work.

Is there a way to iterate over a range of integers?

If you want to just iterate over a range w/o using and indices or anything else, this code sample worked just fine for me. No extra declaration needed, no _. Haven't checked the performance, though.

for range [N]int{} {
    // Body...
}

P.S. The very first day in GoLang. Please, do critique if it's a wrong approach.

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

JavaScript: Passing parameters to a callback function

If you want something slightly more general, you can use the arguments variable like so:

function tryMe (param1, param2) {
    alert(param1 + " and " + param2);
}

function callbackTester (callback) {
    callback (arguments[1], arguments[2]);
}

callbackTester (tryMe, "hello", "goodbye");

But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)

Intel's HAXM equivalent for AMD on Windows OS

From the Android docs (March 2016):

Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer's BIOS and are frequently turned off by default. Check the documentation for your system's motherboard to find out how to enable virtualization extensions.

Most people talk about Genymotion being faster, and I have never heard anyone say it's slower. I definitely think it's faster, and it will be worth the ~20 minutes it will take to set up just to try it.

How do I merge a git tag onto a branch

You mean this?

git checkout destination_branch
git merge tag_name

What does "make oldconfig" do exactly in the Linux kernel makefile?

It reads the existing .config file that was used for an old kernel and prompts the user for options in the current kernel source that are not found in the file. This is useful when taking an existing configuration and moving it to a new kernel.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I'm pretty sure that this issue can have multiple causes — both on server and on client sides.

Recently I faced it with a website I'm hosting on VPS (Ubuntu 18.04, PHP 7.4 FPM, nginx + certbot, site is powered by WordPress) — admin pages were loaded without CSS/JS.

It took me few hours to try different solutions, none of which helped.

Finally, I discovered, that for some reason (probably it was changed by me earlier, but also I can't exclude possibility it was like this by default) in my /etc/nginx/nginx.conf a first line of this file was commented:

# user www-data

I uncommented it, restarted nginx with sudo service nginx restart, and the issue was gone.

If anyone can check on pristine Ubuntu 18.04 with nginx installed if this line is commented by default — please put it in comments.

Having trouble setting working directory

This may help... use the following code and browse the folder you want to set as the working folder

setwd(choose.dir())

Passing data to components in vue.js

I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.

1) Reference data in Vue Instance as an external object (data : dataObj)

2) Then in the data return function in the child component just return parentScope = dataObj and voila. Now you cann do things like {{ parentScope.prop }} and will work like a charm.

Good Luck!

How do you use colspan and rowspan in HTML tables?

If anyone is looking for a rowspan on both the left AND on the right, here is how you can do it:

_x000D_
_x000D_
table { _x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="2">LEFT</td>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
        <td rowspan="2">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Alternatively, if you want to add the LEFT and RIGHT to an existing rowset, you can achieve the same result by throwing them in with a collapsed colspan in between:

_x000D_
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
    padding: 20px; _x000D_
    border: 1px solid black; _x000D_
    text-align: center;_x000D_
}
_x000D_
<table>_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td rowspan="3">LEFT</td>_x000D_
        <td colspan="4" style="padding: 0; border-bottom: solid 1px transparent;"></td>_x000D_
        <td rowspan="3">RIGHT</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 1 </td>_x000D_
        <td> 2 </td>_x000D_
        <td> 3 </td>_x000D_
        <td> 4 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> 5 </td>_x000D_
        <td> 6 </td>_x000D_
        <td> 7 </td>_x000D_
        <td> 8 </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
        <td> - </td>_x000D_
    </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Tensorflow import error: No module named 'tensorflow'

Since none of the above solve my issue, I will post my solution

WARNING: if you just installed TensorFlow using conda, you have to restart your command prompt!

Solution: restart terminal ENTIRELY and restart conda environment

How to list the properties of a JavaScript object?

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var keys = Object.keys(myObject);

The above has a full polyfill but a simplified version is:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

jQuery event for images loaded

Use of the jQuery $().load() as an IMG event handler isn't guaranteed. If the image loads from the cache, some browsers may not fire off the event. In the case of (older?) versions of Safari, if you changed the SRC property of an IMG element to the same value, the onload event will NOT fire.

It appears that this is recognized in the latest jQuery (1.4.x) - http://api.jquery.com/load-event - to quote:

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.

There is a plug-in now to recognize this case and IE's "complete" property for IMG element load states: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

Can't accept license agreement Android SDK Platform 24

Mike's answer works.But need to put the generated license under C:\Users\user\AppData\Local\Android\sdk\licenses.

Python add item to the tuple

From tuple to list to tuple :

a = ('2',)
b = 'b'

l = list(a)
l.append(b)

tuple(l)

Or with a longer list of items to append

a = ('2',)
items = ['o', 'k', 'd', 'o']

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

gives you

>>> 
('2', 'o', 'k', 'd', 'o')

The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You can't change a tuple. So you have to create a new one.

How can I pad an integer with zeros on the left?

You can use Google Guava:

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Sample code:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Note:

Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Ref: GuavaExplained

How to parse a query string into a NameValueCollection in .NET

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}

How to check if there exists a process with a given pid in Python?

In Python 3.3+, you could use exception names instead of errno constants. Posix version:

import os

def pid_exists(pid): 
    if pid < 0: return False #NOTE: pid == 0 returns True
    try:
        os.kill(pid, 0) 
    except ProcessLookupError: # errno.ESRCH
        return False # No such process
    except PermissionError: # errno.EPERM
        return True # Operation not permitted (i.e., process exists)
    else:
        return True # no error, we can send a signal to the process

jQuery Screen Resolution Height Adjustment

Here is an example on how to center an object vertically with jQuery:

var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2  + 'px');

But you could easily change that to whatever your needs are.

How to find topmost view controller on iOS

Previous answer does not seems to handle cases where rootController are UITabBarController or UINavigationController.

Here is the function in swift which works for those cases :

func getCurrentView() -> UIViewController?
{
    if let window = UIApplication.sharedApplication().keyWindow, var currentView: UIViewController = window.rootViewController
    {
        while (currentView.presentedViewController != nil)
        {
            if let presented = currentView.presentedViewController
            {
                currentView = presented
            }
        }

        if currentView is UITabBarController
        {
            if let visible = (currentView as! UITabBarController).selectedViewController
            {
                currentView = visible;
            }
        }

        if currentView is UINavigationController
        {
            if let visible = (currentView as! UINavigationController).visibleViewController
            {
                currentView = visible;
            }
        }

        return currentView
    }

    return nil
}

Accidentally committed .idea directory files into git

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Remove it from repository

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Remove a file from a Git repository without deleting it from the local filesystem

Send the change to others

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

Summary

The full process would look like this:

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

JavaScript - document.getElementByID with onClick

Sometimes JavaScript is not activated. Try something like:

<!DOCTYPE html>
<html>
  <head>

    <script type="text/javascript"> <!--
      function jActivator() {
        document.getElementById("demo").onclick = function() {myFunction()};
        document.getElementById("demo1").addEventListener("click", myFunction);
        }
      function myFunction( s ) {
        document.getElementById("myresult").innerHTML = s;
        }
    // --> </script>
    <noscript>JavaScript deactivated.</noscript>
    <style type="text/css">
    </style>
  </head>
  <body onload="jActivator()">
    <ul>
      <li id="demo">Click me -&gt; onclick.</li>
      <li id="demo1">Click me -&gt; click event.</li>
      <li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
    </ul>
    <div id="myresult">&nbsp;</div>
  </body>
</html>

If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '

How can I install pip on Windows?

There is also an issue with pip on 64 bit Cygwin. After installation, the output of pip command is always empty, no matters what commands/options do you use (even pip -V doesn't produce any output).

If it's your case, just install the development version of Cygwin's package libuuid called libuuid-devel. Without that package using of libuuid causes a segfault. And pip uses that package, so the segfault is the cause of an empty output of pip on Cygwin x64. On 32 bit Cygwin it's working fine even without that package.

You can read some details there: https://github.com/kennethreitz/requests/issues/1547

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

Appending a line to a file only if it does not already exist

This would be a clean, readable and reusable solution using grep and echo to add a line to a file only if it doesn't already exist:

LINE='include "/configs/projectname.conf"'
FILE='lighttpd.conf'
grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"

If you need to match the whole line use grep -xqF

Add -s to ignore errors when the file does not exist, creating a new file with just that line.

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

Inside the simple_html_dom.php change the value of the $offset variable from -1 to 0. this error usually happens when you migrate to PHP 7.

HtmlDomParser::file_get_html uses a default offset of -1, passing in 0 should fix your problem.

How to redirect back to form with input - Laravel 5

I handle validation exceptions in Laravel 5.3 like this. If you use Laravel Collective it will automatically display errors next to inputs and if you use laracasts/flash it will also show first validation error as a notice.


Handler.php render:

public function render($request, Exception $e)
{
    if ($e instanceof \Illuminate\Validation\ValidationException) {
        return $this->handleValidationException($request, $e);
    }

    (..)
}

And the function:

protected function handleValidationException($request, $e)
    {
        $errors = @$e->validator->errors()->toArray();
        $message = null;
        if (count($errors)) {
            $firstKey = array_keys($errors)[0];
            $message = @$e->validator->errors()->get($firstKey)[0];
            if (strlen($message) == 0) {
                $message = "An error has occurred when trying to register";
            }
        }

        if ($message == null) {
            $message = "An unknown error has occured";
        }

        \Flash::error($message);

        return \Illuminate\Support\Facades\Redirect::back()->withErrors($e->validator)->withInput();
    }

Set Locale programmatically

 /**
 * Requests the system to update the list of system locales.
 * Note that the system looks halted for a while during the Locale migration,
 * so the caller need to take care of it.
 */
public static void updateLocales(LocaleList locales) {
    try {
        final IActivityManager am = ActivityManager.getService();
        final Configuration config = am.getConfiguration();

        config.setLocales(locales);
        config.userSetLocale = true;

        am.updatePersistentConfiguration(config);
    } catch (RemoteException e) {
        // Intentionally left blank
    }
}

How to manually trigger validation with jQuery validate?

Eva M from above, almost had the answer as posted above (Thanks Eva M!):

var validator = $( "#myform" ).validate();
validator.form();

This is almost the answer, but it causes problems, in even the most up to date jquery validation plugin as of 13 DEC 2018. The problem is that if one directly copies that sample, and EVER calls ".validate()" more than once, the focus/key processing of the validation can get broken, and the validation may not show errors properly.

Here is how to use Eva M's answer, and ensure those focus/key/error-hiding issues do not occur:

1) Save your validator to a variable/global.

var oValidator = $("#myform").validate();

2) DO NOT call $("#myform").validate() EVER again.

If you call $("#myform").validate() more than once, it may cause focus/key/error-hiding issues.

3) Use the variable/global and call form.

var bIsValid = oValidator.form();

Allowed memory size of X bytes exhausted

This problem is happend because of php.ini defined limit was exided but have lot's of solution for this but simple one is to find your local servers folder and on that find the php folder and in that folder have php.ini file which have all declaration of these type setups. You just need to find one and change that value. But in this situation have one big problem once you change in your localhost file but what about server when you want to put your site on server it again produce same problem and you again follow the same for server. But you also know about .htaccess file this is one of the best and single place to do a lot's of things without changing core files. Like you change www routing, removing .php or other extentions from url or add one. Same like that you also difine default values of php.ini here like this - First you need to open the .htaccess file from your root directory or if you don't have this file so create one on root directory of your site and paste this code on it -

php_value upload_max_filesize 1000M
php_value post_max_size 99500M
php_value memory_limit 500M
php_value max_execution_time 300

after changes if you want to check the changes just run the php code

<?php phpinfo(); ?> 

it will show you the php cofigrations all details. So you find your changes.

Note: for defining unlimited just add -1 like php_value memory_limit -1 It's not good and most of the time slow down your server. But if you like to be limit less then this one option is also fit for you. If after refresh your page changes will not reflect you must restart your local server once for changes.

Good Luck. Hope it will help. Want to download the .htaccess file click this.

must appear in the GROUP BY clause or be used in an aggregate function

The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).

However, there is a workaround: make the required field aggregated as well. In posgres, this should work:

SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

ImportError: No module named 'bottle' - PyCharm

pycharm 2019.3 ,my solution is below: enter image description here

C# Interfaces. Implicit implementation versus Explicit implementation

In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.

Here's an example:

public abstract class StringList : IEnumerable<string>
{
    private string[] _list = new string[] {"foo", "bar", "baz"};

    // ...

    #region IEnumerable<string> Members
    public IEnumerator<string> GetEnumerator()
    {
        foreach (string s in _list)
        { yield return s; }
    }
    #endregion

    #region IEnumerable Members
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    #endregion
}

Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.

ie.

StringList sl = new StringList();

// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();

PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

Handling back button in Android Navigation Component

Newest Update - April 25th, 2019

New release androidx.activity ver. 1.0.0-alpha07 brings some changes

More explanations in android official guide: Provide custom back navigation

Example:

public class MyFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // This callback will only be called when MyFragment is at least Started.
        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
            @Override
            public void handleOnBackPressed() {
                // Handle the back button event
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

        // The callback can be enabled or disabled here or in handleOnBackPressed()
    }
    ...
}

Old Updates

UPD: April 3rd, 2019

Now its simplified. More info here

Example:

requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);

@Override
public boolean handleOnBackPressed() {
    //Do your job here
    //use next line if you just need navigate up
    //NavHostFragment.findNavController(this).navigateUp(); 
    //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
    return true;
    }

Deprecated (since Version 1.0.0-alpha06 April 3rd, 2019) :

Since this, it can be implemented just using JetPack implementation OnBackPressedCallback in your fragment and add it to activity: getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);

Your fragment should looks like this:

public MyFragment extends Fragment implements OnBackPressedCallback {

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
    
    @Override
    public boolean handleOnBackPressed() {
        //Do your job here
        //use next line if you just need navigate up
        //NavHostFragment.findNavController(this).navigateUp(); 
        //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().removeOnBackPressedCallback(this);
    }
}

UPD: Your activity should extends AppCompatActivityor FragmentActivity and in Gradle file:

 implementation 'androidx.appcompat:appcompat:{lastVersion}'

Open soft keyboard programmatically

Based on above answers like this it works in KOTLIN as long as you have the context.

fun Context.showKeyboard(editText: EditText) {

    editText.requestFocus()
    editText.setSelection(editText.text.length)

    GlobalScope.launch {
        delay(200L)

        val inputMethodManager: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInputFromWindow(
            editText.applicationWindowToken,
            InputMethodManager.SHOW_IMPLICIT, 0
        )
    }
}

Then you can call it in your fragment for example as follows

requireContext().showKeyboard(binding.myEditText)

How to fix a header on scroll

Just building on Rich's answer, which uses offset.

I modified this as follows:

  • There was no need for the var $sticky in Rich's example, it wasn't doing anything
  • I've moved the offset check into a separate function, and called it on document ready as well as on scroll so if the page refreshes with the scroll half-way down the page, it resizes straight-away without having to wait for a scroll trigger

    jQuery(document).ready(function($){
        var offset = $( "#header" ).offset();
        checkOffset();
    
        $(window).scroll(function() {
            checkOffset();
        });
    
        function checkOffset() {
            if ( $(document).scrollTop() > offset.top){
                $('#header').addClass('fixed');
            } else {
                $('#header').removeClass('fixed');
            } 
        }
    
    });
    

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

How to highlight text using javascript

Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.

function styleSelected() {
  bg = document.createElement("span");
  bg.style.backgroundColor = "yellow";
  window.getSelection().getRangeAt(0).surroundContents(bg);
}

How to handle ListView click in Android

Use setOnItemClickListener() api in your activity. Following is the sample.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

@Override
public void onItemClick(AdapterView<> parent, View view, int position, long id)
{
     // your code here.
}

});

How can I get the sha1 hash of a string in node.js?

You can use:

  const sha1 = require('sha1');
  const crypt = sha1('Text');
  console.log(crypt);

For install:

  sudo npm install -g sha1
  npm install sha1 --save

What is the correct way to start a mongod service on linux / OS X?

On macOS 10.13.6 with MongoDB 4.0

I was unable to connect to localhost from the mongo shell

I started MongoDB with:

mongod --config /usr/local/etc/mongod.conf

I found that the 'mongod.conf' had:

bindIp: 127.0.0.1

Change my JavaScript connection from localhost to 127.0.0.1 and it worked fine.

The same was occurring with MongoDB Compass too.

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

Empty an array in Java / processing

There's

Arrays.fill(myArray, null);

Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.

This of course doesn't allow you to resize the array (to zero), if that's what you meant by "empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List type like an ArrayList which can have variable size.

IIS - 401.3 - Unauthorized

Just in case anyone else runs into this. I troubleshooted all of these steps and it turns out because I unzipped some files from a MAC, Microsoft automatically without any notification Encrypted the files. After hours of trying to set folder permissions I went in and saw the file names were green which means the files were encrypted and IIS will throw the same error even if folder permissions are correct.

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

How to compare two double values in Java?

Basically you shouldn't do exact comparisons, you should do something like this:

double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}

Parsing date string in Go

I will suggest using time.RFC3339 constant from time package. You can check other constants from time package. https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}

Remove ListView items in Android

You can also use listView.setOnItemLongClickListener to delete selected item. Below is the code.

// listView = name of your ListView

  listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int 
        position, long id) {

        // it will get the position of selected item from the ListView

final int selected_item = position;

            new AlertDialog.Builder(MainActivity.this).
                    setIcon(android.R.drawable.ic_delete)
                    .setTitle("Are you sure...")
                    .setMessage("Do you want to delete the selected item..?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            list.remove(selected_item);
                            arrayAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton("No" , null).show();

            return true;
        }
    });

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.

select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];

Is it possible to start activity through adb shell?

Launch adb shell and enter the command as follows

am start -n yourpackagename/.activityname

What data is stored in Ephemeral Storage of Amazon EC2 instance?

According to AWS documentation [https://aws.amazon.com/premiumsupport/knowledge-center/instance-store-vs-ebs/] instance store volumes is not persistent through instance stops, terminations, or hardware failures. Any AMI created from instance stored disk doesn't contain data present in instance store so all instances launched by this AMI will not have data stored in instance store. Instance store can be used as cache for applications running on instance, for all persistent data you should use EBS.

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv, which are socket-specific ways of writing and reading data). The outline would look something like this:

while (1) {
    // Read data into buffer.  We may not have enough to fill up buffer, so we
    // store how many bytes were actually read in bytes_read.
    int bytes_read = read(input_file, buffer, sizeof(buffer));
    if (bytes_read == 0) // We're done reading from the file
        break;

    if (bytes_read < 0) {
        // handle errors
    }

    // You need a loop for the write, because not all of the data may be written
    // in one call; write will return how many bytes were written. p keeps
    // track of where in the buffer we are, while we decrement bytes_read
    // to keep track of how many bytes are left to write.
    void *p = buffer;
    while (bytes_read > 0) {
        int bytes_written = write(output_socket, p, bytes_read);
        if (bytes_written <= 0) {
            // handle errors
        }
        bytes_read -= bytes_written;
        p += bytes_written;
    }
}

Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop.

For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile.

Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).

In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile. splice is a more general purpose API than sendfile. For a good description of splice and tee, see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").

How to set cookie in node js using express framework?

Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.

My issue was that cookies were set in server response, but were not saved by the browser.

The server response came back with cookies set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

This is how I solved it.

I used fetch in the client-side code. If you do not specify credentials: 'include' in the fetch options, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.

Example:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

I hope this helps somebody.

Is Safari on iOS 6 caching $.ajax results?

A quick work-around for GWT-RPC services is to add this to all the remote methods:

getThreadLocalResponse().setHeader("Cache-Control", "no-cache");

"Line contains NULL byte" in CSV reader (Python)

pandas.read_csv now handles the different UTF encoding when reading/writing and therefore can deal directly with null bytes

data = pd.read_csv(file, encoding='utf-16')

see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

Multiple contexts with the same path error running web service in Eclipse using Tomcat

In my case I found duplicate paths in Servers/Tomcat5.5 at localhost-config/server.xml under tag. Removing the duplicates solved the problem.

How to Generate a random number of fixed length using JavaScript?

This is another random number generator that i use often, it also prevent the first digit from been zero(0)

_x000D_
_x000D_
  function randomNumber(length) {_x000D_
    var text = "";_x000D_
    var possible = "123456789";_x000D_
    for (var i = 0; i < length; i++) {_x000D_
      var sup = Math.floor(Math.random() * possible.length);_x000D_
      text += i > 0 && sup == i ? "0" : possible.charAt(sup);_x000D_
    }_x000D_
    return Number(text);_x000D_
  }
_x000D_
_x000D_
_x000D_

Image comparison - fast algorithm

This post was the starting point of my solution, lots of good ideas here so I though I would share my results. The main insight is that I've found a way to get around the slowness of keypoint-based image matching by exploiting the speed of phash.

For the general solution, it's best to employ several strategies. Each algorithm is best suited for certain types of image transformations and you can take advantage of that.

At the top, the fastest algorithms; at the bottom the slowest (though more accurate). You might skip the slow ones if a good match is found at the faster level.

  • file-hash based (md5,sha1,etc) for exact duplicates
  • perceptual hashing (phash) for rescaled images
  • feature-based (SIFT) for modified images

I am having very good results with phash. The accuracy is good for rescaled images. It is not good for (perceptually) modified images (cropped, rotated, mirrored, etc). To deal with the hashing speed we must employ a disk cache/database to maintain the hashes for the haystack.

The really nice thing about phash is that once you build your hash database (which for me is about 1000 images/sec), the searches can be very, very fast, in particular when you can hold the entire hash database in memory. This is fairly practical since a hash is only 8 bytes.

For example, if you have 1 million images it would require an array of 1 million 64-bit hash values (8 MB). On some CPUs this fits in the L2/L3 cache! In practical usage I have seen a corei7 compare at over 1 Giga-hamm/sec, it is only a question of memory bandwidth to the CPU. A 1 Billion-image database is practical on a 64-bit CPU (8GB RAM needed) and searches will not exceed 1 second!

For modified/cropped images it would seem a transform-invariant feature/keypoint detector like SIFT is the way to go. SIFT will produce good keypoints that will detect crop/rotate/mirror etc. However the descriptor compare is very slow compared to hamming distance used by phash. This is a major limitation. There are a lot of compares to do, since there are maximum IxJxK descriptor compares to lookup one image (I=num haystack images, J=target keypoints per haystack image, K=target keypoints per needle image).

To get around the speed issue, I tried using phash around each found keypoint, using the feature size/radius to determine the sub-rectangle. The trick to making this work well, is to grow/shrink the radius to generate different sub-rect levels (on the needle image). Typically the first level (unscaled) will match however often it takes a few more. I'm not 100% sure why this works, but I can imagine it enables features that are too small for phash to work (phash scales images down to 32x32).

Another issue is that SIFT will not distribute the keypoints optimally. If there is a section of the image with a lot of edges the keypoints will cluster there and you won't get any in another area. I am using the GridAdaptedFeatureDetector in OpenCV to improve the distribution. Not sure what grid size is best, I am using a small grid (1x3 or 3x1 depending on image orientation).

You probably want to scale all the haystack images (and needle) to a smaller size prior to feature detection (I use 210px along maximum dimension). This will reduce noise in the image (always a problem for computer vision algorithms), also will focus detector on more prominent features.

For images of people, you might try face detection and use it to determine the image size to scale to and the grid size (for example largest face scaled to be 100px). The feature detector accounts for multiple scale levels (using pyramids) but there is a limitation to how many levels it will use (this is tunable of course).

The keypoint detector is probably working best when it returns less than the number of features you wanted. For example, if you ask for 400 and get 300 back, that's good. If you get 400 back every time, probably some good features had to be left out.

The needle image can have less keypoints than the haystack images and still get good results. Adding more doesn't necessarily get you huge gains, for example with J=400 and K=40 my hit rate is about 92%. With J=400 and K=400 the hit rate only goes up to 96%.

We can take advantage of the extreme speed of the hamming function to solve scaling, rotation, mirroring etc. A multiple-pass technique can be used. On each iteration, transform the sub-rectangles, re-hash, and run the search function again.

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Please see Why does the property I want to mock need to be virtual?

You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x) call.

cat, grep and cut - translated to python

you need to use os.system module to execute shell command

import os
os.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

How to find the length of a string in R

nchar(YOURSTRING)

you may need to convert to a character vector first;

nchar(as.character(YOURSTRING))

How can I make a UITextField move up when the keyboard is present - on starting to edit?

It is very simple just put following code in your class and customise if you needed .

-(void)textFieldDidBeginEditing:(UITextField *)textField {
     //Show Keyboard
     self.view.frame = CGRectMake(self.view.frame.origin.x,
                              self.view.frame.origin.y-50,
                              self.view.frame.size.width,
                              self.view.frame.size.height);   
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
     // Hide keyboard
     self.view.frame = CGRectMake(self.view.frame.origin.x,
                              self.view.frame.origin.y+50,
                              self.view.frame.size.width,
                              self.view.frame.size.height); 
}

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000

How to replace all occurrences of a character in string?

A simple find and replace for a single character would go something like:

s.replace(s.find("x"), 1, "y")

To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

Ruby on Rails: Clear a cached page

I was able to resolve this problem by cleaning my assets cache:

$ rake assets:clean

Dynamically adding properties to an ExpandoObject

i think this add new property in desired type without having to set a primitive value, like when property defined in class definition

var x = new ExpandoObject();
x.NewProp = default(string)

Force IE9 to emulate IE8. Possible?

Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:

  • Fire up Internet Explorer.
  • Click the 'Tools' menu, then click 'Developer Tools'. Alternatively, just press F12.

That should open the Developer Tools window. That window has two menu items that are of interest:

  • Browser Mode. This setting determines the value of the user-agent header sent for every request.
  • Document Mode. This setting determines how the rendering engine renders the page.

More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx

Open a Web Page in a Windows Batch FIle

start did not work for me.

I used:

firefox http://www.stackoverflow.com

or

chrome http://www.stackoverflow.com

Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.

How do you get current active/default Environment profile programmatically in Spring?

Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles

How to recursively download a folder via FTP on Linux

toggle the prompt by PROMPT command.

Usage:

ftp>cd /to/directory    
ftp>prompt    
ftp>mget  *

document.createElement("script") synchronously

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

Alright, buckle your seats, because it's going to be a bumpy ride. More and more people ask about loading scripts dynamically via javascript, it seems to be a hot topic.

The main reasons why this became so popular are:

  • client-side modularity
  • easier dependency management
  • error handling
  • performance advantages

About modularity: it is obvious that managing client-side dependencies should be handled right on the client-side. If a certain object, module or library is needed we just ask for it and load it dynamically.

Error handling: if a resource fails we still get the chance to block only the parts that depend on the affected script, or maybe even give it another try with some delay.

Performance has become a competitive edge between websites, it is now a search ranking factor. What dynamic scripts can do is mimic asynchronous behavior as opposed to the default blocking way of how browsers handle scripts. Scripts block other resources, scripts block further parsing of the HTML document, scripts block the UI. Now with dynamic script tags and its cross-browser alternatives you can do real asynchronous requests, and execute dependent code only when they are available. Your scripts will load in-parallel even with other resources and the rendering will be flawless.

The reason why some people stick to synchronous scripting is because they are used to it. They think it is the default way, it is the easier way, and some may even think it is the only way.

But the only thing we should care about when this needs to be decided concerning an applications's design is the end-user experience. And in this area asynchronous cannot be beaten. The user gets immediate responses (or say promises), and a promise is always better than nothing. A blank screen scares people. Developers shouldn't be lazy to enhance perceived performance.

And finally some words about the dirty side. What you should do in order to get it working across browsers:

  1. learn to think asynchronously
  2. organize your code to be modular
  3. organize your code to handle errors and edge cases well
  4. enhance progressively
  5. always take care of the right amount of feedback

creating a table in ionic

enter image description here

.html file

<ion-card-content>
<div class='summary_row'>
      <div  class='summarycell'>Header 1</div>
      <div  class='summarycell'>Header 2</div>
      <div  class='summarycell'>Header 3</div>
      <div  class='summarycell'>Header 4</div>
      <div  class='summarycell'>Header 5</div>
      <div  class='summarycell'>Header 6</div>
      <div  class='summarycell'>Header 7</div>

    </div>
    <div  class='summary_row'>
      <div  class='summarycell'>
        Cell1
      </div>
      <div  class='summarycell'>
          Cell2
      </div>
        <div  class='summarycell'>
            Cell3
          </div>

      <div  class='summarycell'>
        Cell5
      </div>
      <div  class='summarycell'>
          Cell6
        </div>
        <div  class='summarycell'>
            Cell7
          </div>
          <div  class='summarycell'>
              Cell8
            </div>
    </div>

.scss file

_x000D_
_x000D_
.row{_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    width: max-content;_x000D_
}_x000D_
.row:first-child .summarycell{_x000D_
    font-weight: bold;_x000D_
    text-align: center;_x000D_
}_x000D_
.cell{_x000D_
    overflow: auto;_x000D_
    word-wrap: break-word;_x000D_
    width: 27vw;_x000D_
    border: 1px solid #b3b3b3;_x000D_
    padding: 10px;_x000D_
    text-align: right;_x000D_
}_x000D_
.cell:nth-child(2){_x000D_
}_x000D_
.cell:first-child{_x000D_
    width:41vw;_x000D_
    text-align: left;_x000D_
}
_x000D_
_x000D_
_x000D_

T-SQL How to select only Second row from a table?

I have a much easier way than the above ones.

DECLARE @FirstId int, @SecondId int

    SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
    SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 

SELECT @SecondId 

How can I count the number of elements of a given value in a matrix?

this would be perfect cause we are doing operation on matrix, and the answer should be a single number

sum(sum(matrix==value))

How to calculate time difference in java?

Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.

Advanced Java 8 libraries. ChronoUnit for Differences.

ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.

LocalTime one = LocalTime.of(5,15);
LocalTime two = LocalTime.of(6,30);
LocalDate date = LocalDate.of(2019, 1, 29);

System.out.println(ChronoUnit.HOURS.between(one, two)); //1
System.out.println(ChronoUnit.MINUTES.between(one, two)); //75
System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException

First example shows that between truncates rather than rounds.

The second shows how easy it is to count different units.

And the last example reminds us that we should not mess up with dates and times in Java :)

remove duplicates from sql union

If you are using T-SQL then it appears from previous posts that UNION removes duplicates. But if you are not, you could use distinct. This doesn't quite feel right to me either but it could get you the result you are looking for

SELECT DISTINCT *
FROM
(
select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
)a

How to install a node.js module without using npm?

Step-by-step:

  • let's say you are working on a project use-gulp which uses(requires) node_modules like gulp and gulp-util.
  • Now you want to make some modifications to gulp-util lib and test it locally with your use-gulp project...
  • Fork gulp-util project on github\bitbucket etc.
  • Switch to your project: cd use-gulp/node_modules
  • Clone gulp-util as gulp-util-dev : git clone https://.../gulp-util.git gulp-util-dev
  • Run npm install to ensure dependencies of gulp-util-dev are available.
  • Now you have a mirror of gulp-util as gulp-util-dev. In your use-gulp project, you can now replace: require('gulp-util')...; call with : require('gulp-util-dev') to test your changes you made to gulp-util-dev

Change color inside strings.xml

Just add your text between the font tags:

for blue color

<string name="hello_world"><font color='blue'>Hello world!</font></string>

or for red color

<string name="hello_world"><font color='red'>Hello world!</font></string>

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Java Compare Two Lists

If you are looking for a handy way to test the equality of two collections, you can use org.apache.commons.collections.CollectionUtils.isEqualCollection, which compares two collections regardless of the ordering.

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

Create an array of integers property in Objective-C

I'm just speculating:

I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:

int *doubleDigits;

And then allocate the space for it in the init-method:

@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}

In this case the interface looks like this:

@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;

Edit:

I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)

int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];

What does the 'standalone' directive mean in XML?

The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.

As an example, consider the humble <img> tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img> tags must be EMPTY and possess src and alt attributes. When a browser is going through an XHTML 1.0 document and finds an <img> tag, it should notice that the DTD requires src and alt attributes and add them if they are not present. It will also self-close the <img> tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone declaration to tell the parser to ignore these rules.

Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.

Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

In Simple Terms,

1.INNER JOIN OR EQUI JOIN : Returns the resultset that matches only the condition in both the tables.

2.OUTER JOIN : Returns the resultset of all the values from both the tables even if there is condition match or not.

3.LEFT JOIN : Returns the resultset of all the values from left table and only rows that match the condition in right table.

4.RIGHT JOIN : Returns the resultset of all the values from right table and only rows that match the condition in left table.

5.FULL JOIN : Full Join and Full outer Join are same.

How to programmatically set style attribute in a view

Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically.

There is also such a thing as a StateListDrawable which lets you define different drawables for each state the your Button can be in, whether focused, selected, pressed, disabled and so on.

For example, to get your button to change colour when it's pressed, you could define an XML file called res/drawable/my_button.xml directory like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/btn_pressed" />
  <item
    android:state_pressed="false"
    android:drawable="@drawable/btn_normal" />
</selector>

You can then apply this selector to a Button by setting the property android:background="@drawable/my_button".

PHP: How do you determine every Nth iteration of a loop?

I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.

if ($ucounter % 1000 == 0) { echo '+'; }

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

How I can check if an object is null in ruby on rails 2?

it's nilin Ruby, not null. And it's enough to say if @objectname to test whether it's not nil. And no then. You can find more on if syntax here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if

jQuery, checkboxes and .is(":checked")

Well, to match the first scenario, this is something I've come up with.

http://jsbin.com/uwupa/edit

Essentially, instead of binding the "click" event, you bind the "change" event with the alert.

Then, when you trigger the event, first you trigger click, then trigger change.

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

Code for best fit straight line of a scatter plot in python

A one-line version of this excellent answer to plot the line of best fit is:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

Using np.unique(x) instead of x handles the case where x isn't sorted or has duplicate values.

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

Join String list elements with a delimiter in one step

If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
                "\n", "<value>", "</value>");

SQL Update to the SUM of its joined values

Use a sub query similar to the below.

UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join 
(Select PitchID, Sum(Price) TotalPrice
    from  dbo.BookingPitchExtras
    Where [Required] = 1
    Group by Pitchid
) as Sub
on p.Id = e.PitchId 
where p.BookingId = 1

How to auto-indent code in the Atom editor?

The accepted answer works, but you have to do a "Select All" first -- every time -- and I'm way too lazy for that.

And it turns out, it's not super trivial -- I figured I'd post this here in an attempt to save like-minded individuals the 30 minutes it takes to track all this down. -- Also note: this approach restores the original selection when it's done (and it happens so fast, you don't even notice the selection was ever changed).

1.) First, add a custom command to your init script (File->Open Your Init Script, then paste this at the bottom):

atom.commands.add 'atom-text-editor', 'custom:reformat', ->
    editor = atom.workspace.getActiveTextEditor();
    oldRanges = editor.getSelectedBufferRanges();
    editor.selectAll();
    atom.commands.dispatch(atom.views.getView(editor), 'editor:auto-indent')
    editor.setSelectedBufferRanges(oldRanges);

2.) Bind "custom:reformat" to a key (File->Open Your Keymap, then paste this at the bottom):

'atom-text-editor':
    'ctrl-alt-d': 'custom:reformat'

3.) Restart Atom (the init.coffee script only runs when atom is first launched).

Global environment variables in a shell script

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

Does --disable-web-security Work In Chrome Anymore?

Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

What is Model in ModelAndView from Spring MVC?

The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.

Example 1

If you have...

return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");

... then in your jsp, to display the message, you will do:-

Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!

Example 2

If you have...

MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");

return new ModelAndView("welcomePage","model",bean);

... then in your jsp, you can do:-

Hello ${model.name}! {model.message} // displays Hello Mike! Meow!

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

I'm not sure what you're trying to do: If you added the file via

svn add myfile

you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an

svn commit

If you delete the file before the commit, svn has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.

So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via

svn delete myfile
svn commit

If you want to undo the add and just throw the file away, you can to an

svn revert myfile

which tells svn (in this case) to undo the add-Operation.

EDIT

Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)

Possible cases for Javascript error: "Expected identifier, string or number"

Here is a easy technique to debug the problem: echo out the script/code to the console. Copy the code from the console into your IDE. Most IDE's perform error checking on the code and highlight errors. You should be able to see the error almost immediately in your JavaScript/HTML editor.

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

PHP $_POST not working?

try this
html code

  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
          <input type="text" name="firstname">
          <input type="submit" name="submit" value="Submit">
        </form>

php code:

if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;

}

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Clear repository is one possible solution.

Windows -> delete all subfolders in the maven repository:

C:\Users\YourUserName.m2\repository

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

Copy entire directory contents to another directory?

The following is an example of using JDK7.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}

To use the visitor do the following

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));

If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });

Get the string representation of a DOM node

if using react:

const html = ReactDOM.findDOMNode(document.getElementsByTagName('html')[0]).outerHTML;

Check if decimal value is null

I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:

var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;

This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.

What is the cleanest way to disable CSS transition effects temporarily?

If you want to remove CSS transitions, transformations and animations from the current webpage you can just execute this little script I wrote (inside your browsers console):

let filePath = "https://dl.dropboxusercontent.com/s/ep1nzckmvgjq7jr/remove_transitions_from_page.css";
let html = `<link rel="stylesheet" type="text/css" href="${filePath}">`;
document.querySelector("html > head").insertAdjacentHTML("beforeend", html);

It uses vanillaJS to load this css-file. Heres also a github repo in case you want to use this in the context of a scraper (Ruby-Selenium): remove-CSS-animations-repo

Shell script - remove first and last quote (") from a variable

I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...

echo "$opt" | sed -r 's/^"|"$//g'

A valid provisioning profile for this executable was not found... (again)

+1 to banging my head against the wall for a day or two...

Also check this setting:

Build Settings -> Code Signing -> Provisioning Profile

After following the above steps, "Automatic" setting worked for me. ~kjm~

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

How to get share counts using graph API

You should not use graph api. If you either call:

or

both will return:

{
  "id": "http://www.apple.com",
  "shares": 1146997
}

But the number shown is the sum of:

  • number of likes of this URL
  • number of shares of this URL (this includes copy/pasting a link back to Facebook)
  • number of likes and comments on stories on Facebook about this URL
  • number of inbox messages containing this URL as an attachment.

So you must use FQL.
Look at this answer: How to fetch facebook likes, share, comments count from an article

Express-js wildcard routing to cover everything under and including a path

It is not necessary to have two routes.

Simply add (/*)? at the end of your path string.

For example, app.get('/hello/world(/*)?' /* ... */)

Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):

const app = require('express')()

// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'

// but fail at this one
const failTest = 'http://localhost:3000/foo/world'

app.get('/hello/world(/*)?', (req, res) => res.send(`
    This will match at example endpoints: <br><br>
    <pre><a href="${test1}">${test1}</a></pre>
    <pre><a href="${test2}">${test2}</a></pre>
    <pre><a href="${test3}">${test3}</a></pre>

    <br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))

app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))

How to get distinct values for non-key column fields in Laravel?

// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);

Showing which files have changed between two revisions

git diff revision_n revision_m

if revision_n and revision_m are successive commits then it outputs same as git show revision_m

PuTTY Connection Manager download?

PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.

http://sourceforge.net/projects/puttysm/

Find out free space on tablespace

There are many ways to check the size, but as a developer we dont have much access to query meta tables, I find this solution very easy (Note: if you are getting error message ORA-01653 ‘The ORA-01653 error is caused because you need to add space to a tablespace.’)

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

Thanks

Retrieve last 100 lines logs

Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):

$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p

$ sed -nf sed.cmd logfilename

For me it is way more difficult than your script so

tail -n 100 logfilename

is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910

mysql_config not found when installing mysqldb python interface

In centos 7 this works for me :

yum install mariadb-devel
pip install mysqlclient