Programs & Examples On #Libjingle

libjingle is a collection of open-source C++ code and sample applications that enables you to build a peer-to-peer application.

Copy or rsync command

if you are using cp doesn't save existing files when copying folders of the same name. Lets say you have this folders:

/myFolder
  someTextFile.txt

/someOtherFolder
  /myFolder
    wellHelloThere.txt

Then you copy one over the other:

cp /someOtherFolder/myFolder /myFolder

result:

/myFolder
  wellHelloThere.txt

This is at least what happens on macOS and I wanted to preserve the diff files so I used rsync.

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

C# how to use enum with switch

All the other answers are correct, but you also need to call your method correctly:

Calculate(5, 5, Operator.PLUS))

And since you use int for left and right, the result will be int as well (3/2 will result in 1). you could cast to double before calculating the result or modify your parameters to accept double

How can I display the current branch and folder path in terminal?

From Mac OS Catalina .bash_profile is replaced with .zprofile

Step 1: Create a .zprofile

touch .zprofile

Step 2:

nano .zprofile

type below line in this

source ~/.bash_profile

and save(ctrl+o return ctrl+x)

Step 3: Restart your terminal

To Add Git Branch Name Now you can add below lines in .bash_profile

    parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Restart your terminal this will work.

Note: Even you can rename .bash_profile to .zprofile that also works.

How to build x86 and/or x64 on Windows from command line with CMAKE?

This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.

To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.

For CMake 3.13 or newer, run the following commands:

cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release

For earlier versions of CMake, run the following commands:

mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release

CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build followed by the build directory. The --config option specifies the build configuration.

Getting index value on razor foreach

//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
    <li>The index is @myItem.i and a value is @myItem.value.Name</li>
}

More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/

How to convert 1 to true or 0 to false upon model fetch

All you need is convert string to int with + and convert the result to boolean with !!:

var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked

You can do this manipulation in the parse method:

parse: function (response) {
  response.isChecked = !!+response.isChecked;
  return response;
}

UPDATE: 7 years later, I find Number(string) conversion more elegant. Also mutating an object is not the best idea. That being said:

parse: function (response) {
  return Object.assign({}, response, {
    isChecked: !!Number(response.isChecked), // OR
    isChecked: Boolean(Number(response.isChecked))
  });
}

How can I get the first two digits of a number?

You can use a regular expression to test for a match and capture the first two digits:

import re

for i in range(1000):
    match = re.match(r'(1[56])', str(i))

    if match:
        print(i, 'begins with', match.group(1))

The regular expression (1[56]) matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.

Output:

15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16

How to group dataframe rows into list in pandas groupby

If performance is important go down to numpy level:

import numpy as np

df = pd.DataFrame({'a': np.random.randint(0, 60, 600), 'b': [1, 2, 5, 5, 4, 6]*100})

def f(df):
         keys, values = df.sort_values('a').values.T
         ukeys, index = np.unique(keys, True)
         arrays = np.split(values, index[1:])
         df2 = pd.DataFrame({'a':ukeys, 'b':[list(a) for a in arrays]})
         return df2

Tests:

In [301]: %timeit f(df)
1000 loops, best of 3: 1.64 ms per loop

In [302]: %timeit df.groupby('a')['b'].apply(list)
100 loops, best of 3: 5.26 ms per loop

How to serve .html files with Spring

In case you use spring boot, you must not set the properties spring.mvc.view.prefix and spring.mvc.view.suffix in your application.properties file, instead configure the bean ViewResolver from a configuration class.

application.properties

# Configured in @Configuration GuestNav
#spring.mvc.view.prefix=/WEB-INF/views/
#spring.mvc.view.suffix=.jsp
# Live reload
spring.devtools.restart.additional-paths=.
# Better logging
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.file-date-format=yyyy-MM-dd
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log

Main method

@SpringBootApplication
public class WebApp extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApp.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApp.class, args);
    }

}

Configuration class

@Configuration
@EnableWebMvc
public class DispatcherConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/views/**").addResourceLocations("/views/");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/notinuse/");
        viewResolver.setSuffix("");
        return viewResolver;
    }

}

A controller class

@Controller
public class GuestNav {

    @GetMapping("/")
    public String home() {
        return "forward:/views/guest/index.html";
    }
}

You must place your files in the directory /webapp/views/guest/index.html, be careful, the webapp directory is outside of the resources directory.
In this way you may use the url patterns of spring-mvc but serve static context.

How to search multiple columns in MySQL?

If your table is MyISAM:

SELECT  *
FROM    pages
WHERE   MATCH(title, content) AGAINST ('keyword' IN BOOLEAN MODE)

This will be much faster if you create a FULLTEXT index on your columns:

CREATE FULLTEXT INDEX fx_pages_title_content ON pages (title, content)

, but will work even without the index.

javascript check for not null

this will do the trick for you

if (!!val) {
    alert("this is not null")
} else {
    alert("this is null")
}

PHP Constants Containing Arrays?

Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

Why are iframes considered dangerous and a security risk?

As soon as you're displaying content from another domain, you're basically trusting that domain not to serve-up malware.

There's nothing wrong with iframes per se. If you control the content of the iframe, they're perfectly safe.

Why shouldn't I use "Hungarian Notation"?

Joel Spolsky wrote a good blog post about this. http://www.joelonsoftware.com/articles/Wrong.html Basically it comes down to not making your code harder to read when a decent IDE will tell you want type the variable is if you can't remember. Also, if you make your code compartmentalized enough, you don't have to remember what a variable was declared as three pages up.

How to delete a certain row from mysql table with same column values?

Add a limit to the delete query

delete from orders 
where id_users = 1 and id_product = 2
limit 1

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="0.01" /> if you are targeting 2 decimal places :-).

Accessing nested JavaScript objects and arrays by string path

I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.

You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:

> var jsocrud = require('jsocrud');

...

// Get (Read) ---
> var obj = {
>     foo: [
>         {
>             'key w/ non-word chars': 'bar'
>         }
>     ]
> };
undefined

> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'

https://www.npmjs.com/package/jsocrud

https://github.com/vertical-knowledge/jsocrud

SQL Server String or binary data would be truncated

As others have already said, one of your columns datatypes in the source table is larger than your destination columns.

A simple solution is to simply turn off the warning and allow truncation to take place. So, if you're receiving this error but you are sure it is acceptable for data in your old database/table to be truncated (cut to size) you can simply do the following;

SET ANSI_WARNINGS  OFF;
-- Your insert TSQL here.
SET ANSI_WARNINGS ON;

As above, always remember to turn warnings back on again afterwards. I hope this helps.

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

send mail from linux terminal in one line

Sending Simple Mail:

$ mail -s "test message from centos" [email protected]
hello from centos linux command line

Ctrl+D to finish

How to make the overflow CSS property work with hidden as value

Ok if anyone else is having this problem this may be your answer:

If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.

Send PHP variable to javascript function

Just write:

<script>
    var my_variable_name = "<?php echo $php_string; ?>";
</script>

Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.

Merge two (or more) lists into one, in C# .NET

When you got few list but you don't know how many exactly, use this:

listsOfProducts contains few lists filled with objects.

List<Product> productListMerged = new List<Product>();

listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

Try with the fully qualified name for the resource:

private static final String FILENAME = "resources/skyscrapper";

Remove useless zero digits from decimals in PHP

This is my solution. I want to keep ability to add thousands separator

    $precision = 5;    
    $number = round($number, $precision);
    $decimals = strlen(substr(strrchr($number, '.'), 1));
    return number_format($number, $precision, '.', ',');

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The is keyword is a test for object identity while == is a value comparison.

If you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

javascript create empty array of a given size

In 2018 and thenceforth we shall use [...Array(500)] to that end.

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

Add This Two Schema locations. That's enough and Efficient instead of adding all the unnecessary schema

 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd

Automatic confirmation of deletion in powershell

Add -confirm:$false to suppress confirmation.

Checking for empty or null JToken in a JObject

Try something like this to convert JToken to JArray:

static public JArray convertToJArray(JToken obj)
{
    // if ((obj).Type == JTokenType.Null) --> You can check if it's null here

    if ((obj).Type == JTokenType.Array)
        return (JArray)(obj);
    else
        return new JArray(); // this will return an empty JArray
}

Scala vs. Groovy vs. Clojure

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

Regular expression to return text between parenthesis

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

React router nav bar example

Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.

Nav.js

  import React from 'react';
  import { Link } from 'react-router';

  export default class Nav extends React.Component {
    render() {    
      return (
        <nav className="Nav">
          <div className="Nav__container">
            <Link to="/" className="Nav__brand">
              <img src="logo.svg" className="Nav__logo" />
            </Link>

            <div className="Nav__right">
              <ul className="Nav__item-wrapper">
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path1">Link 1</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path2">Link 2</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path3">Link 3</Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
      );
    }
  }

App.js

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
            <div>
              <Nav />
              <Switch>
                <Route exactly component={Landing} pattern="/" />
                <Route exactly component={Page1} pattern="/path1" />
                <Route exactly component={Page2} pattern="/path2" />
                <Route exactly component={Page3} pattern="/path3" />
                <Route component={Page404} />
              </Switch>
            </div>
          </Router>
        </div>
      );
    }
  }

Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar

Edit

A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
      <div>
        <Header/>
        <Component {...props}/>
      </div>
    )}/>
  )

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
              <Switch>
                <NavRoute exactly component={Landing} pattern="/" />
                <Route exactly component={Login} pattern="/login" />
                <NavRoute exactly component={Page1} pattern="/path1" />
                <NavRoute exactly component={Page2} pattern="/path2" />
                <NavRoute component={Page404} />
              </Switch>
          </Router>
        </div>
      );
    }
  }

Maven Jacoco Configuration - Exclude classes/packages from report not working

Use sonar.coverage.exclusions property.

mvn clean install -Dsonar.coverage.exclusions=**/*ToBeExcluded.java

