Programs & Examples On #Black box

Should black box or white box testing be the emphasis for testers?

  • *Black box testing: Is the test at system level to check the functionality of the system, to ensure that the system performs all the functions that it was designed for, Its mainly to uncover defects found at the user point. Its better to hire a professional tester to black box your system, 'coz the developer usually tests with a perspective that the codes he had written is good and meets the functional requirements of the clients so he could miss out a lot of things (I don't mean to offend anybody)
  • Whitebox is the first test that is done in the SDLC.This is to uncover bugs like runtime errors and compilation errrors It can be done either by testers or by Developer himself, But I think its always better that the person who wrote the code tests it.He understands them more than another person.*

MySQL, Check if a column exists in a table with SQL

This works well for me.

SHOW COLUMNS FROM `table` LIKE 'fieldname';

With PHP it would be something like...

$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

How to export and import a .sql file from command line with options?

Dump an entire database to a file:

mysqldump -u USERNAME -p password DATABASENAME > FILENAME.sql

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

"Full screen" <iframe>

You can also use viewport-percentage lengths to achieve this:

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

Where 100vh represents the height of the viewport, and likewise 100vw represents the width.

Example Here

_x000D_
_x000D_
body {_x000D_
    margin: 0;            /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
    display: block;       /* iframes are inline by default */_x000D_
    background: #000;_x000D_
    border: none;         /* Reset default border */_x000D_
    height: 100vh;        /* Viewport-relative units */_x000D_
    width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
_x000D_
_x000D_

This is supported in most modern browsers - support can be found here.

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

This problem happened with me when I used jQUery Fancybox inside a website with many others jQuery plugins. When I used the LightBox (site here) instead of Fancybox, the problem is gone.

Switch with if, else if, else, and loops inside case

If you need the for statement to contain only the if, you need to remove its else, like this:

for(int i=0; i<something_in_the_array.length;i++)
    if(whatever_value==(something_in_the_array[i]))
    {
        value=2;
        break;
    }

    /*this "else" must go*/
    if(whatever_value==2)
    {
        value=3;
        break;
    }

    else if(whatever_value==3)
    {
        value=4;
        break;
    }

How to have an automatic timestamp in SQLite?

You can create TIMESTAMP field in table on the SQLite, see this:

CREATE TABLE my_table (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(64),
    sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);

INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');

This is the result:

SELECT * FROM my_table;

enter image description here

How to escape JSON string?

I nice one-liner, used JsonConvert as others have but added substring to remove the added quotes and backslash.

 var escapedJsonString = JsonConvert.ToString(JsonString).Substring(1, JsonString.Length - 2);

Port 443 in use by "Unable to open process" with PID 4

I had a similar issue where port 443 was blocked by PID 4. After breaking my head for several hours I found the command netsh show urlacl which gave me an idea of the system process blocking the port.

To run command run cmd or windows shell in administrator mode.

netsh

http

show urlacl

I got response a which showed 443 was blocked by NT Service SSTPSvc Reserved URL

Response

https://+:443/sra_{BA195980-CD49-458b-9E23-C84EE0ADCD75}/ User: NT SERVICE\SstpSvc Listen: Yes Delegate: Yes User: BUILTIN\Administrators Listen: No Delegate: No User: NT AUTHORITY\SYSTEM Listen: Yes Delegate: Yes

With this information I followed the microsoft link to change the listening port for SSTP based vpn. https://support.microsoft.com/en-in/kb/947032

This resolved my port issue.

In Angular, how do you determine the active route?

how do you determine what the currently active route is?

UPDATE: updated as per Angular2.4.x

constructor(route: ActivatedRoute) {
   route.snapshot.params; // active route's params

   route.snapshot.data; // active route's resolved data

   route.snapshot.component; // active route's component

   route.snapshot.queryParams // The query parameters shared by all the routes
}

see more...

How to write connection string in web.config file and read from it?

After opening the web.config file in application, add sample db connection in connectionStrings section like this:

<connectionStrings>  
    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   
</connectionStrings>  

Declaring connectionStrings in web.config file:

 <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient" />   

There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);  
        con.Open();  
    }  
}  

Binding select element to object in Angular


<select name="typeFather"
    [(ngModel)]="type.typeFather">
        <option *ngFor="let type of types" [ngValue]="type">{{type.title}}</option>
</select>

that approach always gonna work, however If you have a dynamic list, make sure you load it before the model

Convert a hexadecimal string to an integer efficiently in C?

@Eric

Why is a code solution that works getting voted down? Sure, it's ugly and might not be the fastest way to do it, but it's more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood.

I don't really think your solution should have been voted down, but my guess as to why it's happening is because it's less practical. The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it's definitely not the best way to parse hex numbers in a production system.

Again, I don't think there's anything wrong with your answer from an educational standpoint, and I certainly wouldn't (and didn't) vote it down. Don't get discouraged and stop posting just because some people didn't like one of your answers. It happens.

I doubt my answer makes you feel any better about yours being voted down, but I know it's especially not fun when you ask why something's being voted down and no one answers.

Eclipse 3.5 Unable to install plugins

Have you read this post?

http://eclipsewebmaster.blogspot.ch/search?q=wow-what-a-painful-release-this-was-is

Maybe it explains, why it was kinda difficult the last days.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to auto import the necessary classes in Android Studio with shortcut?

File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with

enter image description here

How do I get the offset().top value of an element without using jQuery?

Here is a function that will do it without jQuery:

function getElementOffset(element)
{
    var de = document.documentElement;
    var box = element.getBoundingClientRect();
    var top = box.top + window.pageYOffset - de.clientTop;
    var left = box.left + window.pageXOffset - de.clientLeft;
    return { top: top, left: left };
}

Is there an equivalent of 'which' on the Windows command line?

While later versions of Windows have a where command, you can also do this with Windows XP by using the environment variable modifiers, as follows:

c:\> for %i in (cmd.exe) do @echo.   %~$PATH:i
   C:\WINDOWS\system32\cmd.exe

c:\> for %i in (python.exe) do @echo.   %~$PATH:i
   C:\Python25\python.exe

You don't need any extra tools and it's not limited to PATH since you can substitute any environment variable (in the path format, of course) that you wish to use.


And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:

@echo off
setlocal enableextensions enabledelayedexpansion

:: Needs an argument.

if "x%1"=="x" (
    echo Usage: which ^<progName^>
    goto :end
)

:: First try the unadorned filenmame.

set fullspec=
call :find_it %1

:: Then try all adorned filenames in order.

set mypathext=!pathext!
:loop1
    :: Stop if found or out of extensions.

    if "x!mypathext!"=="x" goto :loop1end

    :: Get the next extension and try it.

    for /f "delims=;" %%j in ("!mypathext!") do set myext=%%j
    call :find_it %1!myext!

:: Remove the extension (not overly efficient but it works).

:loop2
    if not "x!myext!"=="x" (
        set myext=!myext:~1!
        set mypathext=!mypathext:~1!
        goto :loop2
    )
    if not "x!mypathext!"=="x" set mypathext=!mypathext:~1!

    goto :loop1
:loop1end

:end
endlocal
goto :eof

:: Function to find and print a file in the path.

:find_it
    for %%i in (%1) do set fullspec=%%~$PATH:i
    if not "x!fullspec!"=="x" @echo.   !fullspec!
    goto :eof

It actually returns all possibilities but you can tweak it quite easily for specific search rules.

When does a cookie with expiration time 'At end of session' expire?

Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!

On iOS with Safari they expire whenever you switch apps!

On Android with Chrome they don't expire when you close the browser.

On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

iPhone UIView Animation Best Practice

From the UIView reference's section about the beginAnimations:context: method:

Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.

Eg of Block-based Animation based on Tom's Comment

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

What is the difference between WCF and WPF?

WCF = Windows COMMUNICATION Foundation

WPF = Windows PRESENTATION Foundation.

WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)

Difference between Spring MVC and Struts MVC

Spring provides a very clean division between controllers, JavaBean models, and views.

Get 2 Digit Number For The Month

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

What does the 'static' keyword do in a class?

The keyword static is used to denote a field or a method as belonging to the class itself and not the instance. Using your code, if the object Clock is static, all of the instances of the Hello class will share this Clock data member (field) in common. If you make it non-static, each individual instance of Hello can have a unique Clock field.

