Programs & Examples On #Windows xp sp3

mysqldump Error 1045 Access denied despite correct passwords etc

In my case, I could access correctly with mysql.exe but not with mysqldump.exe.

The problem was the port for my connection was not the default one (3306) and I had to put the mysqldump port work with (-P3307)

mysqldump -u root -p -P3307 my_database > /path/backup_database

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

As a windows user, run an Admin powershell and launch :

python -m pip install --upgrade pip

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

How do I 'svn add' all unversioned files to SVN?

Since this post is tagged Windows, I thought I would work out a solution for Windows. I wanted to automate the process, and I made a bat file. I resisted making a console.exe in C#.

I wanted to add any files or folders which are not added in my repository when I begin the commit process.

The problem with many of the answers is they will list unversioned files which should be ignored as per my ignore list in TortoiseSVN.

Here is my hook setting and batch file which does that

Tortoise Hook Script:

"start_commit_hook".
(where I checkout) working copy path = C:\Projects
command line: C:\windows\system32\cmd.exe /c C:\Tools\SVN\svnadd.bat
(X) Wait for the script to finish
(X) (Optional) Hide script while running
(X) Always execute the script

svnadd.bat

@echo off

rem Iterates each line result from the command which lists files/folders
rem     not added to source control while respecting the ignore list.
FOR /F "delims==" %%G IN ('svn status ^| findstr "^?"') DO call :DoSVNAdd "%%G"
goto end

:DoSVNAdd
set addPath=%1
rem Remove line prefix formatting from svn status command output as well as
rem    quotes from the G call (as required for long folder names). Then
rem    place quotes back around the path for the SVN add call.
set addPath="%addPath:~9,-1%"
svn add %addPath%

:end

How to efficiently count the number of keys/properties of an object in JavaScript?

The standard Object implementation (ES5.1 Object Internal Properties and Methods) does not require an Object to track its number of keys/properties, so there should be no standard way to determine the size of an Object without explicitly or implicitly iterating over its keys.

So here are the most commonly used alternatives:

1. ECMAScript's Object.keys()

Object.keys(obj).length; Works by internally iterating over the keys to compute a temporary array and returns its length.

  • Pros - Readable and clean syntax. No library or custom code required except a shim if native support is unavailable
  • Cons - Memory overhead due to the creation of the array.

2. Library-based solutions

Many library-based examples elsewhere in this topic are useful idioms in the context of their library. From a performance viewpoint, however, there is nothing to gain compared to a perfect no-library code since all those library methods actually encapsulate either a for-loop or ES5 Object.keys (native or shimmed).

3. Optimizing a for-loop

The slowest part of such a for-loop is generally the .hasOwnProperty() call, because of the function call overhead. So when I just want the number of entries of a JSON object, I just skip the .hasOwnProperty() call if I know that no code did nor will extend Object.prototype.

Otherwise, your code could be very slightly optimized by making k local (var k) and by using prefix-increment operator (++count) instead of postfix.

var count = 0;
for (var k in myobj) if (myobj.hasOwnProperty(k)) ++count;

Another idea relies on caching the hasOwnProperty method:

var hasOwn = Object.prototype.hasOwnProperty;
var count = 0;
for (var k in myobj) if (hasOwn.call(myobj, k)) ++count;

Whether this is faster or not on a given environment is a question of benchmarking. Very limited performance gain can be expected anyway.

How to check if a key exists in Json Object and get its value

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In my case I was running into issues with my $PATH on Linux. This can also happen on MacOS.

Check to see if /usr/bin/pip3 install package_name_goes_here works for you. If so then run which pip3 this will tell you which is the first directory that pip3 is installed in.

If it is something like /usr/local/bin/pip3 which is different from /usr/bin/pip3 then you may need to adjust your $PATH.

Run echo $PATH and copy the result.

The PATH is simply a colon separated list of directories that contain directories. Bash will always return the first instance of the program that you are attempting to execute. Move all the system directories upfront. Here is a list of some of the system directories:

/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

If that fails then verify you have openssl installed by running openssl version -a if not then install openssl.

Determining if an Object is of primitive type

I think this happens due to auto-boxing.

int i = 3;
Object o = i;
o.getClass().getName(); // prints Integer

You may implement a utility method that matches these specific boxing classes and gives you if a certain class is primitive.

public static boolean isWrapperType(Class<?> clazz) {
    return clazz.equals(Boolean.class) || 
        clazz.equals(Integer.class) ||
        clazz.equals(Character.class) ||
        clazz.equals(Byte.class) ||
        clazz.equals(Short.class) ||
        clazz.equals(Double.class) ||
        clazz.equals(Long.class) ||
        clazz.equals(Float.class);
}

Getting windbg without the whole WDK?

If you run winsdk_web.exe from the following link, you can selectively install windbg or extract windbg installer msi.

Microsoft Windows SDK for Windows 7 and .NET Framework 4 http://go.microsoft.com/fwlink/?LinkID=191420

Debugging tools for Windows

How to detect the screen resolution with JavaScript?

Using jQuery you can do:

$(window).width()
$(window).height()

How to remove from a map while iterating it?

In short "How do I remove from a map while iterating it?"

  • With old map impl: You can't
  • With new map impl: almost as @KerrekSB suggested. But there are some syntax issues in what he posted.

From GCC map impl (note GXX_EXPERIMENTAL_CXX0X):

#ifdef __GXX_EXPERIMENTAL_CXX0X__
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // DR 130. Associative erase should return an iterator.
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *  @return An iterator pointing to the element immediately following
       *          @a position prior to the element being erased. If no such 
       *          element exists, end() is returned.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      iterator
      erase(iterator __position)
      { return _M_t.erase(__position); }
#else
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      void
      erase(iterator __position)
      { _M_t.erase(__position); }
#endif

Example with old and new style:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;
typedef map<int, int> t_myMap;
typedef vector<t_myMap::key_type>  t_myVec;

int main() {

    cout << "main() ENTRY" << endl;

    t_myMap mi;
    mi.insert(t_myMap::value_type(1,1));
    mi.insert(t_myMap::value_type(2,1));
    mi.insert(t_myMap::value_type(3,1));
    mi.insert(t_myMap::value_type(4,1));
    mi.insert(t_myMap::value_type(5,1));
    mi.insert(t_myMap::value_type(6,1));

    cout << "Init" << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    t_myVec markedForDeath;

    for (t_myMap::const_iterator it = mi.begin(); it != mi.end() ; it++)
        if (it->first > 2 && it->first < 5)
            markedForDeath.push_back(it->first);

    for(size_t i = 0; i < markedForDeath.size(); i++)
        // old erase, returns void...
        mi.erase(markedForDeath[i]);

    cout << "after old style erase of 3 & 4.." << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    for (auto it = mi.begin(); it != mi.end(); ) {
        if (it->first == 5)
            // new erase() that returns iter..
            it = mi.erase(it);
        else
            ++it;
    }

    cout << "after new style erase of 5" << endl;
    // new cend/cbegin and lambda..
    for_each(mi.cbegin(), mi.cend(), [](t_myMap::const_reference it){cout << '\t' << it.first << '-' << it.second << endl;});

    return 0;
}

prints:

main() ENTRY
Init
        1-1
        2-1
        3-1
        4-1
        5-1
        6-1
after old style erase of 3 & 4..
        1-1
        2-1
        5-1
        6-1
after new style erase of 5
        1-1
        2-1
        6-1

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

How to get start and end of previous month in VB

The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:

''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013 
DateSerial(Year(Date),1,0) = 31/12/2012 

You can get the first day from the above like so:

LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1

See also: How to caculate last business day of month in VBScript

HTML table sort

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

The basic process is:

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table

The table should, of course, be nice HTML. Something like this...

<table>
 <thead>
  <tr><th>Name</th><th>Age</th></tr>
 </thead>
 <tbody>
  <tr><td>Sioned</td><td>62</td></tr>
  <tr><td>Dylan</td><td>37</td></tr>
  ...etc...
 </tbody>
</table>

So, first adding the click handlers...

const table = document.querySelector('table'); //get the table to be sorted

table.querySelectorAll('th') // get all the table header elements
  .forEach((element, columnNo)=>{ // add a click handler for each 
    element.addEventListener('click', event => {
        sortTable(table, columnNo); //call a function which sorts the table by a given column number
    })
  })

This won't work right now because the sortTable function which is called in the event handler doesn't exist.

Lets write it...

function sortTable(table, sortColumn){
  // get the data from the table cells
  const tableBody = table.querySelector('tbody')
  const tableData = table2data(tableBody);
  // sort the extracted data
  tableData.sort((a, b)=>{
    if(a[sortColumn] > b[sortColumn]){
      return 1;
    }
    return -1;
  })
  // put the sorted data back into the table
  data2table(tableBody, tableData);
}

So now we get to the meat of the problem, we need to make the functions table2data to get data out of the table, and data2table to put it back in once sorted.