This should exclude the classes from coverage calculation.

iTerm2 keyboard shortcut - split pane navigation

?+?+?/?/?/? will let you navigate split panes in the direction of the arrow, i.e. when using ?+D to split panes vertically, ?+?+? and ?+?+? will let you switch between the panes.

Does it matter what extension is used for SQLite database files?

Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.

Defined Edges With CSS3 Filter Blur

If you are using background image, the best way I found is:

filter: blur(5px);
margin-top: -5px;
padding-bottom: 10px;
margin-left: -5px;
padding-right: 10px;

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

System.Net.WebException HTTP status code

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

How to pretty print XML from the command line?

You can also use tidy, which may need to be installed first (e.g. on Ubuntu: sudo apt-get install tidy).

For this, you would issue something like following:

tidy -xml -i your-file.xml > output.xml

Note: has many additional readability flags, but word-wrap behavior is a bit annoying to untangle (http://tidy.sourceforge.net/docs/quickref.html).

jQuery scroll to element

To show the full element (if it's possible with the current window size):

var element       = $("#some_element");
var elementHeight = element.height();
var windowHeight  = $(window).height();

var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);

Insert all values of a table into another table in SQL

I think this statement might do what you want.

INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

How to change UIButton image in Swift

In Swift 4.2 and Xcode 10.1

Add image for selected UIButton

button.addTarget(self, action: #selector(self.onclickDateCheckMark), for: .touchUpInside)//Target 
button.setImage(UIImage.init(named: "uncheck"), for: UIControl.State.normal)//When selected
button.setImage(UIImage.init(named: "check"), for: UIControl.State.highlighted)//When highlighted
button.setImage(UIImage.init(named: "check"), for: UIControl.State.selected)//When selected

But if you want to change selected button image you need to change it's selected state. Then only selected image will appear in your button.

@objc func onclickDateCheckMark(sender:UIButton) {
    if sender.isSelected == true {
        sender.isSelected = false
        print("not Selected")
    }else {
        sender.isSelected = true
        print("Selected")

    }
}

How do I jump out of a foreach loop in C#?

You could avoid explicit loops by taking the LINQ route:

sList.Any(s => s.Equals("ok"))

How do I "un-revert" a reverted Git commit?

A revert commit is just like any other commit in git. Meaning, you can revert it, as in:

git revert 648d7d808bc1bca6dbf72d93bf3da7c65a9bd746

That obviously only makes sense once the changes were pushed, and especially when you can't force push onto the destination branch (which is a good idea for your master branch). If the change has not been pushed, just do cherry-pick, revert or simply remove the revert commit as per other posts.

In our team, we have a rule to use a revert on Revert commits that were committed in the main branch, primarily to keep the history clean, so that you can see which commit reverts what:

      7963f4b2a9d   Revert "Revert "OD-9033 parallel reporting configuration"
      "This reverts commit a0e5e86d3b66cf206ae98a9c989f649eeba7965f.
                    ...
     a0e5e86d3b6    Revert "OD-9055 paralel reporting configuration"
     This reverts commit 648d7d808bc1bca6dbf72d93bf3da7c65a9bd746.
                ...
     Merge pull request parallel_reporting_dbs to master* commit 
    '648d7d808bc1bca6dbf72d93bf3da7c65a9bd746'

This way, you can trace the history and figure out the whole story, and even those without the knowledge of the legacy could work it out for themselves. Whereas, if you cherry-pick or rebase stuff, this valuable information is lost (unless you include it in the comment).

Obviously, if a commit reverted and re-reverted more than once that becomes quite messy.

How to convert JSON object to JavaScript array?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

OnClick vs OnClientClick for an asp:CheckBox?

For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged

window.onload vs $(document).ready()

When you say $(document).ready(f), you tell script engine to do the following:

  1. get the object document and push it, since it's not in local scope, it must do a hash table lookup to find where document is, fortunately document is globally bound so it is a single lookup.
  2. find the object $ and select it, since it's not in local scope, it must do a hash table lookup, which may or may not have collisions.
  3. find the object f in global scope, which is another hash table lookup, or push function object and initialize it.
  4. call ready of selected object, which involves another hash table lookup into the selected object to find the method and invoke it.
  5. done.

In the best case, this is 2 hash table lookups, but that's ignoring the heavy work done by jQuery, where $ is the kitchen sink of all possible inputs to jQuery, so another map is likely there to dispatch the query to correct handler.

Alternatively, you could do this:

window.onload = function() {...}

which will

  1. find the object window in global scope, if the JavaScript is optimized, it will know that since window isn't changed, it has already the selected object, so nothing needs to be done.
  2. function object is pushed on the operand stack.
  3. check if onload is a property or not by doing a hash table lookup, since it is, it is called like a function.

In the best case, this costs a single hash table lookup, which is necessary because onload must be fetched.

Ideally, jQuery would compile their queries to strings that can be pasted to do what you wanted jQuery to do but without the runtime dispatching of jQuery. This way you have an option of either

  1. do dynamic dispatch of jquery like we do today.
  2. have jQuery compile your query to pure JavaScript string that can be passed to eval to do what you want.
  3. copy the result of 2 directly into your code, and skip the cost of eval.

Close dialog on click (anywhere)

If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:

$('body').on('click','.ui-widget-overlay', function() {
    $('.ui-dialog').filter(function () {
    return $(this).css("display") === "block";
    }).find('.ui-dialog-content').dialog('close');
});

(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)

Non-recursive depth first search algorithm

You can use a stack. I implemented graphs with Adjacency Matrix:

void DFS(int current){
    for(int i=1; i<N; i++) visit_table[i]=false;
    myStack.push(current);
    cout << current << "  ";
    while(!myStack.empty()){
        current = myStack.top();
        for(int i=0; i<N; i++){
            if(AdjMatrix[current][i] == 1){
                if(visit_table[i] == false){ 
                    myStack.push(i);
                    visit_table[i] = true;
                    cout << i << "  ";
                }
                break;
            }
            else if(!myStack.empty())
                myStack.pop();
        }
    }
}

Enterprise app deployment doesn't work on iOS 7.1

The universal solution is to connect your device to Mac and to observe what's going on during installation. I got an error:

Could not load download manifest with underlying error: Error Domain=NSURLErrorDomain Code=-1202 "Cannot connect to the Store" UserInfo=0x146635d0 {NSLocalizedDescription=Cannot connect to the Store, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSLocalizedFailureReason=A secure connection could not be established. Please check your Date & Time settings., NSErrorFailingURLStringKey=https://myserver.com/app/manifest.plist, NSUnderlyingError=0x14678880 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myserver.com” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=, NSErrorFailingURLKey=https://myserver.com/app/manifest.plist}

There was even the suggestion in that error to check date settings. For some reason the date was 1 January 1970. Setting correct date solved the problem.

Best way to find the months between two dates

Here's how to do this with Pandas FWIW:

import pandas as pd
pd.date_range("1990/04/03", "2014/12/31", freq="MS")

DatetimeIndex(['1990-05-01', '1990-06-01', '1990-07-01', '1990-08-01',
               '1990-09-01', '1990-10-01', '1990-11-01', '1990-12-01',
               '1991-01-01', '1991-02-01',
               ...
               '2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01',
               '2014-07-01', '2014-08-01', '2014-09-01', '2014-10-01',
               '2014-11-01', '2014-12-01'],
              dtype='datetime64[ns]', length=296, freq='MS')

Notice it starts with the month after the given start date.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

It can do so if you have implicitly or explicitly set the alignment of the struct. A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.

Also a library may be compiled under x86 with 32-bit ints and you may be comparing its components on a 64-bit process would would give you a different result if you were doing this by hand.

What does upstream mean in nginx?

It's used for proxying requests to other servers.

An example from http://wiki.nginx.org/LoadBalanceExample is:

http {
  upstream myproject {
    server 127.0.0.1:8000 weight=3;
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;    
    server 127.0.0.1:8003;
  }

  server {
    listen 80;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
    }
  }
}

This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.

How to convert SQL Query result to PANDAS Data Structure?

Edit 2014-09-30:

pandas now has a read_sql function. You definitely want to use that instead.

Original answer:

I can't help you with SQLAlchemy -- I always use pyodbc, MySQLdb, or psychopg2 as needed. But when doing so, a function as simple as the one below tends to suit my needs:

import decimal

import pydobc
import numpy as np
import pandas

cnn, cur = myConnectToDBfunction()
cmd = "SELECT * FROM myTable"
cur.execute(cmd)
dataframe = __processCursor(cur, dataframe=True)

def __processCursor(cur, dataframe=False, index=None):
    '''
    Processes a database cursor with data on it into either
    a structured numpy array or a pandas dataframe.

    input:
    cur - a pyodbc cursor that has just received data
    dataframe - bool. if false, a numpy record array is returned
                if true, return a pandas dataframe
    index - list of column(s) to use as index in a pandas dataframe
    '''
    datatypes = []
    colinfo = cur.description
    for col in colinfo:
        if col[1] == unicode:
            datatypes.append((col[0], 'U%d' % col[3]))
        elif col[1] == str:
            datatypes.append((col[0], 'S%d' % col[3]))
        elif col[1] in [float, decimal.Decimal]:
            datatypes.append((col[0], 'f4'))
        elif col[1] == datetime.datetime:
            datatypes.append((col[0], 'O4'))
        elif col[1] == int:
            datatypes.append((col[0], 'i4'))

    data = []
    for row in cur:
        data.append(tuple(row))

    array = np.array(data, dtype=datatypes)
    if dataframe:
        output = pandas.DataFrame.from_records(array)

        if index is not None:
            output = output.set_index(index)

    else:
        output = array

    return output

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Implement touch using Python?

Simplistic:

def touch(fname):
    open(fname, 'a').close()
    os.utime(fname, None)
  • The open ensures there is a file there
  • the utime ensures that the timestamps are updated

Theoretically, it's possible someone will delete the file after the open, causing utime to raise an exception. But arguably that's OK, since something bad did happen.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

try it out with the following code

function fun1()  
{  
   $this->db->select('count(DISTINCT(accessid))');  
   $this->db->from('accesslog');  
   $this->db->where('record =','123');  
   $query=$this->db->get();  
   return $query->num_rows();  
}

How to decode viewstate

As another person just mentioned, it's a base64 encoded string. In the past, I've used this website to decode it:

http://www.motobit.com/util/base64-decoder-encoder.asp

How to determine the version of Gradle?

Check in the folder structure of the project the files within the /gradle/wrapper/ The gradle-wrapper.jar version should be the one specified in the gradle-wrapper.properties

How to view/delete local storage in Firefox?

From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings

Once there, you can enable the Storage options under Default Firefox Developer tools

Updated 27-3-16

Firefox 48.0a1 now supports Cookies editing.

Updated 3-4-16

Firefox 48.0a1 now supports localStorage and sessionStorage editing.

Updated 02-08-16

Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB

How to autosize a textarea using Prototype?

My solution not using jQuery (because sometimes they don't have to be the same thing) is below. Though it was only tested in Internet Explorer 7, so the community can point out all the reasons this is wrong:

textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }

So far I really like how it's working, and I don't care about other browsers, so I'll probably apply it to all my textareas:

// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');

for (i = 0; i<textareas.length; i++)
{
    // Retain textarea's starting height as its minimum height
    textareas[i].minHeight = textareas[i].offsetHeight;

    textareas[i].onkeyup = function () {
        this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
    }
    textareas[i].onkeyup(); // Trigger once to set initial height
}

C# Parsing JSON array of objects

I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.

I got an JSON like this:

{"Accounts":"[{\"bank\":\"Itau\",\"account\":\"456\",\"agency\":\"0444\",\"digit\":\"5\"}]"}

And made some types like this

    public class FinancialData
{
    public string Accounts { get; set; } // this will store the JSON string
    public List<Accounts> AccountsList { get; set; } // this will be the actually list. 
}

    public class Accounts
{
    public string bank { get; set; }
    public string account { get; set; }
    public string agency { get; set; }
    public string digit { get; set; }

}

and the "magic" part

 Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
        var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;

        foreach (var account in  accounts)
        {
            if (financialData.AccountsList == null)
            {
                financialData.AccountsList = new List<Models.Accounts>();
            }

            financialData.AccountsList.Add(JsonConvert.DeserializeObject<Models.Accounts>(account.ToString()));
        }

When to use Common Table Expression (CTE)

One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.

But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)

WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
    FROM myTable 
)
SELECT * FROM CTE
WHERE RN = 1