You added a main method to your class Hello so that you could run the code. The problem with that is that the main method is static and as such, it cannot refer to non-static fields or methods inside of it. You can resolve this in two ways:

  1. Make all fields and methods of the Hello class static so that they could be referred to inside the main method. This is really not a good thing to do (or the wrong reason to make a field and/or a method static)
  2. Create an instance of your Hello class inside the main method and access all it's fields and methods the way they were intended to in the first place.

For you, this means the following change to your code:

package hello;

public class Hello {

    private Clock clock = new Clock();

    public Clock getClock() {
        return clock;
    }

    public static void main(String args[]) {
        Hello hello = new Hello();
        hello.getClock().sayTime();
    }
}

What is syntax for selector in CSS for next element?

The > is a child selector. So if your HTML looks like this:

<h1 class="hc-reform">
    title
    <p>stuff here</p>
</h1>

... then that's your ticket.

But if your HTML looks like this:

<h1 class="hc-reform">
    title
</h1>
<p>stuff here</p>

Then you want the adjacent selector:

h1.hc-reform + p{
     clear:both;
}

number of values in a list greater than a certain number

If you are using NumPy (as in ludaavic's answer), for large arrays you'll probably want to use NumPy's sum function rather than Python's builtin sum for a significant speedup -- e.g., a >1000x speedup for 10 million element arrays on my laptop:

>>> import numpy as np
>>> ten_million = 10 * 1000 * 1000
>>> x, y = (np.random.randn(ten_million) for _ in range(2))
>>> %timeit sum(x > y)  # time Python builtin sum function
1 loops, best of 3: 24.3 s per loop
>>> %timeit (x > y).sum()  # wow, that was really slow! time NumPy sum method
10 loops, best of 3: 18.7 ms per loop
>>> %timeit np.sum(x > y)  # time NumPy sum function
10 loops, best of 3: 18.8 ms per loop

(above uses IPython's %timeit "magic" for timing)

What is Turing Complete?

As Waylon Flinn said:

Turing Complete means that it is at least as powerful as a Turing Machine.

I believe this is incorrect, a system is Turing complete if it's exactly as powerful as the Turing Machine, i.e. every computation done by the machine can be done by the system, but also every computation done by the system can be done by the Turing machine.

How do I append a node to an existing XML file in java

If you need to insert node/element in some specific place , you can to do next steps

  1. Divide original xml into two parts
  2. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  3. Append second part to the new document.

It is simple algorithm but should works...

How do I group Windows Form radio buttons?

Put all radio buttons for a group in a container object like a Panel or a GroupBox. That will automatically group them together in Windows Forms.

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

Javascript: Extend a Function

The other methods are great but they don't preserve any prototype functions attached to init. To get around that you can do the following (inspired by the post from Nick Craver).

(function () {
    var old_prototype = init.prototype;
    var old_init = init;
    init = function () {
        old_init.apply(this, arguments);
        // Do something extra
    };
    init.prototype = old_prototype;
}) ();

File name without extension name VBA

Using the Split function seems more elegant than InStr and Left, in my opinion.

Private Sub CommandButton2_Click()


Dim ThisFileName As String
Dim BaseFileName As String

Dim FileNameArray() As String

ThisFileName = ThisWorkbook.Name
FileNameArray = Split(ThisFileName, ".")
BaseFileName = FileNameArray(0)

MsgBox "Base file name is " & BaseFileName

End Sub

sqldeveloper error message: Network adapter could not establish the connection error

https://forums.oracle.com/forums/thread.jspa?threadID=2150962

Re: SQL DevErr:The Network Adapter could not establish the connection VenCode20 Posted: Dec 7, 2011 3:23 AM in response to: MehulDoshi Reply

This worked for me:

Open the "New/Select Database Connection" dialogue and try changing the connection type setting from "Basic" to "TNS" and then selecting the network alias (for me: "ORCL").

How do I programmatically "restart" an Android app?

Use:

navigateUpTo(new Intent(this, MainActivity.class));

It works starting from API level 16 (4.1), I believe.

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Static variable inside of a function in C

You will get 6 7 printed as, as is easily tested, and here's the reason: When foo is first called, the static variable x is initialized to 5. Then it is incremented to 6 and printed.

Now for the next call to foo. The program skips the static variable initialization, and instead uses the value 6 which was assigned to x the last time around. The execution proceeds as normal, giving you the value 7.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

According to the GNU make manual:

CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.

CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.

These variables are used by the implicit rules of make

Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.

Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.

src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules

How can I set the focus (and display the keyboard) on my EditText programmatically

use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

The difference between the Runnable and Callable interfaces in Java

Callable and Runnable both is similar to each other and can use in implementing thread. In case of implementing Runnable you must implement run() method but in case of callable you must need to implement call() method, both method works in similar ways but callable call() method have more flexibility.There is some differences between them.

Difference between Runnable and callable as below--

1) The run() method of runnable returns void, means if you want your thread return something which you can use further then you have no choice with Runnable run() method. There is a solution 'Callable', If you want to return any thing in form of object then you should use Callable instead of Runnable. Callable interface have method 'call()' which returns Object.

Method signature - Runnable->

public void run(){}

Callable->

public Object call(){}

2) In case of Runnable run() method if any checked exception arises then you must need to handled with try catch block, but in case of Callable call() method you can throw checked exception as below

 public Object call() throws Exception {}

3) Runnable comes from legacy java 1.0 version, but callable came in Java 1.5 version with Executer framework.

If you are familiar with Executers then you should use Callable instead of Runnable.

Hope you understand.

Processing Symbol Files in Xcode

In my case symbolicating was take forever. I force restart my phone with both of on/off and home button. Now quickly finished symbolicating and I am starting run my app via xcode.

Get latitude and longitude automatically using php, API

I think allow_url_fopen on your apache server is disabled. you need to trun it on.

kindly change allow_url_fopen = 0 to allow_url_fopen = 1

Don't forget to restart your Apache server after changing it.

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How to initialize a dict with keys from a list and empty value in Python?

You could use dict.fromkeys as follows:

dict.fromkeys([1, 2, 3, 4], list())

This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).

Taking pictures with camera on Android programmatically

For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.

How to split a string between letters and digits (or between digits and letters)?

If you are looking for solution without using Java String functionality (i.e. split, match, etc.) then the following should help:

List<String> splitString(String string) {
        List<String> list = new ArrayList<String>();
        String token = "";
        char curr;
        for (int e = 0; e < string.length() + 1; e++) {
            if (e == 0)
                curr = string.charAt(0);
            else {
                curr = string.charAt(--e);
            }

            if (isNumber(curr)) {
                while (e < string.length() && isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            } else {
                while (e < string.length() && !isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            }

        }

        return list;
    }

boolean isNumber(char c) {
        return c >= '0' && c <= '9';
    }

This solution will split numbers and 'words', where 'words' are strings that don't contain numbers. However, if you like to have only 'words' containing English letters then you can easily modify it by adding more conditions (like isNumber method call) depending on your requirements (for example you may wish to skip words that contain non English letters). Also note that the splitString method returns ArrayList which later can be converted to String array.

Return multiple values from a function, sub or type?

Not elegant, but if you don't use your method overlappingly you can also use global variables, defined by the Public statement at the beginning of your code, before the Subs. You have to be cautious though, once you change a public value, it will be held throughout your code in all Subs and Functions.

Different ways of clearing lists

another solution that works fine is to create empty list as a reference empty list.

empt_list = []

for example you have a list as a_list = [1,2,3]. To clear it just make the following:

a_list = list(empt_list)

this will make a_list an empty list just like the empt_list.

Key Listeners in python?

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

How to find day of week in php in a specific timezone

My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue

visual c++: #include files from other projects in the same solution

You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.

How to implement a binary search tree in Python?

I find the solutions a bit clumsy on the insert part. You could return the root reference and simplify it a bit:

def binary_insert(root, node):
    if root is None:
        return node
    if root.data > node.data:
        root.l_child = binary_insert(root.l_child, node)
    else:
        root.r_child = binary_insert(root.r_child, node)
    return root

Groovy String to Date

Date#parse is deprecated . The alternative is :

java.text.DateFormat#parse 

thereFore :

 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

Change first commit of project with Git?

As stated in 1.7.12 Release Notes, you may use

$ git rebase -i --root

Are there any naming convention guidelines for REST APIs?

I have a list of guidelines at http://soaprobe.blogspot.co.uk/2012/10/soa-rest-service-naming-guideline.html which we have used in prod. Guidelines are always debatable... I think consistency is sometimes more important than getting things perfect (if there is such a thing).

MySQL select query with multiple conditions

@fthiella 's solution is very elegant.

If in future you want show more than user_id you could use joins, and there in one line could be all data you need.

If you want to use AND conditions, and the conditions are in multiple lines in your table, you can use JOINS example:

SELECT `w_name`.`user_id` 
     FROM `wp_usermeta` as `w_name`
     JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id` 
          AND `w_name`.`meta_key` = 'first_name' 
          AND `w_year`.`meta_key` = 'yearofpassing' 
     JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id 
          AND `w_city`.`meta_key` = 'u_city'
     JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id` 
          AND `w_course`.`meta_key` = 'us_course'
     WHERE 
         `w_name`.`meta_value` = '$us_name' AND         
         `w_year`.meta_value   = '$us_yearselect' AND 
         `w_city`.`meta_value` = '$us_reg' AND 
         `w_course`.`meta_value` = '$us_course'

Other thing: Recommend to use prepared statements, because mysql_* functions is not SQL injection save, and will be deprecated. If you want to change your code the less as possible, you can use mysqli_ functions: http://php.net/manual/en/book.mysqli.php

Recommendation:

Use indexes in this table. user_id highly recommend to be and index, and recommend to be the meta_key AND meta_value too, for faster run of query.

The explain:

If you use AND you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.

Tests: Table Data:

          PRIMARY                 INDEX
      int       varchar(255)    varchar(255)
       /                \           |
  +---------+---------------+-----------+
  | user_id | meta_key      | meta_value|
  +---------+---------------+-----------+
  | 1       | first_name    | Kovge     |
  +---------+---------------+-----------+
  | 1       | yearofpassing | 2012      |
  +---------+---------------+-----------+
  | 1       | u_city        | GaPa      |
  +---------+---------------+-----------+
  | 1       | us_course     | PHP       |
  +---------+---------------+-----------+

The result of Query with $us_name='Kovge' $us_yearselect='2012' $us_reg='GaPa', $us_course='PHP':

 +---------+
 | user_id |
 +---------+
 | 1       |
 +---------+

So it should works.

The I/O operation has been aborted because of either a thread exit or an application request

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

Python Script execute commands in Terminal

You should also look into commands.getstatusoutput

This returns a tuple of length 2.. The first is the return integer ( 0 - when the commands is successful ) second is the whole output as will be shown in the terminal.

For ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

Detecting which UIButton was pressed in a UITableView

SWIFT 2 UPDATE

Here's how to find out which button was tapped + send data to another ViewController from that button's indexPath.row as I'm assuming that's the point for most!

@IBAction func yourButton(sender: AnyObject) {


     var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(position)
        let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
        UITableViewCell
        print(indexPath?.row)
        print("Tap tap tap tap")

    }

For those who are using a ViewController class and added a tableView, I'm using a ViewController instead of a TableViewController so I manually added the tableView in order to access it.

Here is the code for passing data to another VC when tapping that button and passing the cell's indexPath.row

@IBAction func moreInfo(sender: AnyObject) {

    let yourOtherVC = self.storyboard!.instantiateViewControllerWithIdentifier("yourOtherVC") as! YourOtherVCVIewController



    var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(position)
    let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
    UITableViewCell
    print(indexPath?.row)
    print("Button tapped")


    yourOtherVC.yourVarName = [self.otherVCVariable[indexPath!.row]]

    self.presentViewController(yourNewVC, animated: true, completion: nil)

}

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.

Okay, I got it working using Android Developers guide.

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);

  // creating an OkHttpClient that uses our SSLSocketFactory
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter that uses this custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

Afaik, the .crt file is your public key and the .key file is your private key.

As I can see, you already have a .cert file, which is the same, so try to use it.


PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:

echo -n | openssl s_client -connect your.server.com:443 | \
  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt

Just replace the your.server.com and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.

Eclipse error: indirectly referenced from required .class files?

I got this exception because eclipse was working in a different version of jdk, just changed to the correct, clean and build and worked!

How do you sort a dictionary by value?

You can sort the Dictionary by value and get the result in dictionary using the code below:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

How can I find where I will be redirected using cURL?

Sometimes you need to get HTTP headers but at the same time you don't want return those headers.**

This skeleton takes care of cookies and HTTP redirects using recursion. The main idea here is to avoid return HTTP headers to the client code.

You can build a very strong curl class over it. Add POST functionality, etc.

<?php

class curl {

  static private $cookie_file            = '';
  static private $user_agent             = '';  
  static private $max_redirects          = 10;  
  static private $followlocation_allowed = true;

  function __construct()
  {
    // set a file to store cookies
    self::$cookie_file = 'cookies.txt';

    // set some general User Agent
    self::$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';

    if ( ! file_exists(self::$cookie_file) || ! is_writable(self::$cookie_file))
    {
      throw new Exception('Cookie file missing or not writable.');
    }

    // check for PHP settings that unfits
    // correct functioning of CURLOPT_FOLLOWLOCATION 
    if (ini_get('open_basedir') != '' || ini_get('safe_mode') == 'On')
    {
      self::$followlocation_allowed = false;
    }    
  }

  /**
   * Main method for GET requests
   * @param  string $url URI to get
   * @return string      request's body
   */
  static public function get($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // this function is in charge of output request's body
    // so DO NOT include HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 0);

    if (self::$followlocation_allowed)
    {
      // if PHP settings allow it use AUTOMATIC REDIRECTION
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($process, CURLOPT_MAXREDIRS, self::$max_redirects); 
    }
    else
    {
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, false);
    }

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    // test for redirection HTTP codes
    $code = curl_getinfo($process, CURLINFO_HTTP_CODE);
    if ($code == 301 || $code == 302)
    {
      curl_close($process);

      try
      {
        // go to extract new Location URI
        $location = self::_parse_redirection_header($url);
      }
      catch (Exception $e)
      {
        throw $e;
      }

      // IMPORTANT return 
      return self::get($location);
    }

    curl_close($process);

    return $return;
  }

  static function _set_basic_options($process)
  {

    curl_setopt($process, CURLOPT_USERAGENT, self::$user_agent);
    curl_setopt($process, CURLOPT_COOKIEFILE, self::$cookie_file);
    curl_setopt($process, CURLOPT_COOKIEJAR, self::$cookie_file);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($process, CURLOPT_VERBOSE, 1);
    // curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
    // curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
  }

  static function _parse_redirection_header($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // NOW we need to parse HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 1);

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    curl_close($process);

    if ( ! preg_match('#Location: (.*)#', $return, $location))
    {
      throw new Exception('No Location found');
    }

    if (self::$max_redirects-- <= 0)
    {
      throw new Exception('Max redirections reached trying to get: ' . $url);
    }

    return trim($location[1]);
  }

}

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to find the length of an array in shell?

$ a=(1 2 3 4)
$ echo ${#a[@]}
4

How do you return the column names of a table?

I'm not sure if the syscolumns.colid value is the same as the 'ORDINAL_POSITION' value returned as part of sp_columns, but in what follows I am using it that way - hope I'm not misinforming...

Here's a slight variation on some of the other answers I've found - I use this because the 'position' or order of the column in the table is important in my application - I basically need to know 'What is column (n) called?'

sp_columns returns a whole bunch of extraneous stuff, and I'm handier with a select than T-SQL functions, so I went this route:

select    
  syscolumns.name, 
  syscolumns.colid    
from     
  sysobjects, syscolumns  
where 
  sysobjects.id = syscolumns.id and   
  sysobjects.xtype = 'u' and   
  sysobjects.name = '<YOUR_TABLE>' 
order by syscolumns.colid 

CSS list item width/height does not work

Remove the <br> from the .navcontainer-top li styles.

Play sound on button click android

This is the most important part in the code provided in the original post.

Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        mp.start();
    }
});

To explain it step by step:

Button one = (Button) this.findViewById(R.id.button1);

First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.

final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);

This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.

one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        //code
    }
});

Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.

public void onClick(View v) {
    mp.start();
}

To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.

There, you can now play a sound on button click in Android!


Bonus part:

As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        //code
    }
});

Inside the onCompletion method, we release it like so:

public void onCompletion(MediaPlayer mp) {
    mp.release();
}

There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.


Original Post

First. You should put your statements inside a block, and in this case the onCreate method.

Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.

Third, put the logic to play the sound inside the onClick.

In summary:

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BasicScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);

        Button one = (Button)this.findViewById(R.id.button1);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
        one.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

Default passwords of Oracle 11g?