Here they are ...

// this function gets data from the rows and cells 
// within an html tbody element
function table2data(tableBody){
  const tableData = []; // create the array that'll hold the data rows
  tableBody.querySelectorAll('tr')
    .forEach(row=>{  // for each table row...
      const rowData = [];  // make an array for that row
      row.querySelectorAll('td')  // for each cell in that row
        .forEach(cell=>{
          rowData.push(cell.innerText);  // add it to the row data
        })
      tableData.push(rowData);  // add the full row to the table data 
    });
  return tableData;
}

// this function puts data into an html tbody element
function data2table(tableBody, tableData){
  tableBody.querySelectorAll('tr') // for each table row...
    .forEach((row, i)=>{  
      const rowData = tableData[i]; // get the array for the row data
      row.querySelectorAll('td')  // for each table cell ...
        .forEach((cell, j)=>{
          cell.innerText = rowData[j]; // put the appropriate array element into the cell
        })
      tableData.push(rowData);
    });
}

And that should do it.

A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2" is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.

How to fix nginx throws 400 bad request headers on any header testing tools?

When nginx returns 400(bad request) it will log the reason into error log, at "info" level and take a look into error log when testing.

How to return a boolean method in java?

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            addNewUser();
            return true;
        }
}

How to set array length in c# dynamically

Does is need to be an array? If you use an ArrayList or one of the other objects available in C#, you won't have this limitation to content with. Hashtable, IDictionnary, IList, etc.. all allow a dynamic number of elements.

Javascript Src Path

As your clock.js is in the root, put your code as this to call your javascript in the index.html found in the folders you mentioned.

<SCRIPT LANGUAGE="JavaScript" SRC="../clock.js"></SCRIPT>

This will call the clock.js which you put in the root of your web site.

How to correctly use the ASP.NET FileUpload control

ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:

<asp:FileUpload ID="FileUpload1" runat="server" />

Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.

Add a button that will do the post back:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:

protected void Button1_Click(object sender, EventArgs e)
{
  if (this.FileUpload1.HasFile)
  {
    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
  }
}

And that's it. All should work as expected.

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Simply type the command:

$ gdb <Binary> <codeDump>

Or

$ gdb <binary>

$ gdb) core <coreDump>

There isn't any need to provide any command line argument. The code dump generated due to an earlier exercise.

SyntaxError: Unexpected token function - Async Await Nodejs

Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:

npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-plugin-transform-async-to-generator": "6.24.1",
   "babel-plugin-transform-runtime": "6.23.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator", 
["transform-runtime", {
      "polyfill": false,
      "regenerator": true
    }]
]
}

and then happy coding with async/await

How to stretch in width a WPF user control to its window?

Instead use Width and Height in user controls, use MinHeight and MinWidth. Then you can configure the UC well, and will be able to stretch inside other window.

Well, as Im seeing in WPF Microsoft made a re-thinking about windows properties and behaviors, but so far, I didn't miss anything from olds windows forms, in WPF the controls are there, but in a new point of view.

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

Setting width to wrap_content for TextView through code

TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

For different layouts like ConstraintLayout and others, they have their own LayoutParams, like so:

pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

or

parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

xls to csv converter

I've tested all anwers, but they were all too slow for me. If you have Excel installed you can use the COM.

I thought initially it would be slower since it will load everything for the actual Excel application, but it isn't for huge files. Maybe because the algorithm for opening and saving files runs a heavily optimized compiled code, Microsoft guys make a lot of money for it after all.

import sys
import os
import glob
from win32com.client import Dispatch

def main(path):
    excel = Dispatch("Excel.Application")
    if is_full_path(path):
        process_file(excel, path)
    else:
        files = glob.glob(path)
        for file_path in files:
            process_file(excel, file_path)
    excel.Quit()

def process_file(excel, path):
    fullpath = os.path.abspath(path)
    full_csv_path = os.path.splitext(fullpath)[0] + '.csv'
    workbook = excel.Workbooks.Open(fullpath)
    workbook.Worksheets(1).SaveAs(full_csv_path, 6)
    workbook.Saved = 1
    workbook.Close()


def is_full_path(path):
    return path.find(":") > -1

if __name__ == '__main__':
    main(sys.argv[1])

This is very raw code and won't check for errors, print help or anything, it will just create a csv file for each file that matches the pattern you entered in the function so you can batch process a lot of files only launching excel application once.

Sort array of objects by object fields

This is what I have for a utility class

class Util
{
    public static function sortArrayByName(&$arrayToSort, $meta) {
        usort($arrayToSort, function($a, $b) use ($meta) {
            return strcmp($a[$meta], $b[$meta]);
        });
    }
}

Call it:

Util::sortArrayByName($array, "array_property_name");

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

Center the nav in Twitter Bootstrap

http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.

http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.

Making a drop down list using swift?

A 'drop down menu' is a web control / term. In iOS we don't have these. You might be better looking at UIPopoverController. Check out this tutorial for a bit of an insight to PopoverControllers

http://www.raywenderlich.com/29472/ipad-for-iphone-developers-101-in-ios-6-uipopovercontroller-tutorial

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

Open Registry Editor using run command regedit.

Locate HKEY_CLASSES_ROOT\TypeLib Key and then did a search for "MSCOMCTL.OCX" and deleted EVERY key that referenced this .ocx file.

Open command prompt (cmd) in Administrator mode. The type the following code,

In 32 bit machine,

cd c:\Windows\System32
regsvr32 MSCOMCTL.OCX
regtlib msdatsrc.tlb
regsvr32 MSCOMCT2.OCX

In 64 bit machine,

cd c:\Windows\SysWOW64
regsvr32 MSCOMCTL.OCX
regtlib msdatsrc.tlb
regsvr32 MSCOMCT2.OCX

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

Run a Command Prompt command from Desktop Shortcut

You can also create a shortcut on desktop that can run a specific command or even a batch file by just typing the command in "Type the Location of Item" bar in create shortcut wizard

  1. Right click on Desktop.
  2. Enter the command in "Type the Location of Item" bar.
  3. Double click the shortcut to run the command.

Found detailed Instructions here

AND/OR in Python?

For the updated question, you can replace what you want with something like:

someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)

filter evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.

Alternatively, if the items in someList should be unique, you can make someList a set and do something like this:

someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))

This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList as a set from the beginning in this case, it will optimize things a bit.

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

Yes not working! I spent whole day with this stupid phpMyAdmin. Just add a new user with a password

1 - Login to mysql or mariadb mysql -u root -p

2 - Run these SQL commands to create a new user with all permissions (or grant your custom permissions)

CREATE USER 'someone'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'someone'@'localhost';
FLUSH PRIVILEGES;

2 - Go to /etc/phpMyAdmin/config.inc.php and change this:

$cfg['Servers'][$i]['user']          = 'someone';
$cfg['Servers'][$i]['password']      = 'password';

WARNING: This config is for localhost development server only, If you're running a production server you must use strong credentials and not setting user pass in config.inc.php

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

check your Bundle identifier for your project and you give Bundle identifier for your app which create on developer.facebook.com that they are same or not.

Oracle PL Sql Developer cannot find my tnsnames.ora file

If you are certain your tnsnames.ora file is correct (eg by testing the connection with the Oracle Net Config Assistant, or logging in successfully with SQLplus), and you are able to open the PLSQL Developer application, but you still can't connect to the database in PLSQL Developer, then follow these steps:

  1. In PLSQL Developer (version 11.0) go to Help/Support Info

  2. Click the TNS Names tab. If the path in PLSQL Developer is wrong it will be blank (no tns file found) or incorrect (wrong tns file in use)

  3. On the Info tab scroll down to the TNS File entry and to see the path for the tns file PLSQL Developer is using. Very likely this is wrong.

  4. To correct the path:

    • open a command prompt
    • navigate to the PLSQL Developer directory in Program Files
    • enter this command:

      plsqldev.exe TNS_ADMIN=c:\your\tns\directory\path\here

    *path is to the directory containing your tnsnames.ora file - for me this is: c:\Oracle\product\11.2.0\client_1\network\admin

  5. A new PLSQL Developer UI will open and you should be able to connect.

  6. Make sure you have a Windows environment variable TNS_ADMIN set to the same path

    • On Windows 7 you go to Start, Control Panel, System, Advanced System Settings, Environment Variables to view/add/update environment variables

Run a script in Dockerfile

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

ADD script.sh /root/script.sh

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

In CMD place [./script]

It should automatically execute your script

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

Set equal width of columns in table layout in Android

Try this.

It boils down to adding android:stretchColumns="*" to your TableLayout root and setting android:layout_width="0dp" to all the children in your TableRows.

<TableLayout
    android:stretchColumns="*"   // Optionally use numbered list "0,1,2,3,..."
>
    <TableRow
        android:layout_width="0dp"
    >

Iterate over values of object

I iterate like this and it works for me.