As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.

ImportError: No module named six

In my case, six was installed for python 2.7 and for 3.7 too, and both pip install six and pip3 install six reported it as already installed, while I still had apps (particularly, the apt program itself) complaining about missing six.

The solution was to install it for python3.6 specifically:

/usr/bin/python3.6 -m pip install six

What is the difference between Class.getResource() and ClassLoader.getResource()?

Had to look it up in the specs:

Class's getResource() - documentation states the difference:

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

Applying CSS styles to all elements inside a DIV

.yourWrapperClass * {
 /* your styles for ALL */
}

This code will apply styles all elements inside .yourWrapperClass.

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.

So, I decided to upgrade all to latest versions:

npm -v : v12.13.0 
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2

This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.

  1. In version 4, you have to defined the task as a function, before call it as a gulp task by it's string name. In V3:

gulp.task('serve', ['sass'], function() {..});

But in V4 it should be like:

function serve() {
...
}
gulp.task('serve', gulp.series(sass));
  1. As @Arthur has mentioned, you need to change the way of passing arguments to the task function. It was like this in V3:

gulp.task('serve', ['sass'], function() { ... });

But in V4, it should be:

gulp.task('serve', gulp.series(sass));

Run php script as daemon process

As others have already mentioned, running PHP as a daemon is quite easy, and can be done using a single line of command. But the actual problem is keeping it running and managing it. I've had the same problem quite some time ago and although there are plenty of solutions already available, most of them have lots of dependencies or are difficult to use and not suitable for basic usages. I wrote a shell script that can manage a any process/application including PHP cli scripts. It can be set as a cronjob to start the application and will contain the application and manage it. If it's executed again, for example via the same cronjob, it check if the app is running or not, if it does then simply exits and let its previous instance continue managing the application.