It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.

  1. Ensure your user account is a member of the dba group. How you do this depends on what OS you are running.

  2. Enter sqlplus / as sysdba in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.

  3. Once you're logged in, you can then enter

    alter user SYS identified by "newpassword";
    

    to reset the SYS password, and similarly for SYSTEM.

(Note: I haven't tried any of this on Oracle 12c; I'm assuming they haven't changed things since Oracle 11g.)

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

How to map a composite key with JPA and Hibernate?

The primary key class must define equals and hashCode methods

  1. When implementing equals you should use instanceof to allow comparing with subclasses. If Hibernate lazy loads a one to one or many to one relation, you will have a proxy for the class instead of the plain class. A proxy is a subclass. Comparing the class names would fail.
    More technically: You should follow the Liskows Substitution Principle and ignore symmetricity.
  2. The next pitfall is using something like name.equals(that.name) instead of name.equals(that.getName()). The first will fail, if that is a proxy.

http://www.laliluna.de/jpa-hibernate-guide/ch06s06.html

Angular bootstrap datepicker date format does not format ng-model value

The datepicker (and datepicker-popup) directive requires that the ng-model be a Date object. This is documented here.

If you want ng-model to be a string in specific format, you should create a wrapper directive. Here is an example (Plunker):

_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    angular_x000D_
        .module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])_x000D_
        .controller('MyController', MyController)_x000D_
        .directive('myDatepicker', myDatepickerDirective);_x000D_
_x000D_
    MyController.$inject = ['$scope'];_x000D_
_x000D_
    function MyController ($scope) {_x000D_
      $scope.dateFormat = 'dd MMMM yyyy';_x000D_
      $scope.myDate = '30 Jun 2017';_x000D_
    }_x000D_
_x000D_
    myDatepickerDirective.$inject = ['uibDateParser', '$filter'];_x000D_
_x000D_
    function myDatepickerDirective (uibDateParser, $filter) {_x000D_
        return {_x000D_
            restrict: 'E',_x000D_
            scope: {_x000D_
                name: '@',_x000D_
                dateFormat: '@',_x000D_
                ngModel: '='_x000D_
            },_x000D_
            required: 'ngModel',_x000D_
            link: function (scope) {_x000D_
_x000D_
                var isString = angular.isString(scope.ngModel) && scope.dateFormat;_x000D_
_x000D_
                if (isString) {_x000D_
                    scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);_x000D_
                } else {_x000D_
                    scope.internalModel = scope.ngModel;_x000D_
                }_x000D_
_x000D_
                scope.open = function (event) {_x000D_
                    event.preventDefault();_x000D_
                    event.stopPropagation();_x000D_
                    scope.isOpen = true;_x000D_
                };_x000D_
_x000D_
                scope.change = function () {_x000D_
                    if (isString) {_x000D_
                        scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);_x000D_
                    } else {_x000D_
                        scope.ngModel = scope.internalModel;_x000D_
                    }_x000D_
                };_x000D_
_x000D_
            },_x000D_
            template: [_x000D_
                '<div class="input-group">',_x000D_
                    '<input type="text" readonly="true" style="background:#fff" name="{{name}}" class="form-control" uib-datepicker-popup="{{dateFormat}}" ng-model="internalModel" is-open="isOpen" ng-click="open($event)" ng-change="change()">',_x000D_
                    '<span class="input-group-btn">',_x000D_
                        '<button class="btn btn-default" ng-click="open($event)">&nbsp;<i class="glyphicon glyphicon-calendar"></i>&nbsp;</button>',_x000D_
                    '</span>',_x000D_
                '</div>'_x000D_
            ].join('')_x000D_
        }_x000D_
    }_x000D_
_x000D_
})();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>_x000D_
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>_x000D_
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>_x000D_
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>_x000D_
    <script src="example.js"></script>_x000D_
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">_x000D_
  </head>_x000D_
_x000D_
  <body ng-app="myExample">_x000D_
    <div ng-controller="MyController">_x000D_
      <p>_x000D_
        Date format: {{dateFormat}}_x000D_
      </p>_x000D_
      <p>_x000D_
        Value: {{myDate}}_x000D_
      </p>_x000D_
      <p>_x000D_
        <my-datepicker ng-model="myDate" date-format="{{dateFormat}}"></my-datepicker>_x000D_
      </p>_x000D_
    </div>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

Xml serialization - Hide null values

private static string ToXml(Person obj)
{
  XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  namespaces.Add(string.Empty, string.Empty);

  string retval = null;
  if (obj != null)
  {
    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
    {
      new XmlSerializer(obj.GetType()).Serialize(writer, obj,namespaces);
    }
    retval = sb.ToString();
  }
  return retval;
}

Iterating through a list to render multiple widgets in Flutter?

The Dart language has aspects of functional programming, so what you want can be written concisely as:

List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();

Read this as "take each name in list and map it to a Text and form them back into a List".

How do I create an executable in Visual Studio 2013 w/ C++?

Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->

PHPUnit assert that an exception was thrown?

An alternative way can be the following:

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');

Please ensure that your test class extents \PHPUnit_Framework_TestCase.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

php return 500 error but no error log

Another case which happened to me, is I did a CURL to some of my pages, and got internal server error and nothing was in the apache logs, even when I enabled all error reporting.

My problem was that in the CURL I set curl_setopt($CR, CURLOPT_FAILONERROR, true);

Which then didn't show me my error, though there was one, this happened because the error was on a framework level and not a PHP one, so it didn't appear in the logs.

How to open Atom editor from command line in OS X?

The symlink solution for this stopped working for me in zsh today. I ended up creating an alias in my .zshrc file instead:

alias atom='sh /Applications/Atom.app/Contents/Resources/app/atom.sh'

How to manually set REFERER header in Javascript?

I think that understanding why you can't change the referer header might help people reading this question.

From this page: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name

From that link:

A forbidden header name is the name of any HTTP header that cannot be modified programmatically...

Modifying such headers is forbidden because the user agent retains full control over them.

Forbidden header names ... are one of the following names:

...

Referer

...

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

You should have name column as a unique constraint. here is a 3 lines of code to change your issues

  1. First find out the primary key constraints by typing this code

    \d table_name
    

    you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)

  2. Drop the constraint:

    ALTER TABLE table_name DROP CONSTRAINT some_constraint
    
  3. Add a new primary key column with existing one:

    ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
    

That's All.

How to find the serial port number on Mac OS X?

Try this: ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"

How to change PHP version used by composer

If anyone is still having trouble, remember you can run composer with any php version that you have installed e.g. $ php7.3 -f /usr/local/bin/composer update

Use which composer command to help locate the composer executable.

How do I add multiple conditions to "ng-disabled"?

You should be able to && the conditions:

ng-disabled="condition1 && condition2"

How to remove all the occurrences of a char in c++ string

This is how I do it:

std::string removeAll(std::string str, char c) {
    size_t offset = 0;
    size_t size = str.size();

    size_t i = 0;
    while (i < size - offset) {
        if (str[i + offset] == c) {
            offset++;
        }

        if (offset != 0) {
            str[i] = str[i + offset];
        }

        i++;
    }

    str.resize(size - offset);
    return str;
}

Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

When should one use a spinlock instead of mutex?

Spinlock and Mutex synchronization mechanisms are very common today to be seen.

Let's think about Spinlock first.

Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?

Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:

In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)

In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How can I convert string date to NSDate?

Below are some string to date format converting options can be usedin swift iOS.

  1. Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
  2. 12/27/2018 format= MM/dd/yyyy
  3. 12-27-2018 09:59 format= MM-dd-yyyy HH:mm
  4. Dec 27, 9:59 AM format= MMM d, h:mm a
  5. December 2018 format= MMMM yyyy
  6. Dec 27, 2018 format= MMM d, yyyy
  7. Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
  8. 2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
  9. 27.12.18 format= dd.MM.yy
  10. 09:59:19.815 format= HH:mm:ss.SSS

Passing string parameter in JavaScript function

Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.

And replace

onclick='myfunction(\''" + name + "'\')'

With

onclick='myfunction(myname)'

Working example:

_x000D_
_x000D_
var myname = "Mathew";_x000D_
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');_x000D_
function myfunction(name) {_x000D_
    alert(name);_x000D_
}
_x000D_
_x000D_
_x000D_

Converting a string to int in Groovy

Several ways to achieve this. Examples are as below

a. return "22".toInteger()
b. if("22".isInteger()) return "22".toInteger()
c. return "22" as Integer()
d. return Integer.parseInt("22")

Hope this helps

How to check undefined in Typescript