for (let [k, v] of myMap) {
    console.log("Key: " + k);
    console.log("Value: " + v);
}

Hope this helps :)

How to use mongoimport to import csv

Check that you have a blank line at the end of the file, otherwise the last line will be ignored on some versions of mongoimport

Is HTML considered a programming language?

I think not exactly a programming language, but exactly what its name says: a markup language. We cannot program using just pure, HTML. But just annotate how to present content.

But if you consider programming the act of tell the computer how to present contents, it is a programming language.

Java inner class and static nested class

I think, the convention that is generally followed is this:

  • static class within a top level class is a nested class
  • non static class within a top level class is a inner class, which further has two more form:
    • local class - named classes declared inside of a block like a method or constructor body
    • anonymous class - unnamed classes whose instances are created in expressions and statements

However, few other points to remembers are:

  • Top level classes and static nested class are semantically same except that in case of static nested class it can make static reference to private static fields/methods of its Outer [parent] class and vice versa.

  • Inner classes have access to instance variables of the enclosing instance of the Outer [parent] class. However, not all inner classes have enclosing instances, for example inner classes in static contexts, like an anonymous class used in a static initializer block, do not.

  • Anonymous class by default extends the parent class or implements the parent interface and there is no further clause to extend any other class or implement any more interfaces. So,

    • new YourClass(){}; means class [Anonymous] extends YourClass {}
    • new YourInterface(){}; means class [Anonymous] implements YourInterface {}

I feel that the bigger question that remains open which one to use and when? Well that mostly depends on what scenario you are dealing with but reading the reply given by @jrudolph may help you making some decision.

git ahead/behind info between master and branch?

You can also use awk to make it a little bit prettier:

git rev-list --left-right --count  origin/develop...feature-branch | awk '{print "Behind "$1" - Ahead "$2""}'

You can even make an alias that always fetches origin first and then compares the branches

commit-diff = !"git fetch &> /dev/null && git rev-list --left-right --count"

Unable to Install Any Package in Visual Studio 2015

I was able to resolve this issue by reinstalling Nuget Package Manager via Tools -> Extensions and Updates

What is the purpose of Node.js module.exports and how do you use it?

There are some default or existing modules in node.js when you download and install node.js like http, sys etc.

Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.

Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.

Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo

Huh, so that's the reason, we do like

exports.additionTwo = function(x)
{return x+2;};

Be careful with the path

Lets say you have created an addition.js module,

exports.additionTwo = function(x){
return x + 2;
};

When you run this on your NODE.JS command prompt:

node
var run = require('addition.js');

This will error out saying

Error: Cannot find module addition.js

This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH

set NODE_PATH = path/to/your/additon.js

Now, this should run successfully without any errors!!

One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:

node
var run = require('./addition.js');

Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.

pandas dataframe columns scaling with sklearn

As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el)) method will produce the following warning:

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.

Converting your columns to numpy arrays should do the job (I prefer StandardScaler):

from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())

-- Edit Nov 2018 (Tested for pandas 0.23.4)--

As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix() returns FutureWarning. Therefore, it should be replaced by .values:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit_transform(dfTest[['A','B']].values)

-- Edit May 2019 (Tested for pandas 0.24.2)--

As joelostblom mentions in the comments, "Since 0.24.0, it is recommended to use .to_numpy() instead of .values."

Updated example:

import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
               'A':[14.00,90.20,90.95,96.27,91.21],
               'B':[103.02,107.26,110.35,114.23,114.68],
               'C':['big','small','big','small','small']
             })
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
      A         B      C
0 -1.995290 -1.571117    big
1  0.436356 -0.603995  small
2  0.460289  0.100818    big
3  0.630058  0.985826  small
4  0.468586  1.088469  small

How do I convert two lists into a dictionary?

method without zip function

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d','e']
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}

XAMPP permissions on Mac OS X?

Tried the above but the option to amend the permission was not available for the htdocs folder,

My solution was:

  1. Open applications folder
  2. Locate XAMPP folder
  3. Right click, get info (as described above)
  4. In pop-up window locate the 'sharing & permission' section
  5. Click the 'locked' padlock symbol
  6. Enter admin password
  7. Change 'Everyone' permissions to read & write
  8. In the get info window still, select the 'cog' icon' drop down option at the very bottom and select 'Apply to enclosed items' this will adjust the permission across all sub-folders as well.
  9. Re-lock the padlock symbol
  10. Close the 'Get Info' window.

Task complete, this will now allow you to populate sub-folders within the htdocs folder as needed to populate your website(s).

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

How can I repeat a character in Bash?

Python is ubiquitous and works the same everywhere.

python -c "import sys; print('*' * int(sys.argv[1]))" "=" 100

Character and count are passed as separate parameters.

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

How to unlock a file from someone else in Team Foundation Server

I solved this with the TFS powertools (dec 2011 - for VS 2010 TFS 2010)

http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f

Find in Source Control | Status... allows you to find all files checked out to a specific person

right click and UNDO... can remove each checkout.

php - How do I fix this illegal offset type error

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

Sending an HTTP POST request on iOS

-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

//Create POST Params and add it to HTTPBody
NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //Handle your response here
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
     NSLog(@"%@",responseDict);
}];
   [dataTask resume];
}

How do I convert datetime to ISO 8601 in PHP

You can try this way:

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DATE_ATOM);

NuGet behind a proxy

Try this. Basically, connection could fail if your system doesn't trust nuget certificate.

Manually install Gradle and use it in Android Studio

Android Studio will automatically use the Gradle wrapper and pull the correct version of Gradle rather than use a locally installed version. If you wish to use a new version of Gradle, you can change the version used by studio. Beneath your Android Studio's project tree, open the file gradle/wrapper/gradle-wrapper.properties. Change this entry:

distributionUrl=http\://services.gradle.org/distributions/gradle-2.1-all.zip

The operation cannot be completed because the DbContext has been disposed error

The reason why it is throwing the error is the object is disposed and after that we are trying to access the table values through the object, but object is disposed.Better to convert that into ToList() so that we can have values

Maybe it isn't actually getting the data until you use it (it is lazy loading), so dataContext doesn't exist when you are trying to do the work. I bet if you did the ToList() in scope it would be ok.

try
{
    IQueryable<User> users;
    var ret = null;

    using (var dataContext = new dataContext())
    {
        users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

        if(users.Any())
        {
            ret = users.Select(x => x.ToInfo()).ToList(); 
        }

     }

   Return ret;
}
catch (Exception ex)
{
    ...
}

Find and Replace text in the entire table using a MySQL query

UPDATE  `MySQL_Table` 
SET  `MySQL_Table_Column` = REPLACE(`MySQL_Table_Column`, 'oldString', 'newString')
WHERE  `MySQL_Table_Column` LIKE 'oldString%';

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

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

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

How to use external ".js" files

This is the way to include an external javascript file to you HTML markup.

<script type="text/javascript" src="/js/external-javascript.js"></script>

Where external-javascript.js is the external file to be included. Make sure the path and the file name are correct while you including it.

<a href="javascript:showCountry('countryCode')">countryCode</a>

The above mentioned method is correct for anchor tags and will work perfectly. But for other elements you should specify the event explicitly.

Example:

<select name="users" onChange="showUser(this.value)">

Thanks, XmindZ

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

php is null or empty?

NULL stands for a variable without value. To check if a variable is NULL you can either use is_null($var) or the comparison (===) with NULL. Both ways, however, generate a warning if the variable is not defined. Similar to isset($var) and empty($var), which can be used as functions.

var_dump(is_null($var)); // true
var_dump($var === null); // true
var_dump(empty($var)); // true

Read more in How to check if a variable is NULL in PHP?

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

How do I edit $PATH (.bash_profile) on OSX?

If you are using MAC Catalina you need to update the .zshrc file instead of .bash_profile or .profile

Versioning SQL Server database

We needed to version our SQL database after we migrated to an x64 platform and our old version broke with the migration. We wrote a C# application which used SQLDMO to map out all of the SQL objects to a folder:

                Root
                    ServerName
                       DatabaseName
                          Schema Objects
                             Database Triggers*
                                .ddltrigger.sql
                             Functions
                                ..function.sql
                             Security
                                Roles
                                   Application Roles
                                      .approle.sql
                                   Database Roles
                                      .role.sql
                                Schemas*
                                   .schema.sql
                                Users
                                   .user.sql
                             Storage
                                Full Text Catalogs*
                                   .fulltext.sql
                             Stored Procedures
                                ..proc.sql
                             Synonyms*
                                .synonym.sql
                             Tables
                                ..table.sql
                                Constraints
                                   ...chkconst.sql
                                   ...defconst.sql
                                Indexes
                                   ...index.sql
                                Keys
                                   ...fkey.sql
                                   ...pkey.sql
                                   ...ukey.sql
                                Triggers
                                   ...trigger.sql
                             Types
                                User-defined Data Types
                                   ..uddt.sql
                                XML Schema Collections*
                                   ..xmlschema.sql
                             Views
                                ..view.sql
                                Indexes
                                   ...index.sql
                                Triggers
                                   ...trigger.sql