I uploaded it to github, feel free to use it : https://github.com/sinasalek/EasyDeamonizer

EasyDeamonizer

Simply watches over your application (start, restart, log, monitor, etc). a generic script to make sure that your appliation remains running properly. Intentionally it uses process name instread of pid/lock file to prevent all its side effects and keep the script as simple and as stirghforward as possible, so it always works even when EasyDaemonizer itself is restarted. Features

  • Starts the application and optionally a customized delay for each start
  • Makes sure that only one instance is running
  • Monitors CPU usage and restarts the app automatically when it reaches the defined threshold
  • Setting EasyDeamonizer to run via cron to run it again if it's halted for any reason
  • Logs its activity

C++ Array Of Pointers

I would do it something along these lines:

class Foo{
...
};

int main(){
  Foo* arrayOfFoo[100]; //[1]

  arrayOfFoo[0] = new Foo; //[2]
}

[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.

[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.

JQuery - Storing ajax response into global variable

I know the thread is old but i thought someone else might find this useful. According to the jquey.com

var bodyContent = $.ajax({
  url: "script.php",
  global: false,
  type: "POST",
  data: "name=value",
  dataType: "html",
  async:false,
  success: function(msg){
     alert(msg);
  }
}).responseText;

would help to get the result to a string directly. Note the .responseText; part.

How to "grep" for a filename instead of the contents of a file?

Also for multiple files.

tree /path/to/directory/ | grep -i "file1 \| file2 \| file3"

How to enable GZIP compression in IIS 7.5

Filing this under #wow

Turns out that IIS has different levels of compression configurable from 1-9.

Some of my dynamic SOAP requests have been getting out of control recently. With the uncompressed SOAP being about 14MB and compressed 3MB.

I noticed that in Fiddler when I compressed my request under Transformer it came to about 470KB instead of the 3MB - so I figured there must be some way to get better compression.

Eventually found this very informative blog post

http://weblogs.asp.net/owscott/iis-7-compression-good-bad-how-much

I went ahead and ran this commnd (followed by iisreset):

C:\Windows\System32\Inetsrv\Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:9

Changed dynamic level up to 9 and now my compressed soap matches what Fiddler gave me - and it about 1/7th the size of the existing compressed file.

Milage will vary, but for SOAP this is a massive massive improvement.

Response.Redirect with POST instead of Get?

You can use this aproach:

Response.Clear();

StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");

Response.Write(sb.ToString());

Response.End();

As result right after client will get all html from server the event onload take place that triggers form submit and post all data to defined postbackUrl.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

how to call a method in another Activity from Activity

If you need to call the same method from both Activities why not then use a third object?

public class FirstActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

    }      

    // Utility.method() used somewhere in FirstActivity
}

public class Utility {

    public static void method()
    {

    }  

}

public class SecondActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        Utility.method();

    }
}

Of course making it static depends on the use case.

c# razor url parameter from view

@(ViewContext.RouteData.Values["parameterName"])

worked with ROUTE PARAM.

Request.Params["paramName"]

did not work with ROUTE PARAM.

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Android Studio Rendering Problems : The following classes could not be found

I faced this error when I created second activity in my project in the newly updated Android Studio,I solved it simply by copy pasting the whole xml code from first layout to the second and then I just removed the code that's unnecessary.

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

GitHub Error Message - Permission denied (publickey)

Assuming you are connecting GitHub over SSH, you can run below command to confirm this.

$git config --get remote.origin.url

If you get a result has following format [email protected]:xxx/xxx.github.com.git, then you should do the following.

Generate a SSH key(or use existing one). if you had one, you just need to add your key to the ssh-agent (step 2)and to your GitHub account(step 3).

below are for those who don't have SSH key.

Step 1 Generating public/private rsa key pair.

$ssh-keygen -t rsa -b 4096 -C "[email protected]"

You'll be asked to confirm where to save the SSH key and what passphrase you want to use.

Step 2 Add your key to the ssh-agent

  • Ensure ssh-agent is enabled

    $eval "$(ssh-agent -s)"

  • Add your SSH key to the ssh-agent:

    $ssh-add ~/.ssh/id_rsa

Step 3 Add your SSH key to your account

$sudo apt-get install xclip

$xclip -sel clip < ~/.ssh/id_rsa.pub

Then add the copied key to GitHub

Go to Settings->SSH keys(Personal settings side bar)->Add SSH key->fill out form(key is on your clipboard, just use ctrl+v)->Add key

After going through above steps, you should solve the permission problem.

Reference Link: Generating SSH keys.

Why is a primary-foreign key relation required when we can join without it?

A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

To do this you use an outer join:

select tablea.code, tablea.name, tableb.location from tablea left outer join 
tableb on tablea.code = tableb.code

join with out relation

SQL join

@import vs #import - iOS 7

History:

#include => #import => .pch => @import

[#include vs #import]
[.pch - Precompiled header]

Module - @import

Product Name == Product Module Name 

@import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

enter image description here

urllib2 and json

Example - sending some data encoded as JSON as a POST data:

import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()

Parse Json string in C#

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

One such example is the one everybody uses: JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>> with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

Note: ValueDescription being this class:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}

Cross-Origin Read Blocking (CORB)

Return response with header 'Access-Control-Allow-Origin:*' Check below code for the Php server response.

<?php header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($phparray); 

How to clear https proxy setting of NPM?

ok, "NPM config delete ..." is the right command for Windows environment, viceversa "NPM config rm ..." it is for Unix-like environment. Moreover, at least for me, it was mandatory to add the option "-g" because the command worked properly

Emulate ggplot2 default color palette

This is the result from

library(scales)
show_col(hue_pal()(4))