From Typescript 3.7 on, you can also use nullish coalescing:

let x = foo ?? bar();

Which is the equivalent for checking for null or undefined:

let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

While not exactly the same, you could write your code as:

var uemail = localStorage.getItem("useremail") ?? alert('Undefined');

Cannot create Maven Project in eclipse

Just delete the ${user.home}/.m2/repository/org/apache/maven/archetypes to refresh all files needed, it worked fine to me!

Can a java lambda have more than 1 parameter?

Some lambda function :

import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;

public class TestLambda {

@Test
public void testLambda() {

    System.out.println("test some lambda function");

    ////////////////////////////////////////////
    //1-any input | any output:
    //lambda define:
    Runnable lambda1 = () -> System.out.println("no parameter");
    //lambda execute:
    lambda1.run();


    ////////////////////////////////////////////
    //2-one input(as ActionEvent) | any output:
    //lambda define:
    ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
    //lambda execute:
    lambda2.actionPerformed(null);


    ////////////////////////////////////////////
    //3-one input | by output(as Integer):
    //lambda define:
    Function<String, Integer> lambda3 = (p1) -> {
        System.out.println("one parameters: " + p1);
        return 10;
    };
    //lambda execute:
    lambda3.apply("test");


    ////////////////////////////////////////////
    //4-two input | any output
    //lambda define:
    TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
    };
    //lambda execute:
    lambda4.apply("param1", 10);


    ////////////////////////////////////////////
    //5-two input | by output(as Integer)
    //lambda define:
    TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
        return p1 + p2;
    };
    //lambda execute:
    lambda5.apply(10, 20);


    ////////////////////////////////////////////
    //6-three input(Integer,Integer,String) | by output(as Integer)
    //lambda define:
    ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
        System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
        return p1 + p2 + p3;
    };
    //lambda execute:
    lambda6.apply(10, 20, 30);

}


@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
    public void apply(T t, U u);
}

@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
    public T apply(T t, U u);
}

@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
    public Integer apply(M m, N n, O o);
}
}

How to run a PowerShell script

In case you want to run a PowerShell script with Windows Task Scheduler, please follow the steps below:

  1. Create a task

  2. Set Program/Script to Powershell.exe

  3. Set Arguments to -File "C:\xxx.ps1"

It's from another answer, How do I execute a PowerShell script automatically using Windows task scheduler?.

HTML5 Pre-resize images before uploading

fd.append("image", dataurl);

This will not work. On PHP side you can not save file with this.

Use this code instead:

var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
  array.push(blobBin.charCodeAt(i));
}
var file = new Blob([new Uint8Array(array)], {type: 'image/png', name: "avatar.png"});

fd.append("image", file); // blob file

SQL Stored Procedure: If variable is not null, update statement

Yet another approach is ISNULL().

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = ISNULL(@ABC, [ABC]),
    [ABCD] = ISNULL(@ABCD, [ABCD])

The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.

select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

Take a full page screenshot with Firefox on the command-line

I think what you are looking for is a utility which enables you to save a complete page opened in your browser into a png file. Most probably you are looking for a utility like commandlineprint2.

After installing the extension, you just need to type the command:

firefox -print http://google.com -printfile ~/foo.png

How to use `subprocess` command with pipes

command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

What is the difference between field, variable, attribute, and property in Java POJOs?

  • variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;

//for example
int myInt;
String myString;
CustomClass myCustomClass;
  • field - member variable or data member. It is a variable inside a class(class variable or instance variable)

  • attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.

CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
  • property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin

For example Kotlin sample:

//field - Backing Field
class Person {
    var name: String = "default name"
        get() = field
        set(value) { field = value }
}

//using
val person = Person()
person.name = "Alex"    // setter is used
println(person.name)    // getter is used

[Swift variable, property...]

Automatically add all files in a folder to a target using CMake?

The answer by Kleist certainly works, but there is an important caveat:

When you write a Makefile manually, you might generate a SRCS variable using a function to select all .cpp and .h files. If a source file is later added, re-running make will include it.

However, CMake (with a command like file(GLOB ...)) will explicitly generate a file list and place it in the auto-generated Makefile. If you have a new source file, you will need to re-generate the Makefile by re-running cmake.

edit: No need to remove the Makefile.

How to fix ReferenceError: primordials is not defined in node

For anyone having same error for the same reason in ADOS CI Build:

This question was the first I found when looking for help. I have an ADOS CI build pipeline where first Node.js tool installer task is used to install Node. Then npm task is used to install gulp (npm install -g gulp). Then the following Gulp task runs default-task from gulpfile.js. There's some gulp-sass stuff in it.

When I changed the Node.js tool to install 12.x latest node instead of an older one and the latest gulp version was 4.0.2. The result was the same error as described in the question.

What worked for me in this case was to downgrade node.js to latest 11.x version as was already suggested by Alphonse R. Dsouza and Aymen Yaseen. In this case though there's no need to use any commands they suggested, but rather just set the Node.js tool installer version spec to latest Node version from 11.x.

enter image description here

The exact version of Node.js that got installed and is working was 11.15.0. I didn't have to downgrade the Gulp.

Draw on HTML5 Canvas using a mouse

Googled this ("html5 canvas paint program"). Looks like what you need.

http://dev.opera.com/articles/view/html5-canvas-painting/

Composer could not find a composer.json

In my case, I did not copy all project files to the folder where I was running composer install. So do:

  1. Copy your project files (including the composer.json) to folder
  2. open CMD (I am using ConEmu), navigate to the new folder, run composer install from there
  3. It should work or throw errors in case the json file is not correct.

If you just want to make composer run, create a new composer.json file with for example:

{
    "require": {
        "php": ">=5.3.2"
    }
}

Then run composer install.

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

If you made a virtual env, then deleted that python installation, you'll get the same error. Just rm -r your venv folder, then recreate it with a valid python location and do pip install -r requirements.txt and you'll be all set (assuming you got your requirements.txt right).

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

How to get ASCII value of string in C#

This should work:

string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
    Console.WriteLine(b);
}

align right in a table cell with CSS

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

MySQL - UPDATE query with LIMIT

I would suggest a two step query

I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id, substitute with whatever your PK is called.

1 - figure out the primary key number for column 1000.

SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000

2 - update the table.

UPDATE smartmeter_usage.users_reporting SET panel_id = 3 
WHERE panel_id IS NULL AND id >= @id 
ORDER BY id 
LIMIT 1000

Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.

How to get pip to work behind a proxy server

At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.

export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi

Parsing GET request parameters in a URL that contains another URL

I had a similar problem and ended up using parse_url and parse_str, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:

$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);

function so_5645412_url_params($url) {
    $url_comps = parse_url($url);
    $query = $url_comps['query'];

    $args = array();
    parse_str($query, $args);

    return $args;
}

$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )

"starting Tomcat server 7 at localhost has encountered a prob"

to overcome this kind of problem follow the steps below:

  • open command prompt.
  • c:\Users\CGITS_04> netstat -o -n -a | findstr 0.0:80
  • then you can see a list of process that is currently using port 80.
  • open task manager->search the process-> select and end process.
  • Now open eclipse and start tomcat.
  • happy coding!

How can I transform string to UTF-8 in C#?

Use the below code snippet to get bytes from csv file

protected byte[] GetCSVFileContent(string fileName)
    {
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
        {
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }
        string allines = sb.ToString();


        UTF8Encoding utf8 = new UTF8Encoding();


        var preamble = utf8.GetPreamble();

        var data = utf8.GetBytes(allines);


        return data;
    }

Call the below and save it as an attachment

           Encoding csvEncoding = Encoding.UTF8;
                   //byte[] csvFile = GetCSVFileContent(FileUpload1.PostedFile.FileName);
          byte[] csvFile = GetCSVFileContent("Your_CSV_File_NAme");


        string attachment = String.Format("attachment; filename={0}.csv", "uomEncoded");

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "text/csv";
        Response.ContentEncoding = csvEncoding;
        Response.AppendHeader("Content-Disposition", attachment);
        //Response.BinaryWrite(csvEncoding.GetPreamble());
        Response.BinaryWrite(csvFile);
        Response.Flush();
        Response.End();

Getting "conflicting types for function" in C, why?

You are trying to call do_something before you declare it. You need to add a function prototype before your printf line:

char* do_something(char*, const char*);

Or you need to move the function definition above the printf line. You can't use a function before it is declared.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

I had to add a user environment variable, HOME, with C:\Users\<your user name> by going to System, Advanced System Settings, in the System Properties window, the Advanced tab, Environment Variables...