The application would then compare the newly written version with the version stored in SVN, and if there were differences it would update SVN. We determined that running the process once a night was sufficient since we did not make that many changes to SQL. It allows us to track changes to all the objects we care about plus it allows us to rebuild our full schema in the event of a serious problem.

How can I clear an HTML file input with JavaScript?

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How can I get file extensions with JavaScript?

There is a standard library function for this in the path module:

import path from 'path';

console.log(path.extname('abc.txt'));

Output:

.txt

So, if you only want the format:

path.extname('abc.txt').slice(1) // 'txt'

If there is no extension, then the function will return an empty string:

path.extname('abc') // ''

If you are using Node, then path is built-in. If you are targetting the browser, then Webpack will bundle a path implementation for you. If you are targetting the browser without Webpack, then you can include path-browserify manually.

There is no reason to do string splitting or regex.

Clear dropdown using jQuery Select2

These both work for me to clear the dropdown:

.select2('data', null)
.select2('val', null)

But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3

How to use timeit module

Example of how to use Python REPL interpreter with function that accepts parameters.

>>> import timeit                                                                                         

>>> def naive_func(x):                                                                                    
...     a = 0                                                                                             
...     for i in range(a):                                                                                
...         a += i                                                                                        
...     return a                                                                                          

>>> def wrapper(func, *args, **kwargs):                                                                   
...     def wrapper():                                                                                    
...         return func(*args, **kwargs)                                                                  
...     return wrapper                                                                                    

>>> wrapped = wrapper(naive_func, 1_000)                                                                  

>>> timeit.timeit(wrapped, number=1_000_000)                                                              
0.4458435332577161                                                                                        

phpMyAdmin - config.inc.php configuration?

Have a look at config.sample.inc.php: you will find examples of the configuration directives that you should copy to your config.inc.php (copy the missing ones). Then, have a look at examples/create_tables.sql which will help you create the missing tables.

The complete documentation for this is available at http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

How do I associate file types with an iPhone application?

To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>IPA</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.item</string>
                <string>public.content</string>
                <string>public.data</string>
                <string>public.database</string>
                <string>public.composite-content</string>
                <string>public.contact</string>
                <string>public.archive</string>
                <string>public.url-name</string>
                <string>public.text</string>
                <string>public.plain-text</string>
                <string>public.source-code</string>
                <string>public.executable</string>
                <string>public.script</string>
                <string>public.shell-script</string>
                <string>public.xml</string>
                <string>public.symlink</string>
                <string>org.gnu.gnu-zip-archve</string>
                <string>org.gnu.gnu-tar-archive</string>
                <string>public.image</string>
                <string>public.movie</string>
                <string>public.audiovisual-?content</string>
                <string>public.audio</string>
                <string>public.directory</string>
                <string>public.folder</string>
                <string>com.apple.bundle</string>
                <string>com.apple.package</string>
                <string>com.apple.plugin</string>
                <string>com.apple.application-?bundle</string>
                <string>com.pkware.zip-archive</string>
                <string>public.filename-extension</string>
                <string>public.mime-type</string>
                <string>com.apple.ostype</string>
                <string>com.apple.nspboard-typ</string>
                <string>com.adobe.pdf</string>
                <string>com.adobe.postscript</string>
                <string>com.adobe.encapsulated-?postscript</string>
                <string>com.adobe.photoshop-?image</string>
                <string>com.adobe.illustrator.ai-?image</string>
                <string>com.compuserve.gif</string>
                <string>com.microsoft.word.doc</string>
                <string>com.microsoft.excel.xls</string>
                <string>com.microsoft.powerpoint.?ppt</string>
                <string>com.microsoft.waveform-?audio</string>
                <string>com.microsoft.advanced-?systems-format</string>
                <string>com.microsoft.advanced-?stream-redirector</string>
                <string>com.microsoft.windows-?media-wmv</string>
                <string>com.microsoft.windows-?media-wmp</string>
                <string>com.microsoft.windows-?media-wma</string>
                <string>com.apple.keynote.key</string>
                <string>com.apple.keynote.kth</string>
                <string>com.truevision.tga-image</string>
            </array>
            <key>CFBundleTypeIconFiles</key>
            <array>
                <string>Icon-76@2x</string>
            </array>
        </dict>
    </array>

Why would one use nested classes in C++?

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

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

Rather than:

class Product {}
class ProductBuilder {}

Mongoose, update values in array of objects

You're close; you should use dot notation in your use of the $ update operator to do that:

Person.update({'items.id': 2}, {'$set': {
    'items.$.name': 'updated item2',
    'items.$.value': 'two updated'
}}, function(err) { ...

How to retrieve a file from a server via SFTP?

The best solution I've found is Paramiko. There's a Java version.

How to align the checkbox and label in same line in html?

Another approach here:

.checkbox-wrapper {
  white-space: nowrap
}
.checkbox {
  vertical-align: top;
  display:inline-block
}
.checkbox-label {
  white-space: normal
  display:inline-block
}

<div class="text-left checkbox-wrapper">
  <input type="checkbox" id="terms" class="checkbox">
  <label class="checkbox-label" for="terms">I accept whatever you want!</label>
</div>

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This usually happens if you have entered the wrong details when you created the App in Facebook. Or have you changed a URL's of an existing App?

Can you please recheck the settings of your APP in this page?

https://developers.facebook.com/apps

  1. Select the correct App and click in the edit button;

  2. Check the URLs & paths are correctly entered and are pointing to the site where you have installed Ultimate Facebook plugin.

How to exit an if clause

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

How to print the current time in a Batch-File?

set time1=%time%
call timeout 10
set time2=%time%
echo. time1
echo. time2
echo.
pause

Angular CLI SASS options

Update for Angular 6+

  1. New Projects

    When generating a new project with Angular CLI, specify the css pre-processor as

    • Use SCSS syntax

      ng new sassy-project --style=scss
      
    • Use SASS syntax

      ng new sassy-project --style=sass
      
  2. Updating existing project

    Set default style on an existing project by running

    • Use SCSS syntax

      ng config schematics.@schematics/angular:component.styleext scss
      
    • Use SASS syntax

      ng config schematics.@schematics/angular:component.styleext sass
      

    The above command will update your workspace file (angular.json) with

    "schematics": {
        "@schematics/angular:component": {
            "styleext": "scss"
        }
    } 
    

    where styleext can be either scss or sass as per the choice.




Original Answer (for Angular < 6)

New projects

For new projects we can set the options --style=sass or --style=scss according to the desired flavor SASS/SCSS

  • Use SASS syntax

    ng new project --style=sass 
    
  • Use SCSS syntax

    ng new project --style=scss 
    

then install node-sass,

npm install node-sass --save-dev

Updating existing projects

To make angular-cli to compile sass files with node-sass, I had to run,

npm install node-sass --save-dev 

which installs node-sass. Then

  • for SASS syntax

    ng set defaults.styleExt sass
    
  • for SCSS syntax

    ng set defaults.styleExt scss
    

to set the default styleExt to sass

(or)

change styleExt to sass or scss for desired syntax in .angular-cli.json,

  • for SASS syntax

    "defaults": {
         "styleExt": "sass",
    }
    
  • for SCSS syntax

    "defaults": {
         "styleExt": "scss",
    }
    


Although it generated compiler errors.

ERROR in multi styles
Module not found: Error: Can't resolve '/home/user/projects/project/src/styles.css' in '/home/user/projects/project'
 @ multi styles 

which was fixed by changing the lines of .angular-cli.json,

"styles": [
        "styles.css"
      ],

to either,

  • for SASS syntax

    "styles": [
            "styles.sass"
          ],
    
  • for SCSS syntax

    "styles": [
            "styles.scss"
          ],
    

git - Your branch is ahead of 'origin/master' by 1 commit

If you just want to throw away the changes and revert to the last commit (the one you wanted to share):

git reset --hard HEAD~

You may want to check to make absolutely sure you want this (git log), because you'll loose all changes.

A safer alternative is to run

git reset --soft HEAD~ # reset to the last commit
git stash              # stash all the changes in the working tree 
git push               # push changes 
git stash pop          # get your changes back 

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

QComboBox - set selected item based on the item's data

If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.

ui->comboBox->setCurrentText("choice 2");

From the Qt 5.7 documentation

The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.

So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.

Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop

How do I use $scope.$watch and $scope.$apply in AngularJS?

You need to be aware about how AngularJS works in order to understand it.

Digest cycle and $scope

First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar in each iteration of the loop.

A natural follow-up question would be: Is everything attached to $scope being watched? Fortunately, no. If you would watch for changes to every object in your $scope, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope variable as being watched (read below).

$watch helps to listen for $scope changes

There are two ways of declaring a $scope variable as being watched.

  1. By using it in your template via the expression <span>{{myVar}}</span>
  2. By adding it manually via the $watch service

Ad 1) This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat) can also create implicit watches.