Four color ggplot

show_col(hue_pal()(3))

Three color ggplot

Extend a java class from one file in another java file

Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so: import foo.bar.Baz

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

In my case, which none of the answers above stated. If your device is using the miniUsb connector, make sure you are using a cable that is not charge-only. I became accustom to using developing with a newer Usb-C device and could not fathom a charge-only cable got mixed with my pack especially since there is no visible way to tell the difference.

Before you uninstall and go through a nightmare of driver reinstall and android menu options. Try a different cable first.

Check if a value is an object in JavaScript

Oh My God! I think this could be more shorter than ever, let see this:

Short and Final code

_x000D_
_x000D_
function isObject(obj)_x000D_
{_x000D_
    return obj != null && obj.constructor.name === "Object"_x000D_
}_x000D_
_x000D_
console.log(isObject({})) // returns true_x000D_
console.log(isObject([])) // returns false_x000D_
console.log(isObject(null)) // returns false
_x000D_
_x000D_
_x000D_

Explained

Return Types

typeof JavaScript objects (including null) returns "object"

_x000D_
_x000D_
console.log(typeof null, typeof [], typeof {})
_x000D_
_x000D_
_x000D_

Checking on Their constructors

Checking on their constructor property returns function with their names.

_x000D_
_x000D_
console.log(({}).constructor) // returns a function with name "Object"_x000D_
console.log(([]).constructor) // returns a function with name "Array"_x000D_
console.log((null).constructor) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_

Introducing Function.name

Function.name returns a readonly name of a function or "anonymous" for closures.

_x000D_
_x000D_
console.log(({}).constructor.name) // returns "Object"_x000D_
console.log(([]).constructor.name) // returns "Array"_x000D_
console.log((null).constructor.name) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_

Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:

@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.

So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.

Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.

The complete solution:

*:not(html) {
    -webkit-transform: translate3d(0, 0, 0);
}

Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.

So, thanks again, and hope this helps some other lost soul. This surely helped me big time!

Windows 8.1 gets Error 720 on connect VPN

This solved my 720 problem. The idea is to change the driver of the faulty WAN to another network adaptar driver, and then we are able to uninstall the WAN device and then reboot the system.

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

How to Change Font Size in drawString Java

All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

HTML form with two submit buttons and two "target" attributes

Example:

<input 
  type="submit" 
  onclick="this.form.action='new_target.php?do=alternative_submit'" 
  value="Alternative Save"
/>

Voila. Very "fancy", three word JavaScript!

Javascript validation: Block special characters

It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

var checkString = document.formname.txt.value;
if (checkString != "") {
    if ( /[^A-Za-z\d]/.test(checkString)) {
        alert("Please enter only letter and numeric characters");
        document.formname.txt.focus();
        return (false);
    }
}

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

In my case.. following steps resolved:

There was a column value which was set to "Update" - replaced it with Edit (non sql keyword) There was a space in one of the column names (removed the extra space or trim)

Java: How to check if object is null?

drawable.equals(null)

The above line calls the "equals(...)" method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

To check whether an object exists and it is not null, use the following

if(drawable == null) {
    ...
    ...
}

In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

null == null

is valid.

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

JQuery create new select option

If you need to make single element you can use this construction:

$('<option/>', {
    'class': this.dataID,
    'text': this.s_dataValue
}).appendTo('.subCategory');

But if you need to print many elements you can use this construction:

function printOptions(arr){
    jQuery.each(arr, function(){
        $('<option/>', {
            'value': this.dataID,
            'text': this.s_dataValue
        }).appendTo('.subCategory');
    });
}

Entity Framework select distinct name

DBContext.TestAddresses.Select(m => m.NAME).Distinct();

if you have multiple column do like this:

DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();

In this example no duplicate CategoryId and no CategoryName i hope this will help you

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

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

For PHP version 4 or later versions:

<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

Display last git commit comment

For something a little more readable, run this command once:

git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"

so that when you then run:

git lg

you get a nice readout. To show only the last line:

git lg -1

Solution found here

Expansion of variables inside single quotes in a command in Bash

EDIT: (As per the comments in question:)

I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

This is another valid way to make a copy of a vector, just use its constructor:

std::vector<int> newvector(oldvector);

This is even simpler than using std::copy to walk the entire vector from start to finish to std::back_insert them into the new vector.

That being said, your .swap() one is not a copy, instead it swaps the two vectors. You would modify the original to not contain anything anymore! Which is not a copy.

SQL Inner-join with 3 tables?

select empid,empname,managename,[Management ],cityname  
from employees inner join Managment  
on employees.manageid = Managment.ManageId     
inner join CITY on employees.Cityid=CITY.CityId


id name  managename  managment  cityname
----------------------------------------
1  islam   hamza       it        cairo

Parsing a comma-delimited std::string

std::string input="1,1,1,1,2,1,1,1,0";
std::vector<long> output;
for(std::string::size_type p0=0,p1=input.find(',');
        p1!=std::string::npos || p0!=std::string::npos;
        (p0=(p1==std::string::npos)?p1:++p1),p1=input.find(',',p0) )
    output.push_back( strtol(input.c_str()+p0,NULL,0) );

It would be a good idea to check for conversion errors in strtol(), of course. Maybe the code may benefit from some other error checks as well.

Regular cast vs. static_cast vs. dynamic_cast

C-style casts conflate const_cast, static_cast, and reinterpret_cast.

I wish C++ didn't have C-style casts. C++ casts stand out properly (as they should; casts are normally indicative of doing something bad) and properly distinguish between the different kinds of conversion that casts perform. They also permit similar-looking functions to be written, e.g. boost::lexical_cast, which is quite nice from a consistency perspective.

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Why am I getting Unknown error in line 1 of pom.xml?

Simply add below maven jar version in properties tag in pom.xml, <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>

Then follow below steps,

Step 1: mvn clean

Step 2 : update project

Problem solved for me! You should also try this :)

ImportError: No module named 'Tkinter'

Firstly you should test your python idle to see if you have tkinter:

import tkinter

tkinter._test()

Trying typing it, copy paste doesn't work.

So after 20 hours of trying every way that recommended on those websites figured out that you can't use "tkinter.py" or any other file name that contains "tkinter..etc.py". If you have the same problem, just change the file name.

How can I capitalize the first letter of each word in a string?

The .title() method won't work in all test cases, so using .capitalize(), .replace() and .split() together is the best choice to capitalize the first letter of each word.

eg: def caps(y):

     k=y.split()
     for i in k:
        y=y.replace(i,i.capitalize())
     return y

Generate random numbers uniformly over an entire range

If RAND_MAX is 32767, you can double the number of bits easily.

int BigRand()
{
    assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);
    return rand() * (RAND_MAX+1) + rand();
}

How to connect to remote Oracle DB with PL/SQL Developer?

In the "database" section of the logon dialog box, enter //hostname.domain:port/database, in your case //123.45.67.89:1521/TEST - this assumes that you don't want to set up a tnsnames.ora file/entry for some reason.

Also make sure the firewall settings on your server are not blocking port 1521.

How to get all selected values from <select multiple=multiple>?

Unless a question asks for JQuery the question should be first answered in standard javascript as many people do not use JQuery in their sites.

From RobG How to get all selected values of a multiple select box using JavaScript?:

  function getSelectValues(select) {
  var result = [];
  var options = select && select.options;
  var opt;

  for (var i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
}

How to convert DateTime to a number with a precision greater than days in T-SQL?

SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)