Then in my C:\Users\<your user name> I created the file .bashrc, e.g., touch .bashrc and added the desired aliases.

How to sleep the thread in node.js without affecting other threads?

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

How to picture "for" loop in block representation of algorithm

What's a "block scheme"?

If I were drawing it, I might draw a box with "for each x in y" written in it.

If you're drawing a flowchart, there's always a loop with a decision box.

Nassi-Schneiderman diagrams have a loop construct you could use.

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

Unix command to find lines common in two files

To easily apply the comm command to unsorted files, use Bash's process substitution:

$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321

So the files abc and def have one line in common, the one with "132". Using comm on unsorted files:

$ comm abc def
123
    132
567
132
    777
    321
$ comm -12 abc def # No output! The common line is not found
$

The last line produced no output, the common line was not discovered.

Now use comm on sorted files, sorting the files with process substitution:

$ comm <( sort abc ) <( sort def )
123
            132
    321
567
    777
$ comm -12 <( sort abc ) <( sort def )
132

Now we got the 132 line!

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

What is href="#" and why is it used?

About hyperlinks:

The main use of anchor tags - <a></a> - is as hyperlinks. That basically means that they take you somewhere. Hyperlinks require the href property, because it specifies a location.

Hash:

A hash - # within a hyperlink specifies an html element id to which the window should be scrolled.

href="#some-id" would scroll to an element on the current page such as <div id="some-id">.

href="//site.com/#some-id" would go to site.com and scroll to the id on that page.

Scroll to Top:

href="#" doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#" will move the scroll position to the top.

See this demo.

This is the expected behavior according to the w3 documentation.

Hyperlink placeholders:

An example where a hyperlink placeholder makes sense is within template previews. On single page demos for templates, I have often seen <a href="#"> so that the anchor tag is a hyperlink, but doesn't go anywhere. Why not leave the href property blank? A blank href property is actually a hyperlink to the current page. In other words, it will cause a page refresh. As I discussed, href="#" is also a hyperlink, and causes scrolling. Therefore, the best solution for hyperlink placeholders is actually href="#!" The idea here is that there hopefully isn't an element on the page with id="!" (who does that!?) and the hyperlink therefore refers to nothing - so nothing happens.

About anchor tags:

Another question that you may be wondering is, "Why not just leave the href property off?". A common response I've heard is that the href property is required, so it "should" be present on anchors. This is FALSE! The href property is required only for an anchor to actually be a hyperlink! Read this from w3. So, why not just leave it off for placeholders? Browsers render default styles for elements and will change the default style of an anchor tag that doesn't have the href property. Instead, it will be considered like regular text. It even changes the browser's behavior regarding the element. The status bar (bottom of the screen) will not be displayed when hovering on an anchor without the href property. It is best to use a placeholder href value on an anchor to ensure it is treated as a hyperlink.

See this demo demonstrating style and behavior differences.

Iterating through a string word by word

When you do -

for word in string:

You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split() , and then iterate through that . Example -

my_string = "this is a string"
for word in my_string.split():
    print (word)

Please note, str.split() , without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).

What resources are shared between threads?

Besides global memory, threads also share a number of other attributes (i.e., these attributes are global to a process, rather than specific to a thread). These attributes include the following:

  • process ID and parent process ID;
  • process group ID and session ID;
  • controlling terminal;
  • process credentials (user and group IDs);
  • open file descriptors;
  • record locks created using fcntl();
  • signal dispositions;
  • file system–related information: umask, current working directory, and root directory;
  • interval timers (setitimer()) and POSIX timers (timer_create());
  • System V semaphore undo (semadj) values (Section 47.8);
  • resource limits;
  • CPU time consumed (as returned by times());
  • resources consumed (as returned by getrusage()); and
  • nice value (set by setpriority() and nice()).

Among the attributes that are distinct for each thread are the following:

  • thread ID (Section 29.5);
  • signal mask;
  • thread-specific data (Section 31.3);
  • alternate signal stack (sigaltstack());
  • the errno variable;
  • floating-point environment (see fenv(3));
  • realtime scheduling policy and priority (Sections 35.2 and 35.3);
  • CPU affinity (Linux-specific, described in Section 35.4);
  • capabilities (Linux-specific, described in Chapter 39); and
  • stack (local variables and function call linkage information).

Excerpt From: The Linux Programming Interface: A Linux and UNIX System Programming Handbook , Michael Kerrisk, page 619

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

Android: Share plain text using intent (to all messaging apps)

New way of doing this would be using ShareCompat.IntentBuilder like so:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

If you have any more questions about using ShareCompat, I highly recommend this great article from Ian Lake, an Android Developer Advocate at Google, for a more complete breakdown of the API. As you'll notice, I borrowed some of this example from that article.

If that article doesn't answer all of your questions, there is always the Javadoc itself for ShareCompat.IntentBuilder on the Android Developers website. I added more to this example of the API's usage on the basis of clemantiano's comment.

Converting a UNIX Timestamp to Formatted Date String

<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>

What is a method group in C#?

The first result in your MSDN search said:

The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke

my understanding is that basically because when you just write someInteger.ToString, it may refer to:

Int32.ToString(IFormatProvider) 

or it can refer to:

Int32.ToString()

so it is called a method group.

How do I get the calling method name and type using reflection?

It's actually something that can be done using a combination of the current stack-trace data, and reflection.

public void MyMethod()
{
     StackTrace stackTrace = new System.Diagnostics.StackTrace();
     StackFrame frame = stackTrace.GetFrames()[1];
     MethodInfo method = frame.GetMethod();
     string methodName = method.Name;
     Type methodsClass = method.DeclaringType;
}

The 1 index on the StackFrame array will give you the method which called MyMethod

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

If you're behind a proxy, you should use X-Forwarded-For: http://en.wikipedia.org/wiki/X-Forwarded-For

It is an IETF draft standard with wide support:

The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.

If not, here are a couple other common headers I've seen:

Function pointer as a member of a C struct

You can use also "void*" (void pointer) to send an address to the function.

typedef struct pstring_t {
    char * chars;
    int(*length)(void*);
} PString;

int length(void* self) {
    return strlen(((PString*)self)->chars);
}

PString initializeString() {
    PString str;
    str.length = &length;
    return str;
}

int main()
{
    PString p = initializeString();

    p.chars = "Hello";

    printf("Length: %i\n", p.length(&p));

    return 0;
}

Output:

Length: 5

How do I use valgrind to find memory leaks?

How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.

Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any parameters to the program).

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

The flags are, in short:

  • --leak-check=full: "each individual leak will be shown in detail"
  • --show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.
  • --track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.
  • --verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.
  • --log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)

Let's take a look at the C code I wrote too:

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

Well, there were 5 bytes lost. How did it happen? The error report just says main and malloc. In a larger program, that would be seriously troublesome to hunt down. This is because of how the executable was compiled. We can actually get line-by-line details on what went wrong. Recompile your program with a debug flag (I'm using gcc here):

gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it

Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)

Techniques for Debugging Memory Leaks & Errors

  • Make use of www.cplusplus.com! It has great documentation on C/C++ functions.
  • General advice for memory leaks:
    • Make sure your dynamically allocated memory does in fact get freed.
    • Don't allocate memory and forget to assign the pointer.
    • Don't overwrite a pointer with a new one unless the old memory is freed.
  • General advice for memory errors:
    • Access and write to addresses and indices you're sure belong to you. Memory errors are different from leaks; they're often just IndexOutOfBoundsException type problems.
    • Don't access or write to memory after freeing it.
  • Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

    • List out the functions in your code that depend on/are dependent on the "offending" code that has the memory error. Follow the program's execution (maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.
    • Try commenting out the "offending" block of code (within reason, so your code still compiles). If the Valgrind error goes away, you've found where it is.
  • If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

And the code:

#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}

As a teaching assistant, I've seen this mistake often. The student makes use of a local variable and forgets to update the original pointer. The error here is noticing that realloc can actually move the allocated memory somewhere else and change the pointer's location. We then leave resizeArray without telling array->data where the array was moved to.

Invalid write

1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* alphabet = calloc(26, sizeof(char));

    for(uint8_t i = 0; i < 26; i++) {
        *(alphabet + i) = 'A' + i;
    }
    *(alphabet + 26) = '\0'; //null-terminate the string?

    free(alphabet);
    return 0;
}