Ad 2) This is how you create your own watches. $watch service helps you to run some code when some value attached to the $scope has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:

function MyController($scope) {

    $scope.myVar = 1;

    $scope.$watch('myVar', function() {
        alert('hey, myVar has changed!');
    });

    $scope.buttonClicked = function() {
        $scope.myVar = 2; // This will trigger $watch expression to kick in
    };
}

$apply enables to integrate changes with the digest cycle

You can think of the $apply function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.

However, sometimes you want to change some value outside of the AngularJS world and see the changes propagate normally. Consider this - you have a $scope.myVar value which will be modified within a jQuery's $.ajax() handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.

To tackle this, $apply has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.

How is all of this related to the DOM?

Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all $scopes as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.

You can attach objects to the $scope object either explicitly in the Controller, or by declaring them in {{expression}} form directly in the view.

I hope that helps to clarify some basic knowledge about all this.

Further readings:

Singleton in Android

The most clean and modern way to use singletons in Android is just to use the Dependency Injection framework called Dagger 2. Here you have an explanation of possible scopes you can use. Singleton is one of these scopes. Dependency Injection is not that easy but you shall invest a bit of your time to understand it. It also makes testing easier.

OpenSSL: unable to verify the first certificate for Experian URL

If you are using MacOS use:

sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs

after this Trust anchor not found error disappears

Why is $$ returning the same id as the parent process?

Try getppid() if you want your C program to print your shell's PID.

PHP: Best way to check if input is a valid number?

The most secure way

if(preg_replace('/^(\-){0,1}[0-9]+(\.[0-9]+){0,1}/', '', $value) == ""){
  //if all made of numbers "-" or ".", then yes is number;
}

navbar color in Twitter Bootstrap

You can overwrite the bootstrap colors, including the .navbar-inner class, by targetting it in your own stylesheet as opposed to modifying the bootstrap.css stylesheet, like so:

.navbar-inner {
  background-color: #2c2c2c; /* fallback color, place your own */

  /* Gradients for modern browsers, replace as you see fit */
  background-image: -moz-linear-gradient(top, #333333, #222222);
  background-image: -ms-linear-gradient(top, #333333, #222222);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222));
  background-image: -webkit-linear-gradient(top, #333333, #222222);
  background-image: -o-linear-gradient(top, #333333, #222222);
  background-image: linear-gradient(top, #333333, #222222);
  background-repeat: repeat-x;

  /* IE8-9 gradient filter */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0);
}

You just have to modify all of those styles with your own and they will get picked up, like something like this for example, where i eliminate all gradient effects and just set a solid black background-color:

.navbar-inner {
  background-color: #000; /* background color will be black for all browsers */
  background-image: none;
  background-repeat: no-repeat;
  filter: none;
}

You can take advantage of such tools as the Colorzilla Gradient Editor and create your own gradient colors for all browsers and replace the original colors with your own.

And as i mentioned on the comments, i would not recommend you modifying the bootstrap.css stylesheet directly as all of your changes will be lost once the stylesheet gets updated (current version is v2.0.2) so it is preferred that you include all of your changes inside your own stylesheet, in tandem with the bootstrap.css stylesheet. But remember to overwrite all of the appropriate properties to have consistency across browsers.

Creating a class object in c++

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.

This is wrong. A constructor must exist in order to create an object. The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated. In fact, the lifetime of an object is defined to begin when the constructor routine returns.

From Paragraph 3.8/1 of the C++11 Standard:

[...] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

Therefore, a constructor must be present.

1) What is the difference between both the way of creating class objects.

When you instantiate object with automatic storage duration, like this (where X is some class):

X x;

You are creating an object which will be automatically destroyed when it goes out of scope. On the other hand, when you do:

X* x = new X();

You are creating an object dynamically and you are binding its address to a pointer. This way, the object you created will not be destroyed when your x pointer goes out of scope.

In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics, raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).

In fact, when creating an object with new, you always have to remember destroying it with delete:

delete x;

If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:

std::shared_ptr<X> x = std::make_shared<X>();

Smart pointers take care of memory management issues, which is what gives you headache with raw pointers. Smart pointers are, in fact, almost the same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.

2) If i am creating object like Example example; how to use that in an singleton class.

You could do something like this (simplified code):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Can you split/explode a field in a MySQL query?

Well, nothing I used worked, so I decided creating a real simple split function, hope it helps:

    DECLARE inipos INTEGER;
    DECLARE endpos INTEGER;
    DECLARE maxlen INTEGER;
    DECLARE item VARCHAR(100);
    DECLARE delim VARCHAR(1);

    SET delim = '|';
    SET inipos = 1;
    SET fullstr = CONCAT(fullstr, delim);
    SET maxlen = LENGTH(fullstr);

    REPEAT
        SET endpos = LOCATE(delim, fullstr, inipos);
        SET item =  SUBSTR(fullstr, inipos, endpos - inipos);

        IF item <> '' AND item IS NOT NULL THEN           
            USE_THE_ITEM_STRING;
        END IF;
        SET inipos = endpos + 1;
    UNTIL inipos >= maxlen END REPEAT;

Firefox "ssl_error_no_cypher_overlap" error

"Error code: ssl_error_no_cypher_overlap" error message after login, when Welcome screen expected--using Firefox browser Solution 1: enter 'about:config' in Browser Address bar 2: find/select "security.ssl3.rsa_rc4_40_md5" 3: set boolean to TRUE

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

I want to start by thanking everyone that answered. But cleaning and rebuilding was not enough in my case because the problem was still there and needed fixing.

Turned out that one of my package directories had accidentally been copied so that an extra directory now existed called "Copy of dagskra" containing Java files with wrong package declarations. In addition the errors in this "new" directory don't show up with a "red-x" in the package that it exists in:

Snapshot from Package Explorer showing errorous "Copy of dagskra" directoryr http://www.freeimagehosting.net/uploads/a824304b18.png

It was the hint of reading the "Problems" tab :-) that turned me into the right direction, so I'm selecting that answer as the accepted answer because this is what I needed:

Snapshot from Problems tab http://www.freeimagehosting.net/uploads/dea26d5dd0.png

Hoping this will help others...

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

How to get function parameter names/values dynamically?

Try Manually:

function something(arg1, arg2) {
  console.log ( arg1 + arg2 );
}

How to push both key and value into an Array in Jquery

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets

Java get month string from integer

DateFormatSymbols class provides methods for our ease use.

To get short month strings. For example: "Jan", "Feb", etc.

getShortMonths()

To get month strings. For example: "January", "February", etc.

getMonths()

Sample code to return month string in mmm format,

private static String getShortMonthFromNumber(int month){
    if(month<0 || month>11){
        return "";
    }
    return new DateFormatSymbols().getShortMonths()[month];
}

Java URL encoding of query string parameters

URL url= new URL("http://example.com/query?q=random word £500 bank $");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String correctEncodedURL=uri.toASCIIString(); 
System.out.println(correctEncodedURL);

Prints

http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$

What is happening here?

1. Split URL into structural parts. Use java.net.URL for it.

2. Encode each structural part properly!

3. Use IDN.toASCII(putDomainNameHere) to Punycode encode the host name!

4. Use java.net.URI.toASCIIString() to percent-encode, NFC encoded unicode - (better would be NFKC!). For more info see: How to encode properly this URL

In some cases it is advisable to check if the url is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.

Here are some examples that will also work properly

{
      "in" : "http://???????.com/",
     "out" : "http://xn--mgba3gch31f.com/"
},{
     "in" : "http://www.example.com/?/foo",
     "out" : "http://www.example.com/%E2%80%A5/foo"
},{
     "in" : "http://search.barnesandnoble.com/booksearch/first book.pdf", 
     "out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
}, {
     "in" : "http://example.com/query?q=random word £500 bank $", 
     "out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
}

The solution passes around 100 of the testcases provided by Web Plattform Tests.

403 Forbidden You don't have permission to access /folder-name/ on this server

Solved issue using below steps :

1) edit file "/etc/apache2/sites-enabled/000-default.conf"

    DocumentRoot "dir_name"

    ServerName <server_IP>

    <Directory "dir_name">
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
    </Directory>

    <Directory "dir_name">
       AllowOverride None
       # Allow open access:
       Require all granted

2) change folder permission sudo chmod -R 777 "dir_name"

fatal error LNK1169: one or more multiply defined symbols found in game programming

The two int variables are defined in the header file. This means that every source file which includes the header will contain their definition (header inclusion is purely textual). The of course leads to multiple definition errors.

You have several options to fix this.

  1. Make the variables static (static int WIDTH = 1024;). They will still exist in each source file, but their definitions will not be visible outside of the source file.

  2. Turn their definitions into declarations by using extern (extern int WIDTH;) and put the definition into one source file: int WIDTH = 1024;.

  3. Probably the best option: make the variables const (const int WIDTH = 1024;). This makes them static implicitly, and also allows them to be used as compile-time constants, allowing the compiler to use their value directly instead of issuing code to read it from the variable etc.