yields 39977.9590277778

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):

SELECT
    CONCAT(table_name, '.', column_name) AS 'foreign key',
    CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references',
    constraint_name AS 'constraint name'
FROM
    information_schema.key_column_usage
WHERE
    referenced_table_name IS NOT NULL;

If you want to check tables in a specific database, add the following:

AND table_schema = 'database_name';

Convert a String representation of a Dictionary to a dictionary?

string = "{'server1':'value','server2':'value'}"

#Now removing { and }
s = string.replace("{" ,"")
finalstring = s.replace("}" , "")

#Splitting the string based on , we get key value pairs
list = finalstring.split(",")

dictionary ={}
for i in list:
    #Get Key Value pairs separately to store in dictionary
    keyvalue = i.split(":")

    #Replacing the single quotes in the leading.
    m= keyvalue[0].strip('\'')
    m = m.replace("\"", "")
    dictionary[m] = keyvalue[1].strip('"\'')

print dictionary

Form content type for a json HTTP POST?

multipart/form-data

is used when you want to upload files to the server. Please check this article for details.

Copy table to a different database on a different SQL Server

If it’s only copying tables then linked servers will work fine or creating scripts but if secondary table already contains some data then I’d suggest using some third party comparison tool.

I’m using Apex Diff but there are also a lot of other tools out there such as those from Red Gate or Dev Art...

Third party tools are not necessary of course and you can do everything natively it’s just more convenient. Even if you’re on a tight budget you can use these in trial mode to get things done….

Here is a good thread on similar topic with a lot more examples on how to do this in pure sql.

Calling class staticmethod within the class body?

What about this solution? It does not rely on knowledge of @staticmethod decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.

class Klass(object):

    class StaticMethod:
        @staticmethod  # use as decorator
        def _stat_func():
            return 42

    _ANS = StaticMethod._stat_func()  # call the staticmethod

    def method(self):
        ret = self.StaticMethod._stat_func() + Klass._ANS
        return ret

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

How can I count occurrences with groupBy?

Here is the simple solution by StreamEx:

StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());

This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.

How to check if a value is not null and not empty string in JS

try it----------

_x000D_
_x000D_
function myFun(){_x000D_
var inputVal=document.getElementById("inputId").value;_x000D_
if(inputVal){_x000D_
document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';_x000D_
}_x000D_
else{_x000D_
document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";_x000D_
}_x000D_
}
_x000D_
<input type="text" id="inputId">_x000D_
<input type="button" onclick="myFun()" value="View Result">_x000D_
<h1 id="result"></h1>
_x000D_
_x000D_
_x000D_

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

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

I had an issue where I was putting in the override = "Allow" values (mentioned here already)......but on a x64 bit system.......my 32 notepad++ was phantom saving them. Switching to Notepad (which is a 64bit application on a x64 bit O/S) allowed me to save the settings.

See :

http://dpotter.net/technical/2009/11/editing-applicationhostconfig-on-64-bit-windows/

The relevant text:

One of the problems I’m running down required that I view and possibly edit applicationHost.config. This file is located at %SystemRoot%\System32\inetsrv\config. Seems simple enough. I was able to find it from the command line easily, but when I went to load it in my favorite editor (Notepad++) I got a file not found error. Turns out that the System32 folder is redirected for 32-bit applications to SysWOW64. There appears to be no way to view the System32 folder using a 32-bit app. Go figure. Fortunately, 64-bit versions of Windows ship with a 64-bit version of Notepad. As much as I dislike it, at least it works.

"Could not find a valid gem in any repository" (rubygame and others)

For what it is worth I came to this page because I had the same problem. I never got anywhere except some IMAP stuff that I don't understand. Then I remembered I had uninstalled privoxy on my ubuntu (because of some weird runtime error that mentioned 127.0.0.1:8118 when I used Daniel Kehoe's Rails template, https://github.com/RailsApps/rails3-application-templates [never discovered what it was]) and I hadn't changed my terminal to the state of no system wide proxy, under network proxy.

I know this may not be on-point but if I wound up here maybe other privoxy users can benefit too.

How to fix the session_register() deprecated issue?

To complement Felix Kling's answer, I was studying a codebase that used to have the following code:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        session_register($var);
    }
} else if (!(empty($start_vars))) {
    session_register($start_vars);
}

In order to not use session_register they made the following adjustments:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        $_SESSION[$var] =  $GLOBALS[$var];
    }
} else if (!(empty($start_vars))) {
    $_SESSION[$start_vars] =  $GLOBALS[$start_vars];
}

Dealing with HTTP content in HTTPS pages

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

Binding an enum to a WinForms combo box, and then setting it

In Framework 4 you can use the following code:

To bind MultiColumnMode enum to combobox for example:

cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());

and to get selected index:

MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;

note: I use DevExpress combobox in this example, you can do the same in Win Form Combobox

Custom fonts and XML layouts (Android)

There are two ways to customize fonts :

!!! my custom font in assets/fonts/iran_sans.ttf

Way 1 : Refrection Typeface.class ||| best way

call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts

AppController.java

public class AppController extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //Initial Font
        FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");

    }
}

FontsOverride.java

public class FontsOverride {

    public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    private static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Way 2: use setTypeface

for special view just call setTypeface() to change font.

CTextView.java

public class CTextView extends TextView {

    public CTextView(Context context) {
        super(context);
        init(context,null);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    public void init(Context context, @Nullable AttributeSet attrs) {

        if (isInEditMode())
            return;

        // use setTypeface for change font this view
        setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));

    }
}

FontUtils.java

public class FontUtils {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<>();

    public static Typeface getTypeface(String fontName) {
        Typeface tf = fontCache.get(fontName);
        if (tf == null) {
            try {
                tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }

}

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

How to resolve javax.mail.AuthenticationFailedException issue?

The problem is, you are creating a transport object and using it's connect method to authenticate yourself. But then you use a static method to send the message which ignores authentication done by the object.

So, you should either use the sendMessage(message, message.getAllRecipients()) method on the object or use an authenticator as suggested by others to get authorize through the session.

Here's the Java Mail FAQ, you need to read.

Query based on multiple where clauses in Firebase

var ref = new Firebase('https://your.firebaseio.com/');

Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
            Movie movie = dataSnapshot.getValue(Movie.class);
            if (movie.getLead().equals('Jack Nicholson')) {
                console.log(movieSnapshot.getKey());
            }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

How can I kill all sessions connecting to my oracle database?

If Oracle is running in Unix /Linux then we can grep for all client connections and kill it

grep all oracle client process:

ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}' | wc -l

Kill all oracle client process :

kill -9 ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}'

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

pip install returning invalid syntax

Try running cmd as administrator (in the menu that pops up after right-clicking) and/or entering "pip" alone and then

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

CKEditor, Image Upload (filebrowserUploadUrl)

That URL will points to your own server-side file upload action. The documentation doesn't go into much detail, but fortunately Don Jones fills in some of the blanks here:

How can you integrate a custom file browser/uploader with CKEditor?

See also:

http://zerokspot.com/weblog/2009/09/09/custom-filebrowser-callbacks-ckeditor/

How to connect to SQL Server from another computer?

Disclamer

This is just some additional information that might help anyone. I want to make it abundantly clear that what I am describing here is possibly:

  • A. not 100% correct and
  • B. not safe in terms of network security.

I am not a DBA, but every time I find myself setting up a SQL Server (Express or Full) for testing or what not I run into the connectivity issue. The solution I am describing is more for the person who is just trying to get their job done - consult someone who is knowledgeable in this field when setting up a production server.