Notice that Valgrind points us to the commented line of code above. The array of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid write—it's out of bounds. An invalid write is a common result of off-by-one errors. Look at the left side of your assignment operation.

Invalid read

1 errors in context 1 of 1:
Invalid read of size 1
   at 0x400602: main (main.c:9)
 Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x4005E1: main (main.c:6)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* destination = calloc(27, sizeof(char));
    char* source = malloc(26 * sizeof(char));

    for(uint8_t i = 0; i < 27; i++) {
        *(destination + i) = *(source + i); //Look at the last iteration.
    }

    free(destination);
    free(source);
    return 0;
}

Valgrind points us to the commented line above. Look at the last iteration here, which is
*(destination + 26) = *(source + 26);. However, *(source + 26) is out of bounds again, similarly to the invalid write. Invalid reads are also a common result of off-by-one errors. Look at the right side of your assignment operation.


The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.

Jansson: a JSON library

#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}

This is a simple program: it reads a JSON string and parses it. In the making, we use library calls to do the parsing for us. Jansson makes the necessary allocations dynamically since JSON can contain nested structures of itself. However, this doesn't mean we decref or "free" the memory given to us from every function. In fact, this code I wrote above throws both an "Invalid read" and an "Invalid write". Those errors go away when you take out the decref line for value.

Why? The variable value is considered a "borrowed reference" in the Jansson API. Jansson keeps track of its memory for you, and you simply have to decref JSON structures independent of each other. The lesson here: read the documentation. Really. It's sometimes hard to understand, but they're telling you why these things happen. Instead, we have existing questions about this memory error.

SDL: a graphics and gaming library

#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?
It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!


Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

Make iframe automatically adjust height according to the contents without using scrollbar?

This works for me (also with multiple iframes on one page):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});

raw_input function in Python

raw_input is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input. Say, a=input(5) returns a as an integer with value 5 whereas a=raw_input(5) returns a as a string of "5"

Insert NULL value into INT column

If column is not NOT NULL (nullable).

You just put NULL instead of value in INSERT statement.

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

creating custom tableview cells in swift

Last Updated Version is with xCode 6.1

class StampInfoTableViewCell: UITableViewCell{


@IBOutlet weak var stampDate: UILabel!
@IBOutlet weak var numberText: UILabel!


override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}

required init(coder aDecoder: NSCoder) {
    //fatalError("init(coder:) has not been implemented")
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}
}

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I had a similar error but for me it was react-router. Solved it by installing types for it.

npm install --save @types/react-router

Error:

(6,30): error TS7016: Could not find a declaration file for module 'react-router'. '\node_modules\react-router\index.js' implicitly has an 'any' type.

If you would like to disable it site wide you can instead edit tsconfig.json and set noImplicitAny to false.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Your firewall blocked port 27017 which used to connect to MongoDB.

Try to find which firewall is being used in your system, e.g. in my case is csf, config file placed at

/etc/csf/csf.conf

find TCP_IN & TCP_OUT as follow and add port 27017 to allowed incoming and outgoing ports

# Allow incoming TCP ports
TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2222,27017"

# Allow outgoing TCP ports
TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995,2222,27017"

Save config file and restart csf to apply it:

csf -r

How to get the difference between two arrays in JavaScript?

function diff(arr1, arr2) {
  var filteredArr1 = arr1.filter(function(ele) {
    return arr2.indexOf(ele) == -1;
  });

  var filteredArr2 = arr2.filter(function(ele) {
    return arr1.indexOf(ele) == -1;
  });
  return filteredArr1.concat(filteredArr2);
}

diff([1, "calf", 3, "piglet"], [1, "calf", 3, 4]); // Log ["piglet",4]

Detect & Record Audio in Python

import pyaudio
import wave
from array import array

FORMAT=pyaudio.paInt16
CHANNELS=2
RATE=44100
CHUNK=1024
RECORD_SECONDS=15
FILE_NAME="RECORDING.wav"

audio=pyaudio.PyAudio() #instantiate the pyaudio

#recording prerequisites
stream=audio.open(format=FORMAT,channels=CHANNELS, 
                  rate=RATE,
                  input=True,
                  frames_per_buffer=CHUNK)

#starting recording
frames=[]

for i in range(0,int(RATE/CHUNK*RECORD_SECONDS)):
    data=stream.read(CHUNK)
    data_chunk=array('h',data)
    vol=max(data_chunk)
    if(vol>=500):
        print("something said")
        frames.append(data)
    else:
        print("nothing")
    print("\n")


#end of recording
stream.stop_stream()
stream.close()
audio.terminate()
#writing to file
wavfile=wave.open(FILE_NAME,'wb')
wavfile.setnchannels(CHANNELS)
wavfile.setsampwidth(audio.get_sample_size(FORMAT))
wavfile.setframerate(RATE)
wavfile.writeframes(b''.join(frames))#append frames recorded to file
wavfile.close()

I think this will help.It is a simple script which will check if there is a silence or not.If silence is detected it will not record otherwise it will record.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Jenkins: Failed to connect to repository

Make sure that the RSA host key and the IP of the bitbucket server is added to the 'known hosts' file. The contents should look like

bitbucket.org,xx.xx.xx.xx ssh-rsa host_key

Remember to change ownership to Jenkins for all the files in /var/lib/jenkins/.ssh/

How to install mod_ssl for Apache httpd?

Try installing mod_ssl using following command:

yum install mod_ssl

and then reload and restart your Apache server using following commands:

systemctl reload httpd.service
systemctl restart httpd.service

This should work for most of the cases.

Best way to reset an Oracle sequence to the next value in an existing column?

Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.

You can use an ALTER TABLE Statement to modify "START WITH" of the identity.

ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

How do I pass JavaScript values to Scriptlet in JSP?

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.

can't load package: package .: no buildable Go source files

you can try to download packages from mod

go get -v all

Quadratic and cubic regression in Excel

You need to use an undocumented trick with Excel's LINEST function:

=LINEST(known_y's, [known_x's], [const], [stats])

Background

A regular linear regression is calculated (with your data) as:

=LINEST(B2:B21,A2:A21)

which returns a single value, the linear slope (m) according to the formula:

enter image description here

which for your data:

enter image description here

is:

enter image description here

Undocumented trick Number 1

You can also use Excel to calculate a regression with a formula that uses an exponent for x different from 1, e.g. x1.2:

enter image description here

using the formula:

=LINEST(B2:B21, A2:A21^1.2)

which for you data:

enter image description here

is:

enter image description here

You're not limited to one exponent

Excel's LINEST function can also calculate multiple regressions, with different exponents on x at the same time, e.g.:

=LINEST(B2:B21,A2:A21^{1,2})

Note: if locale is set to European (decimal symbol ","), then comma should be replaced by semicolon and backslash, i.e. =LINEST(B2:B21;A2:A21^{1\2})

Now Excel will calculate regressions using both x1 and x2 at the same time:

enter image description here

How to actually do it

The impossibly tricky part there's no obvious way to see the other regression values. In order to do that you need to:

  • select the cell that contains your formula:

    enter image description here

  • extend the selection the left 2 spaces (you need the select to be at least 3 cells wide):

    enter image description here

  • press F2

  • press Ctrl+Shift+Enter

    enter image description here

You will now see your 3 regression constants:

  y = -0.01777539x^2 + 6.864151123x + -591.3531443

Bonus Chatter

I had a function that I wanted to perform a regression using some exponent:

y = m×xk + b

But I didn't know the exponent. So I changed the LINEST function to use a cell reference instead:

=LINEST(B2:B21,A2:A21^F3, true, true)

With Excel then outputting full stats (the 4th paramter to LINEST):

enter image description here

I tell the Solver to maximize R2:

enter image description here

And it can figure out the best exponent. Which for you data:

enter image description here

is:

enter image description here

Test a weekly cron job

Just do what cron does, run the following as root:

run-parts -v /etc/cron.weekly

... or the next one if you receive the "Not a directory: -v" error:

run-parts /etc/cron.weekly -v

Option -v prints the script names before they are run.

Finding the type of an object in C++

As others indicated you can use dynamic_cast. But generally using dynamic_cast for finding out the type of the derived class you are working upon indicates the bad design. If you are overriding a function that takes pointer of A as the parameter then it should be able to work with the methods/data of class A itself and should not depend on the the data of class B. In your case instead of overriding if you are sure that the method you are writing will work with only class B, then you should write a new method in class B.

Subset dataframe by multiple logical conditions of rows to remove

data <- data[-which(data[,1] %in% c("b","d","e")),]