How to represent multiple conditions in a shell if statement?

#!/bin/bash

current_usage=$( df -h | grep 'gfsvg-gfslv' | awk {'print $5'} )
echo $current_usage
critical_usage=6%
warning_usage=3%

if [[ ${current_usage%?} -lt ${warning_usage%?} ]]; then
echo OK current usage is $current_usage
elif [[ ${current_usage%?} -ge ${warning_usage%?} ]] && [[ ${current_usage%?} -lt ${critical_usage%?} ]]; then
echo Warning $current_usage
else
echo Critical $current_usage
fi

iFrame onload JavaScript event

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

Question mark and colon in JavaScript

? : isn't this the ternary operator?

var x= expression ? true:false

Using JAXB to unmarshal/marshal a List<String>

From a personal blog post, it is not necessary to create a specific JaxbList < T > object.

Assuming an object with a list of strings:

@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}

A JAXB round trip:

public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}

Produces the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

MS-access reports - The search key was not found in any record - on save

In Access 2007 this error occurs when importing an Excel file where there are two fields with the same column header.

How to detect when facebook's FB.init is complete

While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.

It can be used like so:

f52.fb.ready(function() {
    // safe to use FB here
});

Here's the source file (note that it's defined within a 'f52.fb' namespace).

if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {

    var fbAppId = f52.inputs.base.fbAppId,
        fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function() {
        FB.init({
            appId: fbAppId,
            xfbml: true,
            version: 'v2.0'
        });

        FB.getLoginStatus(function(response){
            fbApiInit = true;
            notifyQ();
        });
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

How can I be notified when an element is added to the page?

ETA 24 Apr 17 I wanted to simplify this a bit with some async/await magic, as it makes it a lot more succinct:

Using the same promisified-observable:

const startObservable = (domNode) => {
  var targetNode = domNode;

  var observerConfig = {
    attributes: true,
    childList: true,
    characterData: true
  };

  return new Promise((resolve) => {
      var observer = new MutationObserver(function (mutations) {
         // For the sake of...observation...let's output the mutation to console to see how this all works
         mutations.forEach(function (mutation) {
             console.log(mutation.type);
         });
         resolve(mutations)
     });
     observer.observe(targetNode, observerConfig);
   })
} 

Your calling function can be as simple as:

const waitForMutation = async () => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {
      const results = await startObservable(someDomNode)
      return results
    } catch (err) { 
      console.error(err)
    }
}

If you wanted to add a timeout, you could use a simple Promise.race pattern as demonstrated here:

const waitForMutation = async (timeout = 5000 /*in ms*/) => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {

      const results = await Promise.race([
          startObservable(someDomNode),
          // this will throw after the timeout, skipping 
          // the return & going to the catch block
          new Promise((resolve, reject) => setTimeout(
             reject, 
             timeout, 
             new Error('timed out waiting for mutation')
          )
       ])
      return results
    } catch (err) { 
      console.error(err)
    }
}

Original

You can do this without libraries, but you'd have to use some ES6 stuff, so be cognizant of compatibility issues (i.e., if your audience is mostly Amish, luddite or, worse, IE8 users)

First, we'll use the MutationObserver API to construct an observer object. We'll wrap this object in a promise, and resolve() when the callback is fired (h/t davidwalshblog)david walsh blog article on mutations:

const startObservable = (domNode) => {
    var targetNode = domNode;

    var observerConfig = {
        attributes: true,
        childList: true,
        characterData: true
    };

    return new Promise((resolve) => {
        var observer = new MutationObserver(function (mutations) {
            // For the sake of...observation...let's output the mutation to console to see how this all works
            mutations.forEach(function (mutation) {
                console.log(mutation.type);
            });
            resolve(mutations)
        });
        observer.observe(targetNode, observerConfig);
    })
} 

Then, we'll create a generator function. If you haven't used these yet, then you're missing out--but a brief synopsis is: it runs like a sync function, and when it finds a yield <Promise> expression, it waits in a non-blocking fashion for the promise to be fulfilled (Generators do more than this, but this is what we're interested in here).

// we'll declare our DOM node here, too
let targ = document.querySelector('#domNodeToWatch')

function* getMutation() {
    console.log("Starting")
    var mutations = yield startObservable(targ)
    console.log("done")
}

A tricky part about generators is they don't 'return' like a normal function. So, we'll use a helper function to be able to use the generator like a regular function. (again, h/t to dwb)

function runGenerator(g) {
    var it = g(), ret;

    // asynchronously iterate over generator
    (function iterate(val){
        ret = it.next( val );

        if (!ret.done) {
            // poor man's "is it a promise?" test
            if ("then" in ret.value) {
                // wait on the promise
                ret.value.then( iterate );
            }
            // immediate value: just send right back in
            else {
                // avoid synchronous recursion
                setTimeout( function(){
                    iterate( ret.value );
                }, 0 );
            }
        }
    })();
}

Then, at any point before the expected DOM mutation might happen, simply run runGenerator(getMutation).

Now you can integrate DOM mutations into a synchronous-style control flow. How bout that.

An invalid form control with name='' is not focusable

There are things that still surprises me... I have a form with dynamic behaviour for two different entities. One entity requires some fields that the other don't. So, my JS code, depending on the entity, does something like: $('#periodo').removeAttr('required'); $("#periodo-container").hide();

and when the user selects the other entity: $("#periodo-container").show(); $('#periodo').prop('required', true);

But sometimes, when the form is submitted, the issue apppears: "An invalid form control with name=periodo'' is not focusable (i am using the same value for the id and name).

To fix this problem, you have to ensurance that the input where you are setting or removing 'required' is always visible.

So, what I did is:

$("#periodo-container").show(); //for making sure it is visible
$('#periodo').removeAttr('required'); 
$("#periodo-container").hide(); //then hide

Thats solved my problem... unbelievable.

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Failed to load resource: net::ERR_INSECURE_RESPONSE

If you're developing, and you're developing with a Windows machine, simply add localhost as a Trusted Site.

And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...

I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.

To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.

Example for manual parsing:

var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));

Example using date.js:

var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

Leap year calculation

Python 3.5

def is_leap_baby(year):
    if ((year % 4 is 0) and (year % 100 is not 0)) or (year % 400 is 0):
        return "{0}, {1} is a leap year".format(True, year)
    return "{0} is not a leap year".format(year)

print(is_leap_baby(2014))
print(is_leap_baby(2012))

Creating a triangle with for loops

I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.

Let's think about writing a method to print a single line, telling the method which number line it is:

public void printTriangleLine(int rowNumber) {
    // we have to work out what to put here
}

We have to print some number of spaces, then some number of stars.

Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.

Let's invent a method that prints the rows of characters for us, and use it:

public void printTriangleLine(int rowNumber) {
    printSequence(" ", 5 - rowNumber);
    printSequence("*", 2 * rowNumber + 1);
    System.out.println(); 
}

That won't compile until we actually write printSequence(), so let's do that:

public void printSequence(String s, int repeats) {
    for(int i=0; i<repeats; i++) {
        System.out.print(s);
    }
}

Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()

public static void main(String [] args) {
    printSequence("a",3);
    System.out.println();
    printTriangleLine(2);
}

... run it and verify (with your eyes) that it outputs:

aaa
   *****

When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:

assertEquals("   *****", TriangleDrawer.triangleLine(2));
assertEquals("     *", TriangleDrawer.triangleLine(0))

Now we have the pieces we need to draw a triangle.

public void drawTriangle() {
    for(int i=0; i<5; i++) {
        printTriangleLine(i);
    }
}

The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.

For extra credit:

  • adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use System.out.print(drawTriangle())
  • adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call drawTriangle(3) or drawTriangle(5)
  • make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

You could try by these ways. 1st.

sudo chown -R mongod:mongod /data/db

but at some times,this is not useful. 2nd. if the above way is not useful,you can try to do this:

mkdir /data/db #as the database storage path

nohup mongod --dbpath /data/db &

or type:

mongod --dbpath /data/db

to get the output stream

Calculate the execution time of a method

Following this Microsoft Doc:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Output: RunTime 00:00:09.94

Error in plot.new() : figure margins too large in R

I have just use the Clear all plots then again give the plot command and it was helpfull

Django download a file

Reference:

In view.py Implement function like,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response

Android YouTube app Play Video Intent

Try this:

public class abc extends Activity implements OnPreparedListener{

  /** Called when the activity is first created. */

  @Override
    public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM")));          


    @Override
      public void onPrepared(MediaPlayer mp) {
        // TODO Auto-generated method stub

    }
  }
}

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

Login credentials not working with Gmail SMTP

I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.

Log in to your Google account, and use these links:

Step 1 [Link of Disabling 2-step verification]:

https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

Step 2: [Link for Allowing less secure apps]

https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

It should be all good now.

Setting Remote Webdriver to run tests in a remote computer using Java

This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

What is recursion and when should I use it?

Recursion is solving a problem with a function that calls itself. A good example of this is a factorial function. Factorial is a math problem where factorial of 5, for example, is 5 * 4 * 3 * 2 * 1. This function solves this in C# for positive integers (not tested - there may be a bug).

public int Factorial(int n)
{
    if (n <= 1)
        return 1;

    return n * Factorial(n - 1);
}

Negative weights using Dijkstra's Algorithm

you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.

this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]

in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Android toolbar center title and custom font

Try

@Override
    public void onBackPressed() {
          if(getTitle().equals(getResources().getString(R.string.app_name))) {
            super.onBackPressed();}
          else {
//set visiblity
           }
}

How do relative file paths work in Eclipse?

This is really similar to another question. How should I load files into my Java application?

How should I load my files into my Java Application?

You do not want to load your files in by:

C:\your\project\file.txt

this is bad!

You should use getResourceAsStream.

InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);

And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

Debug assertion failed. C++ vector subscript out of range

Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0 (0, 1, ..., 9). So in your second loop v[j] is invalid, when j is 10.

This will fix the error:

for(int j = 9;j >= 0;--j)
{
    cout << v[j];
}

In general it's better to think about indexes as 0 based, so I suggest you change also your first loop to this:

for(int i = 0;i < 10;++i)
{
    v.push_back(i);
}

Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):

for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
    std::cout << *i << std::endl;
}

Having Django serve downloadable files

Just mentioning the FileResponse object available in Django 1.10

Edit: Just ran into my own answer while searching for an easy way to stream files via Django, so here is a more complete example (to future me). It assumes that the FileField name is imported_file

views.py

from django.views.generic.detail import DetailView   
from django.http import FileResponse
class BaseFileDownloadView(DetailView):
  def get(self, request, *args, **kwargs):
    filename=self.kwargs.get('filename', None)
    if filename is None:
      raise ValueError("Found empty filename")
    some_file = self.model.objects.get(imported_file=filename)
    response = FileResponse(some_file.imported_file, content_type="text/csv")
    # https://docs.djangoproject.com/en/1.11/howto/outputting-csv/#streaming-large-csv-files
    response['Content-Disposition'] = 'attachment; filename="%s"'%filename
    return response

class SomeFileDownloadView(BaseFileDownloadView):
    model = SomeModel

urls.py

...
url(r'^somefile/(?P<filename>[-\w_\\-\\.]+)$', views.SomeFileDownloadView.as_view(), name='somefile-download'),
...

How to tell if a JavaScript function is defined

If you look at the source of the library @Venkat Sudheer Reddy Aedama mentioned, underscorejs, you can see this:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

This is just my HINT, HINT answer :>

What is the connection string for localdb for version 11

I had the same problem for a bit. I noticed that I had:

Data Source= (localdb)\v11.0"

Simply by adding one back-slash it solved the problem for me:

Data Source= (localdb)\\v11.0"

Twitter Bootstrap modal on mobile devices

EDIT: An unofficial Bootstrap Modal modification has been built to address responsive/mobile issues. This is perhaps the simplest and easiest way to remedy the problem.

There has since been a fix found in one of the issues you discussed earlier

in bootstrap-responsive.css

.modal { 
    position: fixed; 
    top: 3%; 
    right: 3%; 
    left: 3%; 
    width: auto; 
    margin: 0; 
}
.modal-body { 
    height: 60%; 
}

and in bootstrap.css

.modal-body { 
    max-height: 350px; 
    padding: 15px; 
    overflow-y: auto; 
    -webkit-overflow-scrolling: touch; 
 }

T-SQL split string

There is a correct version on here but I thought it would be nice to add a little fault tolerance in case they have a trailing comma as well as make it so you could use it not as a function but as part of a larger piece of code. Just in case you're only using it once time and don't need a function. This is also for integers (which is what I needed it for) so you might have to change your data types.

DECLARE @StringToSeperate VARCHAR(10)
SET @StringToSeperate = '1,2,5'

--SELECT @StringToSeperate IDs INTO #Test

DROP TABLE #IDs
CREATE TABLE #IDs (ID int) 

DECLARE @CommaSeperatedValue NVARCHAR(255) = ''
DECLARE @Position INT = LEN(@StringToSeperate)

--Add Each Value
WHILE CHARINDEX(',', @StringToSeperate) > 0
BEGIN
    SELECT @Position  = CHARINDEX(',', @StringToSeperate)  
    SELECT @CommaSeperatedValue = SUBSTRING(@StringToSeperate, 1, @Position-1)

    INSERT INTO #IDs 
    SELECT @CommaSeperatedValue

    SELECT @StringToSeperate = SUBSTRING(@StringToSeperate, @Position+1, LEN(@StringToSeperate)-@Position)

END

--Add Last Value
IF (LEN(LTRIM(RTRIM(@StringToSeperate)))>0)
BEGIN
    INSERT INTO #IDs
    SELECT SUBSTRING(@StringToSeperate, 1, @Position)
END

SELECT * FROM #IDs

SQLiteDatabase.query method

db.query(
        TABLE_NAME,
        new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
        TABLE_ROW_ID + "=" + rowID,
        null, null, null, null, null
);

TABLE_ROW_ID + "=" + rowID, here = is the where clause. To select all values you will have to give all column names:

or you can use a raw query like this 
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);

and here is a good tutorial for database.

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

MySQL SELECT statement for the "length" of the field is greater than 1

Just in case anybody want to find how in oracle and came here (like me), the syntax is

select length(FIELD) from TABLE

just in case ;)

How do I auto size a UIScrollView to fit its content

Following extension would be helpful in Swift.

extension UIScrollView{
    func setContentViewSize(offset:CGFloat = 0.0) {
        // dont show scroll indicators
        showsHorizontalScrollIndicator = false
        showsVerticalScrollIndicator = false

        var maxHeight : CGFloat = 0
        for view in subviews {
            if view.isHidden {
                continue
            }
            let newHeight = view.frame.origin.y + view.frame.height
            if newHeight > maxHeight {
                maxHeight = newHeight
            }
        }
        // set content size
        contentSize = CGSize(width: contentSize.width, height: maxHeight + offset)
        // show scroll indicators
        showsHorizontalScrollIndicator = true
        showsVerticalScrollIndicator = true
    }
}

Logic is the same with the given answers. However, It omits hidden views within UIScrollView and calculation is performed after scroll indicators set hidden.

Also, there is an optional function parameter and you're able to add an offset value by passing parameter to function.

new DateTime() vs default(DateTime)

If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

The following line will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will compile:

    private void MyMethod(DateTime syncedTime = default(DateTime))

java.lang.OutOfMemoryError: Java heap space in Maven

I have solved this problem on my side by 2 ways:

  1. Adding this configuration in pom.xml

    <configuration><argLine>-Xmx1024m</argLine></configuration>
    
  2. Switch to used JDK 1.7 instead of 1.6

How to change the background-color of jumbrotron?

just and another class to jumbotron

bg-transparent

It will work perfectly

bootstrap color documentation: https://getbootstrap.com/docs/4.3/utilities/colors/

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

How can I find the number of days between two Date objects in Ruby?

Subtract the beginning date from the end date:

endDate - beginDate 

npm install -g less does not work: EACCES: permission denied