For SQL Server 2008 R2 this is what I end up doing:

  1. Make sure everything is squared away like in this tutorial which is the same tutorial posted above as a solution by "Dani" as the selected answer to this question.
  2. Check and/or set, your firewall settings for the computer that is hosting the SQL Server. If you are using a Windows Server 2008 R2 then use the Server Manager, go to Configuration and then look at "Windows Firewall with Advanced Security". If you are using Windows 7 then go to Control Panel and search for "Firewall" click on "Allow a program through Windows Firewall".
    • Create an inbound rule for port TCP 1433 - allow the connection
    • Create an outbound rule for port TCP 1433 - allow the connection
  3. When you are finished with the firewall settings you are going to want to check one more thing. Open up the "SQL Server Configuration Manager" locate: SQL Server Network Configuration - Protocols for SQLEXPRESS (or equivalent) - TCP/IP
    • Double click on TCP/IP
    • Click on the IP Addresses tab
    • Under IP1 set the TCP Port to 1433 if it hasn't been already
    • Under IP All set the TCP Port to 1433 if it hasn't been already
  4. Restart SQL Server and SQL Browser (do both just to be on the safe side)

Usually after I do what I mentioned above I don't have a problem anymore. Here is a screenshot of what to look for - for that last step:

Port 1433 is the default port used by SQL Server but for some reason doesn't show up in the configuration by default.

Again, if someone with more information about this topic sees a red flag please correct me.

How to dynamically add rows to a table in ASP.NET?

in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site

how to set default main class in java?

In Netbeans 11(Gladle Project) follow these steps:

In the tab files>yourprojectname> double click in the file "build.gladle" than set in line "mainClassName:'yourpackagepath.YourMainClass'"

Hope this helps!

H2 in-memory database. Table not found

I came to this post because I had the same error.

In my case the database evolutions weren't been executed, so the table wasn't there at all.

My problem was that the folder structure for the evolution scripts was wrong.

from: https://www.playframework.com/documentation/2.0/Evolutions

Play tracks your database evolutions using several evolutions script. These scripts are written in plain old SQL and should be located in the conf/evolutions/{database name} directory of your application. If the evolutions apply to your default database, this path is conf/evolutions/default.

I had a folder called conf/evolutions.default created by eclipse. The issue disappeared after I corrected the folder structure to conf/evolutions/default

How can I get dictionary key as variable directly in Python (not by searching from value)?

If you want to access both the key and value, use the following:

Python 2:

for key, value in my_dict.iteritems():
    print(key, value)

Python 3:

for key, value in my_dict.items():
    print(key, value)

How to iterate object keys using *ngFor

I think the most elegant way to do that is to use the javascript Object.keys like this (I had first implemented a pipe for that but for me, it just complicated my work unnecessary):

in the Component pass Object to template:

Object = Object;

then in the template:

<div *ngFor="let key of Object.keys(objs)">
   my key: {{key}}
   my object {{objs[key] | json}} <!-- hier I could use ngFor again with Object.keys(objs[key]) -->
</div>

If you have a lot of subobjects you should create a component that will print the object for you. By printing the values and keys as you want and on an subobject calling itselfe recursively.

Hier you can find an stackblitz demo for both methods.

Return date as ddmmyyyy in SQL Server

SELECT REPLACE(CONVERT(VARCHAR(10), THEDATE, 103), '/', '') AS [DDMMYYYY]

As seen here: http://www.sql-server-helper.com/tips/date-formats.aspx

Makefile to compile multiple C programs?

A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.

When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.

Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.

The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.

Again: draw the graph!.

PHP date add 5 year to current date

Using Carbon:

$dt = Carbon::now();
echo $dt->addYears(5); 

Set initial focus in an Android application

android:focusedByDefault="true"

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}

Listing files in a specific "folder" of a AWS S3 bucket

Based on @davioooh answer. This code is worked for me.

ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName("your-bucket")
            .withPrefix("your/folder/path/").withDelimiter("/");

Installing Tomcat 7 as Service on Windows Server 2008

You can find the solution here!

Install the service named 'Tomcat7'

C:\>Tomcat\bin\service.bat install

There is a 2nd optional parameter that lets you specify the name of the service, as displayed in Windows services.

Install the service named 'MyTomcatService'

C:\>Tomcat\bin\service.bat install MyTomcatService

"insufficient memory for the Java Runtime Environment " message in eclipse

I know the question talking about eclipse but i got the similar issue many times with Intellij as well and the solution for it was easy .. Just run the 64 bit exe not the 32 one which is always the default one.

How to use custom packages

First, be sure to read and understand the "How to write Go code" document.

The actual answer depends on the nature of your "custom package".

If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate go get-table project.

If your library is for internal use, you could go like this:

  1. Place the directory with library files under the directory of your project.
  2. In the rest of your project, refer to the library using its path relative to the root of your workspace containing the project.

To demonstrate:

src/
  myproject/
    mylib/
      mylib.go
      ...
    main.go

Now, in the top-level main.go, you could import "myproject/mylib" and it would work OK.

dropdownlist set selected value in MVC3 Razor

To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.

ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");

How to pass value from <option><select> to form action

with jQuery :
html :

<form method="POST" name="myform" action="index.php?action=contact_agent&agent_id="  onsubmit="SetData()">
  <select name="agent" id="agent">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

jQuery :

$('form').submit(function(){
   $(this).attr('action',$(this).attr('action')+$('#agent').val());
   $(this).submit();
});

javascript :

function SetData(){
   var select = document.getElementById('agent');
   var agent_id = select.options[select.selectedIndex].value;
   document.myform.action = "index.php?action=contact_agent&agent_id="+agent_id ; # or .getAttribute('action')
   myform.submit();
}

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

How to switch between hide and view password

show and hide password Edit_Text with check Box

XML

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

    <EditText
        android:inputType="textPassword"
        android:id="@+id/edtPass"
        android:textSize="20dp"
        android:hint="password"
        android:padding="20dp"
        android:background="#efeaea"
        android:layout_width="match_parent"
        android:layout_margin="20dp"
        android:layout_height="wrap_content" />

    <CheckBox
        android:background="#ff4"
        android:layout_centerInParent="true"
        android:textSize="25dp"
        android:text="show password"
        android:layout_below="@id/edtPass"
        android:id="@+id/showPassword"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:gravity="top|right"
        android:layout_height="wrap_content" />

</RelativeLayout>

java code

package com.example.root.sql2;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class password extends AppCompatActivity {


    EditText password;
    CheckBox show_hide_password;

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



    }//end onCreate



    public void show_hide_pass(){
        show_hide_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!b){
                    // hide password
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());

                }else{
                    // show password
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });
    } // end show_hide_pass




    public void findViewById(){ //  find ids ui and
        password = (EditText) findViewById(R.id.edtPass);
        show_hide_password = (CheckBox) findViewById(R.id.showPassword);
    }//end findViewById



}// end class

Why is setState in reactjs Async instead of Sync?

setState is asynchronous. You can see in this documentation by Reactjs

React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.

However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.

The reason is this would break the consistency between props and state, causing issues that are very hard to debug.

You can still perform functions if it is dependent on the change of the state value:

Option 1: Using callback function with setState

this.setState({
   value: newValue
},()=>{
   // It is an callback function.
   // Here you can access the update value
   console.log(this.state.value)
})

Option 2: using componentDidUpdate This function will be called whenever the state of that particular class changes.