Load resources from relative path using local html in uiwebview

@sdbrain's answer in Swift 3:

    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
    webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)

How to call a Python function from Node.js

The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.

Installation: npm install python-shell.

Running a simple Python script:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

Running a Python script with arguments and options:

var PythonShell = require('python-shell');

var options = {
  mode: 'text',
  pythonPath: 'path/to/python',
  pythonOptions: ['-u'],
  scriptPath: 'path/to/my/scripts',
  args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
  if (err) 
    throw err;
  // Results is an array consisting of messages collected during execution
  console.log('results: %j', results);
});

For the full documentation and source code, check out https://github.com/extrabacon/python-shell

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

Blade if(isset) is not working Laravel

@isset($usersType)
  // $usersType is defined and is not null...
@endisset

For a detailed explanation refer documentation:

In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

Output single character in C

As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.

What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.

Using printf is like using a machine gun to fire one bullet.

How to pass command line arguments to a rake task

In addition to answer by kch (I didn't find how to leave a comment to that, sorry):

You don't have to specify variables as ENV variables before the rake command. You can just set them as usual command line parameters like that:

rake mytask var=foo

and access those from your rake file as ENV variables like such:

p ENV['var'] # => "foo"

How do I resolve `The following packages have unmet dependencies`

First of all try this

sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove

If error still persists then do this

sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f

Afterwards try this again:

sudo apt-get install npm

But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a and remove them one-by-one . Let's say dependencies are on npm then go for this ,

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Then check for the dependencies problem again using sudo dpkg --configure -a and if it's all clear then you are done . Later on install npm again using this

v=8   # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

How do I use a regular expression to match any string, but at least 3 characters?

I tried find similiar as topic first post.

For my needs I find this

http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/

"\b[a-zA-Z0-9]{3}\b"

3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "

How to scroll page in flutter

Two way to add Scroll in page

1. Using SingleChildScrollView :

     SingleChildScrollView(
          child: Column(
            children: [
              Container(....),
              SizedBox(...),
              Container(...),
              Text(....)
            ],
          ),
      ),

2. Using ListView : ListView is default provide Scroll no need to add extra widget for scrolling

     ListView(
          children: [
            Container(..),
            SizedBox(..),
            Container(...),
            Text(..)
          ],
      ),

Trying to Validate URL Using JavaScript

If you're looking for a more reliable regex, check out RegexLib. Here's the page you'd probably be interested in:

http://regexlib.com/Search.aspx?k=url

As for the error messages showing while the person is still typing, change the event from keydown to blur and then it will only check once the person moves to the next element.

How do I format a number with commas in T-SQL?

This belongs in a comment to Phil Hunt's answer but alas I don't have the rep.

To strip the ".00" off the end of your number string, parsename is super-handy. It tokenizes period-delimited strings and returns the specified element, starting with the rightmost token as element 1.

SELECT PARSENAME(CONVERT(varchar, CAST(987654321 AS money), 1), 2)

Yields "987,654,321"

Ascending and Descending Number Order in java

int arr[] = { 12, 13, 54, 16, 25, 8, 78 };

for (int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.println(arr[i]);
}

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

How to set ObjectId as a data type in mongoose

My solution on using ObjectId

// usermodel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId


let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

UserSchema.set('autoIndex', true)

module.exports = mongoose.model('User', UserSchema)

Using mongoose's populate method

// controller.js

const mongoose = require('mongoose')
const User = require('./usermodel.js')

let query = User.findOne({ name: "Person" })

query.exec((err, user) => {
  if (err) {
     console.log(err)
  }

  user.events = events
  // user.events is now an array of events
})

How can I read a large text file line by line using Java?

You can read file data line by line as below:

String fileLoc = "fileLocationInTheDisk";

List<String> lines = Files.lines(Path.of(fileLoc), StandardCharsets.UTF_8).collect(Collectors.toList());

Determine the process pid listening on a certain port

The -p flag of netstat gives you PID of the process:

netstat -l -p

Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat. As we worked out during the discussion with @Cyclone, the line that does the job is:

sockstat -4 -l | grep :80 | awk '{print $3}' | head -1

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

Select row on click react-table

There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.


enter image description here



After importing the HOC you can then use it like this with the necessary methods:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

See here for more information:
https://github.com/tannerlinsley/react-table/tree/v6#selecttable

Here is a working example:
https://codesandbox.io/s/react-table-select-j9jvw

Assets file project.assets.json not found. Run a NuGet package restore

Another one, if by any chance you're using Dropbox, check for Conflicted in file names, do a search in your repo and delete all those conflicted files.

This may have happened if you have moved the files around.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

C++ error 'Undefined reference to Class::Function()'

Specify the Class Card for the constructor-:

void Card::Card(Card::Rank rank, Card::Suit suit) {

And also define the default constructor and destructor.

Sending email with gmail smtp with codeigniter email library

Perhaps your hosting server and email server are located at same place and you don't need to go for smtp authentication. Just keep every thing default like:

$config = array(        
    'protocol' => '',
    'smtp_host' => '',
    'smtp_port' => '',
    'smtp_user' => '[email protected]',
    'smtp_pass' => '**********'
    );

or

$config['protocol'] = '';
$config['smtp_host'] = '';
$config['smtp_port'] = ;
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'password';

it works for me.

Execute a stored procedure in another stored procedure in SQL server

Your sp_test: Return fullname

USE [MY_DB]
GO

IF (OBJECT_ID('[dbo].[sp_test]', 'P') IS NOT NULL)
DROP PROCEDURE [dbo].sp_test;
GO

CREATE PROCEDURE [dbo].sp_test 
@name VARCHAR(20),
@last_name VARCHAR(30),
@full_name VARCHAR(50) OUTPUT
AS

SET @full_name = @name + @last_name;

GO

In your sp_main

...
DECLARE @my_name VARCHAR(20);
DECLARE @my_last_name VARCHAR(30);
DECLARE @my_full_name VARCHAR(50);
...

EXEC sp_test @my_name, @my_last_name, @my_full_name OUTPUT;
...

Find Item in ObservableCollection without using a loop

I'd suggest storing these in a Hashtable. You can then access an item in the collection using the key, it's a much more efficient lookup.

var myObjects = new Hashtable();
myObjects.Add(yourObject.Title, yourObject);
...
var myRetrievedObject = myObjects["TargetTitle"];

What is the meaning of # in URL and how can I use that?

Yes, it is mainly to anchor your keywords, in particular the location of your page, so whenever URL loads the page with particular anchor name, then it will be pointed to that particular location.

For example, www.something.com/some_page/#computer if it is very lengthy page and you want to show exactly computer then you can anchor.

<p> adfadsf </p>
<p> adfadsf </p>
<p> adfadsf </p>
<a name="computer"></a><p> Computer topics </p>
<p> adfadsf </p>

Now the page will scroll and bring computer-related topics to the top.

What's the difference between SortedList and SortedDictionary?

Here is a tabular view if it helps...

From a performance perspective:

+------------------+---------+----------+--------+----------+----------+---------+
| Collection       | Indexed | Keyed    | Value  | Addition |  Removal | Memory  |
|                  | lookup  | lookup   | lookup |          |          |         |
+------------------+---------+----------+--------+----------+----------+---------+
| SortedList       | O(1)    | O(log n) | O(n)   | O(n)*    | O(n)     | Lesser  |
| SortedDictionary | O(n)**  | O(log n) | O(n)   | O(log n) | O(log n) | Greater |
+------------------+---------+----------+--------+----------+----------+---------+

  * Insertion is O(log n) for data that are already in sort order, so that each 
    element is added to the end of the list. If a resize is required, that element
    takes O(n) time, but inserting n elements is still amortized O(n log n).
    list.
** Available through enumeration, e.g. Enumerable.ElementAt.

From an implementation perspective:

+------------+---------------+----------+------------+------------+------------------+
| Underlying | Lookup        | Ordering | Contiguous | Data       | Exposes Key &    |
| structure  | strategy      |          | storage    | access     | Value collection |
+------------+---------------+----------+------------+------------+------------------+
| 2 arrays   | Binary search | Sorted   | Yes        | Key, Index | Yes              |
| BST        | Binary search | Sorted   | No         | Key        | Yes              |
+------------+---------------+----------+------------+------------+------------------+

To roughly paraphrase, if you require raw performance SortedDictionary could be a better choice. If you require lesser memory overhead and indexed retrieval SortedList fits better. See this question for more on when to use which.

You can read more here, here, here, here and here.