Run these commands in a terminal window (note: DON'T replace the $USER part... thats a linux command to get your user!):

sudo chown -R $USER ~/.npm
sudo chown -R $USER /usr/lib/node_modules
sudo chown -R $USER /usr/local/lib/node_modules

Break when a value changes using the Visual Studio debugger

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

REST API using POST instead of GET

Think about it. When your client makes a GET request to an URI X, what it's saying to the server is: "I want a representation of the resource located at X, and this operation shouldn't change anything on the server." A PUT request is saying: "I want you to replace whatever is the resource located at X with the new entity I'm giving you on the body of this request". A DELETE request is saying: "I want you to delete whatever is the resource located at X". A PATCH is saying "I'm giving you this diff, and you should try to apply it to the resource at X and tell me if it succeeds." But a POST is saying: "I'm sending you this data subordinated to the resource at X, and we have a previous agreement on what you should do with it."

If you don't have it documented somewhere that the resource expects a POST and does something with it, it doesn't make sense to send a POST to it expecting it to act like a GET.

REST relies on the standardized behavior of the underlying protocol, and POST is precisely the method used for an action that isn't standardized. The result of a GET, PUT and DELETE requests are clearly defined in the standard, but POST isn't. The result of a POST is subordinated to the server, so if it's not documented that you can use POST to do something, you have to assume that you can't.

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

Are HTTP cookies port specific?

The current cookie specification is RFC 6265, which replaces RFC 2109 and RFC 2965 (both RFCs are now marked as "Historic") and formalizes the syntax for real-world usages of cookies. It clearly states:

  1. Introduction

...

For historical reasons, cookies contain a number of security and privacy infelicities. For example, a server can indicate that a given cookie is intended for "secure" connections, but the Secure attribute does not provide integrity in the presence of an active network attacker. Similarly, cookies for a given host are shared across all the ports on that host, even though the usual "same-origin policy" used by web browsers isolates content retrieved via different ports.

And also:

8.5. Weak Confidentiality

Cookies do not provide isolation by port. If a cookie is readable by a service running on one port, the cookie is also readable by a service running on another port of the same server. If a cookie is writable by a service on one port, the cookie is also writable by a service running on another port of the same server. For this reason, servers SHOULD NOT both run mutually distrusting services on different ports of the same host and use cookies to store security sensitive information.

python: urllib2 how to send cookie with urlopen request

Cookie is just another HTTP header.

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

See urllib2 examples for other ways how to add HTTP headers to your request.

There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.

Solving a "communications link failure" with JDBC and MySQL

Go to Windows services in the control panel and start the MySQL service. For me it worked. When I was doing a Java EE project I got this error" Communication link failure". I restarted my system and then it worked.

After that I again got the same error even after restarting my system. Then I tried to open the MySQL command line console and login with root, even then it gave me an error.

Finally when I started the MySQL service from Windows services, it worked.

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Script to Change Row Color when a cell changes text

Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.

Assuming the "Status" was Column D:

Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as

=RegExMatch($D2,"Complete")

or

=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))

Edit (thanks to Frederik Schøning)

=RegExMatch($D2,"(?i)Complete") then set the range to cover all the rows e.g. A2:Z10. This is case insensitive, so will match complete, Complete or CoMpLeTe.

You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.

Remove a file from the list that will be committed

Maybe you could also use stash to store temporaly your modifications in a patch file and then reapply it (after a checkout to come back to the old version). This could be related to this other topic : How would I extract a single file (or changes to a file) from a git stash?.

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

how to zip a folder itself using java

I usually use a helper class I once wrote for this task:

import java.util.zip.*;
import java.io.*;

public class ZipExample {
    public static void main(String[] args){
        ZipHelper zippy = new ZipHelper();
        try {
            zippy.zipDir("folderName","test.zip");
        } catch(IOException e2) {
            System.err.println(e2);
        }
    }
}

class ZipHelper  
{
    public void zipDir(String dirName, String nameZipFile) throws IOException {
        ZipOutputStream zip = null;
        FileOutputStream fW = null;
        fW = new FileOutputStream(nameZipFile);
        zip = new ZipOutputStream(fW);
        addFolderToZip("", dirName, zip);
        zip.close();
        fW.close();
    }

    private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException {
        File folder = new File(srcFolder);
        if (folder.list().length == 0) {
            addFileToZip(path , srcFolder, zip, true);
        }
        else {
            for (String fileName : folder.list()) {
                if (path.equals("")) {
                    addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
                } 
                else {
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);
                }
            }
        }
    }

    private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException {
        File folder = new File(srcFile);
        if (flag) {
            zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/"));
        }
        else {
            if (folder.isDirectory()) {
                addFolderToZip(path, srcFile, zip);
            }
            else {
                byte[] buf = new byte[1024];
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
                while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
                }
            }
        }
    }
}

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

Java integer to byte array

The chunks below work at least for sending an int over UDP.

int to byte array:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

byte array to int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}

How can I extract embedded fonts from a PDF as valid font files?

Even though this question is 10 years old, it is still valid and as technology changes so does a valid answer.

In searching the current answers noticed none of them note WOFF (Web Open Font Format) (W3C) (Wikipedia) which can be used to recreate the individual characters (glyphs) and display them in a web page accurately.

Using the free online web page by IDR Solutions, PDF to HTML5 (link), convert a PDF to a zip file. In the resulting zip will be a font directory of woff file types. Current Internet browsers support woff files if you were not aware. (reference) These can be examined at the online site FontDrop! (link).

WOFF files can be converted to/from OTF or TTF at WOFFer – WOFF font converter

Also the zip file from PDF to HTML5 will contain an HTML file for each page of the PDF that can be opened in an Internet browser and is one of the best and most accurate PDF translations I have found or seen.

While I am just learning how to use WOFF files, this is worth passing along. Enjoy.

PS, I will probably update with more info as I learn more about using woff file types, but as this is creative commons, feel free to edit this answer if you have something of value to pass along.

In Perl, how can I read an entire file into a string?

A simple way is:

while (<FILE>) { $document .= $_ }

Another way is to change the input record separator "$/". You can do it locally in a bare block to avoid changing the global record separator.

{
    open(F, "filename");
    local $/ = undef;
    $d = <F>;
}

HttpClient - A task was cancelled?

I was using a simple call instead of async. As soon I added await and made method async it started working fine.

public async Task<T> ExecuteScalarAsync<T>(string query, object parameter = null, CommandType commandType = CommandType.Text) where T : IConvertible
        {
            using (IDbConnection db = new SqlConnection(_con))
            {
                return await db.ExecuteScalarAsync<T>(query, parameter, null, null, commandType);
            }
        }

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I enabled zlib.output_compression in php.ini and it seemed to fix the issue for me.

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

I'm afraid that WhatsApp for Android does not currently support to be called from a web browser.

I had the same requirement for my current project, and since I couldn't find any proper information I ended up downloading the APK file.

In Android, if an application wants to be called from a web browser, it needs to define an Activity with the category android.intent.category.BROWSABLE.

You can find more information about this here: https://developers.google.com/chrome/mobile/docs/intents

If you take a look to the WhatsApp AndroidManifest.xml file, the only Activiy with category BROWSABLE is this one:

<activity android:name="com.whatsapp.Conversation"   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
        <intent-filter>
            <action android:name="android.intent.action.SENDTO" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="sms" />
            <data android:scheme="smsto" />
        </intent-filter>
    </activity>

I've been playing with it for a while, and I couldn't make it to work. The most I got was to open the WhatsApp application from Chrome, but I couldn't figure out a way to set the message content and recipient.

Since it is not documented by the WhatsApp team, I think this is still work in progress. It looks like in the future WhatsApp will handle SMS too.

The only way to get more information is by reaching the WhatsApp dev team, what I tried, but I'm still waiting for a response.

Regards!

sql how to cast a select query

And when you use a case :

CASE
WHEN TB1.COD IS NULL THEN
    TB1.COD || ' - ' || TB1.NAME
ELSE
    TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,

preg_match in JavaScript?

This should work:

var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];

How to install libusb in Ubuntu

First,

sudo apt-get install libusb-1.0-0-dev

updatedb && locate libusb.h.

Second, replace <libusb.h> with <libusb-1.0/libusb.h>.

update:

don't need to change any file.just add this to your Makefile.

`pkg-config libusb-1.0 --libs --cflags`

its result is that -I/usr/include/libusb-1.0 -lusb-1.0

Jquery: Find Text and replace

More specific:

$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));

Calculating bits required to store decimal number

Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.

For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits

Get top n records for each group of grouped results

Check this out:

SELECT
  p.Person,
  p.`Group`,
  p.Age
FROM
  people p
  INNER JOIN
  (
    SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`
    UNION
    SELECT MAX(p3.Age) AS Age, p3.`Group` FROM people p3 INNER JOIN (SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`) p4 ON p3.Age < p4.Age AND p3.`Group` = p4.`Group` GROUP BY `Group`
  ) p2 ON p.Age = p2.Age AND p.`Group` = p2.`Group`
ORDER BY
  `Group`,
  Age DESC,
  Person;

SQL Fiddle: http://sqlfiddle.com/#!2/cdbb6/15

There is an error in XML document (1, 41)

In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map

git pull fails "unable to resolve reference" "unable to update local ref"

Just ran into the problem today.

Troubleshooting method: With SourceTree on Windows Servers, you may try to run it as an Administrator. That fixes my problem of "unable to update local ref" on Atlassian Source Tree 2.1.2.5 on a Windows Server 2012 R2 in domain.

If you can too replicate this situation, it proves that the problem is caused by permission issue. It's better to drill down and find the root cause - probably some particular files are owned by other users and such - otherwise there's an unwelcome side-effect: you'll have to run SourceTree as Administrator for the rest of eternity.

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

SQL Server: Examples of PIVOTing String data

I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below

PIVOT(
  min(value)
  FOR ColTitle in([F4], [UR], [UQ])
 )

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

Running Python on Windows for Node.js dependencies

i can't help but to mention this. If you're using Python3 and failing with node-gyp, then i'm sad to tell you node-gyp currently doesn't support python3.

Here is a link for you: https://github.com/nodejs/node-gyp/issues/1268 https://github.com/nodejs/node-gyp/issues/193

How do I remove a key from a JavaScript object?

It's as easy as:

delete object.keyname;

or

delete object["keyname"];