componentDidUpdate(prevProps, prevState){
    //Here you can check if value of your desired variable is same or not.
    if(this.state.value !== prevState.value){
        // this part will execute if your desired variable updates
    }
}

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

Add hover text without javascript like we hover on a user's reputation

This can also be done in CSS, for more customisability:

_x000D_
_x000D_
.hoverable {
  position: relative;
}

.hoverable>.hoverable__tooltip {
  display: none;
}

.hoverable:hover>.hoverable__tooltip {
  display: inline;
  position: absolute;
  top: 1em;
  left: 1em;
  background: #888;
  border: 1px solid black;
}
_x000D_
<div class="hoverable">
  <span class="hoverable__main">Main text</span>
  <span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
_x000D_
_x000D_

(Obviously, styling can be improved)

jQuery if statement, syntax

If you're using Jquery to manipulate the DOM, then I have found the following a good way to include logic in a Jquery statement:

$(selector).addClass(A && B?'classIfTrue':'');

Determine distance from the top of a div to top of window with javascript

This can be achieved purely with JavaScript.

I see the answer I wanted to write has been answered by lynx in comments to the question.

But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.

So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:

// Fetch the element
var el = document.getElementById("someElement");  

use getBoundingClientRect()

// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top; 

Thats it!

Hope this helps someone :)

Calling a phone number in swift

Swift 3.0 solution:

let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)

How to delete an SMS from the inbox in Android programmatically?

You just try the following code.It will delete all the sms that are all in phone (Received or Sent)

Uri uri = Uri.parse("content://sms");

ContentResolver contentResolver = getContentResolver();

Cursor cursor = contentResolver.query(uri, null, null, null,
  null);



while (cursor.moveToNext()) {

 long thread_id = cursor.getLong(1);
 Uri thread = Uri.parse("content://sms/conversations/"
   + thread_id);
 getContentResolver().delete(thread, null, null);
}

if...else within JSP or JSTL

If you just want to output different text, a more concise example would be

${condition ? "some text when true" : "some text when false"}

It is way shorter than c:choose.

Save and load MemoryStream to/from a file

I use a Panel Control to add a image or even stream video, but you can save the image on SQL Server as Image or MySQL as largeblob. This code works for me a lot. Check it out.

Here you save the image

MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, panel1.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // here you can change the Image format
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
ms.Close();

And here you can load, but I used a PictureBox Control.

MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);

Hope helps.

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

How to change the integrated terminal in visual studio code or VSCode

I know is late but you can quickly accomplish that by just typing Ctrl + Shift + p and then type default, it will show an option that says

Terminal: Select Default Shell

, it will then display all the terminals available to you.

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How to detect when a UIScrollView has finished scrolling

For all scrolls related to dragging interactions, this will be sufficient:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _isScrolling = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        _isScrolling = NO;
    }
}

Now, if your scroll is due to a programmatic setContentOffset/scrollRectVisible (with animated = YES or you obviously know when scroll is ended):

 - (void)scrollViewDidEndScrollingAnimation {
     _isScrolling = NO;
}

If your scroll is due to something else (like keyboard opening or keyboard closing), it seems like you'll have to detect the event with a hack because scrollViewDidEndScrollingAnimation is not useful either.

The case of a PAGINATED scroll view:

Because, I guess, Apple apply an acceleration curve, scrollViewDidEndDecelerating get called for every drag so there's no need to use scrollViewDidEndDragging in this case.

MongoDB not equal to

Use $ne instead of $not

http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne

db.collections.find({"name": {$ne: ""}});

How to host a Node.Js application in shared hosting

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the demo of a node app on PHP shared hosting.

EDIT: I started a Node.php project on GitHub.

How to get build time stamp from Jenkins build variables?

If you want add a timestamp to every request from browser to jenkins server. You can refer to the jenkins crumb issuer mechanism, and you can hack the /scripts/hudson-behavior.js add modify here. so it will transform a timestamp to server.

    /**
     * Puts a hidden input field to the form so that the form submission will have the crumb value
     */
    appendToForm : function(form) {
        // add here. ..... you code
        if(this.fieldName==null)    return; // noop
        var div = document.createElement("div");
        div.innerHTML = "<input type=hidden name='"+this.fieldName+"' value='"+this.value+"'>";
        form.appendChild(div);
    }

IIS error, Unable to start debugging on the webserver

Just ran into this problem myself and it turned out to be that my site in IIS was set up to use anonymous authentication with a specific network account. I had been forced to reset the password on that account, and so IIS was failing because it was using the old one. Once I updated the site with the new password (or even better, changed it to use Network Service instead), all worked again.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Just run the certified-update executable and this command will make sure that all your certificates are up-to-date.

This worked for my Ruby on Rails application in Windows.

Generate random int value from 3 to 6

DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);

Step by step

DECLARE @min INT = 3;
DECLARE @max INT = 6;

DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk; 
SELECT @result;

Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.

CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT        RAND() AS seed

and then create the random function

CREATE FUNCTION udf_RandomNumberBetween
(
    @min INT,
    @max INT
)
RETURNS INT
AS
BEGIN
    RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END

Getting the minimum of two values in SQL

Here is a trick if you want to calculate maximum(field, 0):

SELECT (ABS(field) + field)/2 FROM Table

returns 0 if field is negative, else, return field.

Does swift have a trim method on String?

Truncate String to Specific Length

If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class

extension String {

   func trunc(_ length: Int) -> String {
    if self.characters.count > length {
        return self.substring(to: self.characters.index(self.startIndex, offsetBy: length))
    } else {
        return self
    }
  }

  func trim() -> String{
     return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
   }

}

Use

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
//str is length 74
print(str)
//O/P:  Lorem Ipsum is simply dummy text of the printing and typesetting industry.

str = str.trunc(40)
print(str)
//O/P: Lorem Ipsum is simply dummy text of the 

How do I paste multi-line bash codes into terminal and run it all at once?

Add parenthesis around the lines. Example:

$ (
sudo apt-get update
dokku apps
dokku ps:stop APP # repeat to shut down each running app
sudo apt-get install -qq -y dokku herokuish sshcommand plugn
dokku ps:rebuildall # rebuilds all applications
)

List Git aliases

for windows:

git config --list | findstr "alias"

Entity framework self referencing loop detected

Well the correct answer for the default Json formater based on Json.net is to set ReferenceLoopHandling to Ignore.

Just add this to the Application_Start in Global.asax:

HttpConfiguration config = GlobalConfiguration.Configuration;

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

This is the correct way. It will ignore the reference pointing back to the object.

Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.

Using the JsonIgnore attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.

Removing all empty elements from a hash / YAML?

You can use Hash#reject to remove empty key/value pairs from a ruby Hash.

# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |key,value| value.empty? } 
#=> {:a=>"first", :c=>"third"}

# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? } 
# => {:a=>"first", :c=>"third"}

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } 
# => {:c=>"third"}

c# - approach for saving user settings in a WPF application?

Apart from a database, you can also have following options to save user related settings

  1. registry under HKEY_CURRENT_USER

  2. in a file in AppData folder

  3. using Settings file in WPF and by setting its scope as User

How to easily duplicate a Windows Form in Visual Studio?

  1. Copy and paste the form.
  2. Rename the pasted form .cs to match the new form class name. This should auto rename other related files.
  3. Open up .cs file. Change the class name and the name of the constructor(s) and destructor.
  4. Open up .Designer.cs file and change the class name.

Extra Credit:

  1. Consider abstracting common functionality from the form into common form or controls.