Programs & Examples On #Ion

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

How to click an element in Selenium WebDriver using JavaScript

const {Builder, By, Key, util} = require('selenium-webdriver')

// FUNÇÃO PARA PAUSA
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function example() {

    // chrome
    let driver = await new Builder().forBrowser("firefox").build()
    await driver.get('https://www.google.com.br')
    // await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)

    await sleep(2000)

    await driver.findElement(By.name('q')).sendKeys('Selenium')

    await sleep(2000)

    // CLICAR
    driver.findElement(By.name('btnK')).click()


}
example()

Com essas últimas linhas, você pode clicar !

Set focus to field in dynamically loaded DIV

$("#header").attr('tabindex', -1).focus();

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

Regex: match everything but specific pattern

You can put a ^ in the beginning of a character set to match anything but those characters.

[^=]*

will match everything but =

How to get memory available or used in C#

System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.

If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

Here's what the JDK API says about AbstractMethodError:

Thrown when an application tries to call an abstract method. Normally, this error is caught by the compiler; this error can only occur at run time if the definition of some class has incompatibly changed since the currently executing method was last compiled.

Bug in the oracle driver, maybe?

What in layman's terms is a Recursive Function using PHP

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

Although I cannot compete with the directory example, I hope this helps somewhat.

(4/20/10) Update:

It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,

How to output a comma delimited list in jinja python template?

And using the joiner from http://jinja.pocoo.org/docs/dev/templates/#joiner

{% set comma = joiner(",") %}
{% for user in userlist %}
    {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}  

It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

A more complex example on why you would use it.

{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
    Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
    Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
    <a href="?action=edit">Edit</a>
{% endif %}

How can I get session id in php and show it?

Before getting a session id you need to start a session and that is done by using: session_start() function.

Now that you have started a session you can get a session id by using: session_id().

/* A small piece of code for setting, displaying and destroying session in PHP */

<?php
session_start();
$r=session_id();

/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */

/* now registering a session for an authenticated user */
$_SESSION['username']=$username;

/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];


/* now destroying the session id */

if(isset($_SESSION['username']))
{
    $_SESSION=array();
    unset($_SESSION);
    session_destroy();
    echo "session destroyed...";
}
?>

ReactJS - Does render get called any time "setState" is called?

Another reason for "lost update" can be the next:

  • If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
  • so if that state value comes from props at the beginning it is overwrite in every update.

If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this

static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
   return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}

Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)

Encode String to UTF-8

You can try this way.

byte ptext[] = myString.getBytes("ISO-8859-1"); 
String value = new String(ptext, "UTF-8"); 

How do you run a Python script as a service in Windows?

This answer is plagiarizer from several sources on StackOverflow - most of them above, but I've forgotten the others - sorry. It's simple and scripts run "as is". For releases you test you script, then copy it to the server and Stop/Start the associated service. And it should work for all scripting languages (Python, Perl, node.js), plus batch scripts such as GitBash, PowerShell, even old DOS bat scripts. pyGlue is the glue that sits between Windows Services and your script.

'''
A script to create a Windows Service, which, when started, will run an executable with the specified parameters.
Optionally, you can also specify a startup directory

To use this script you MUST define (in class Service)
1. A name for your service (short - preferably no spaces)
2. A display name for your service (the name visibile in Windows Services)
3. A description for your service (long details visible when you inspect the service in Windows Services)
4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe
5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)
6. The startup directory (or specify None)
7. Any parameters for your script (or for your executable if you have no script)

NOTE: This does not make a portable script.
The associated '_svc_name.exe' in the dist folder will only work if the executable,
(and any optional startup directory) actually exist in those locations on the target system

Usage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
Options for 'install' and 'update' commands only:
        --username domain\\username : The Username the service is to run under
        --password password : The password for the username
        --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
        --interactive : Allow the service to interact with the desktop.
        --perfmonini file: .ini file to use for registering performance monitor data
        --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll
Options for 'start' and 'stop' commands only:
        --wait seconds: Wait for the service to actually start or stop.
                If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,
                each waiting the specified period.
'''

# Import all the modules that make life easy
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
import win32evtlogutil
import os
from logging import Formatter, Handler
import logging
import subprocess


# Define the win32api class
class Service (win32serviceutil.ServiceFramework):
        # The following variable are edited by the build.sh script
        _svc_name_ = "TestService"
        _svc_display_name_ = "Test Service"
        _svc_description_ = "Test Running Python Scripts as a Service"
        service_exe = 'c:/Python27/python.exe'
        service_script = None
        service_params = []
        service_startDir = None

        # Initialize the service
        def __init__(self, args):
                win32serviceutil.ServiceFramework.__init__(self, args)
                self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
                self.configure_logging()
                socket.setdefaulttimeout(60)

        # Configure logging to the WINDOWS Event logs
        def configure_logging(self):
                self.formatter = Formatter('%(message)s')
                self.handler = logHandler()
                self.handler.setFormatter(self.formatter)
                self.logger = logging.getLogger()
                self.logger.addHandler(self.handler)
                self.logger.setLevel(logging.INFO)

        # Stop the service
        def SvcStop(self):
                self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
                win32event.SetEvent(self.hWaitStop)

        # Run the service
        def SvcDoRun(self):
                self.main()

        # This is the service
        def main(self):

                # Log that we are starting
                servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
                                                          (self._svc_name_, ''))

                # Fire off the real process that does the real work
                logging.info('%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)
                self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)
                logging.info('%s - started process %d', self._svc_name_, self.process.pid)

                # Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds
                rc = None
                while rc != win32event.WAIT_OBJECT_0:
                        rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))

                # Shut down the real process and exit
                logging.info('%s - is terminating process %d', self._svc_name_, self.process.pid)
                self.process.terminate()
                logging.info('%s - is exiting', self._svc_name_)


class logHandler(Handler):
        '''
Emit a log record to the WINDOWS Event log
        '''

        def emit(self, record):
                servicemanager.LogInfoMsg(record.getMessage())


# The main code
if __name__ == '__main__':
        '''
Create a Windows Service, which, when started, will run an executable with the specified parameters.
        '''

        # Check that configuration contains valid values just in case this service has accidentally
        # been moved to a server where things are in different places
        if not os.path.isfile(Service.service_exe):
                print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)
                sys.exit(0)
        if not os.access(Service.service_exe, os.X_OK):
                print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)
                sys.exit(0)
        # Check that any optional startup directory exists
        if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):
                print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)
                sys.exit(0)

        if len(sys.argv) == 1:
                servicemanager.Initialize()
                servicemanager.PrepareToHostSingle(Service)
                servicemanager.StartServiceCtrlDispatcher()
        else:
                # install/update/remove/start/stop/restart or debug the service
                # One of those command line options must be specified
                win32serviceutil.HandleCommandLine(Service)

Now there's a bit of editing and you don't want all your services called 'pyGlue'. So there's a script (build.sh) to plug in the bits and create a customized 'pyGlue' and create an '.exe'. It is this '.exe' which gets installed as a Windows Service. Once installed you can set it to run automatically.

#!/bin/sh
# This script build a Windows Service that will install/start/stop/remove a service that runs a script
# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc

if [ $# -lt 6 ]; then
        echo "Usage: build.sh Name Display Description Executable Script StartupDir [Params]..."
        exit 0
fi

name=$1
display=$2
desc=$3
exe=$4
script=$5
startDir=$6
shift; shift; shift; shift; shift; shift
params=
while [ $# -gt 0 ]; do
        if [ "${params}" != "" ]; then
                params="${params}, "
        fi
        params="${params}'$1'"
        shift
done

cat pyGlue.py | sed -e "s/pyGlue/${name}/g" | \
        sed -e "/_svc_name_ =/s?=.*?= '${name}'?" | \
        sed -e "/_svc_display_name_ =/s?=.*?= '${display}'?" | \
        sed -e "/_svc_description_ =/s?=.*?= '${desc}'?" | \
        sed -e "/service_exe =/s?=.*?= '$exe'?" | \
        sed -e "/service_script =/s?=.*?= '$script'?" | \
        sed -e "/service_params =/s?=.*?= [${params}]?" | \
        sed -e "/service_startDir =/s?=.*?= '${startDir}'?" > ${name}.py

cxfreeze ${name}.py --include-modules=win32timezone

Installation - copy the '.exe' the server and the script to the specified folder. Run the '.exe', as Administrator, with the 'install' option. Open Windows Services, as Adminstrator, and start you service. For upgrade, just copy the new version of the script and Stop/Start the service.

Now every server is different - different installations of Python, different folder structures. I maintain a folder for every server, with a copy of pyGlue.py and build.sh. And I create a 'serverBuild.sh' script for rebuilding all the service on that server.

# A script to build all the script based Services on this PC
sh build.sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe autocode.py C:/Users/russell/Documents/autocoding -S -T

How do you Make A Repeat-Until Loop in C++?

You could use macros to simulate the repeat-until syntax.

#define repeat do
#define until(exp) while(!(exp))

DNS caching in linux

Firefox contains a dns cache. To disable the DNS cache:

  1. Open your browser
  2. Type in about:config in the address bar
  3. Right click on the list of Properties and select New > Integer in the Context menu
  4. Enter 'network.dnsCacheExpiration' as the preference name and 0 as the integer value

When disabled, Firefox will use the DNS cache provided by the OS.

WebView link click open default browser

you can use Intent for this:

Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

How to check that an element is in a std::set?

Just to clarify, the reason why there is no member like contains() in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end() internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find(), which is inefficient. It's better to use find directly, so you can cache your result, like so:

auto it = myContainer.find(key);
if (it != myContainer.end())
{
    // Do something with it, no more lookup needed.
}
else
{
    // Key was not present.
}

Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The PHP function echo() prints out its input to the web server response.

echo("Hello World!");

prints out Hello World! to the web server response.

echo("<prev>");

prints out the tag to the web server response.

echo do not require valid HTML tags. You can use PHP to print XML, images, excel, HTML and so on.

<prev> is not a HTML tag. Is is a valid XML tag, but since I don't know what page you are working in, i cannot tell you what it is. Maybe it is the root tag of a XML page, or a miswritten <pre> tag.

How to get the current date and time of your timezone in Java?

With the java.time classes built into Java 8 and later:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }

Android Studio : unmappable character for encoding UTF-8

1/ Convert the file encoding
File -> Settings -> Editor -> File encodings -> set UTF-8 for

  • IDE Encoding
  • Project Encoding
  • Default encoding propertie file

Press OK

2/ Rebuild Project

Build -> Rebuild project

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

delete espresso dependencies in gradle file works for me.

delete those lines in app gradle file:

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

Replacing few values in a pandas dataframe column with another value

Replace

DataFrame object has powerful and flexible replace method:

DataFrame.replace(
        to_replace=None,
        value=None,
        inplace=False,
        limit=None,
        regex=False, 
        method='pad',
        axis=None)

Note, if you need to make changes in place, use inplace boolean argument for replace method:

Inplace

inplace: boolean, default False If True, in place. Note: this will modify any other views on this object (e.g. a column form a DataFrame). Returns the caller if this is True.

Snippet

df['BrandName'].replace(
    to_replace=['ABC', 'AB'],
    value='A',
    inplace=True
)

How can I make one python file run another?

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

How can I insert new line/carriage returns into an element.textContent?

nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like

[script]alert(1);[/script]

(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
            domElement.appendChild(document.createTextNode(lines[i]));
            domElement.appendChild(document.createElement('br'));
        }
    }
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];
            domElement.appendChild(lineElement);
        }
    }
}

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

Get contentEditable caret index position

_x000D_
_x000D_
$("#editable").on('keydown keyup mousedown mouseup',function(e){_x000D_
     _x000D_
       if($(window.getSelection().anchorNode).is($(this))){_x000D_
       $('#position').html('0')_x000D_
       }else{_x000D_
         $('#position').html(window.getSelection().anchorOffset);_x000D_
       }_x000D_
 });
_x000D_
body{_x000D_
  padding:40px;_x000D_
}_x000D_
#editable{_x000D_
  height:50px;_x000D_
  width:400px;_x000D_
  border:1px solid #000;_x000D_
}_x000D_
#editable p{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<div contenteditable="true" id="editable">move the cursor to see position</div>_x000D_
<div>_x000D_
position : <span id="position"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create timer events using C++ 11?

This is the code I have so far:

I am using VC++ 2012 (no variadic templates)

//header
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
#include <memory>
#include <algorithm>

template<class T>
class TimerThread
{
  typedef std::chrono::high_resolution_clock clock_t;

  struct TimerInfo
  {
    clock_t::time_point m_TimePoint;
    T m_User;

    template <class TArg1>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1))
    {
    }

    template <class TArg1, class TArg2>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1, TArg2 && arg2)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2))
    {
    }
  };

  std::unique_ptr<std::thread> m_Thread;
  std::vector<TimerInfo>       m_Timers;
  std::mutex                   m_Mutex;
  std::condition_variable      m_Condition;
  bool                         m_Sort;
  bool                         m_Stop;

  void TimerLoop()
  {
    for (;;)
    {
      std::unique_lock<std::mutex>  lock(m_Mutex);

      while (!m_Stop && m_Timers.empty())
      {
        m_Condition.wait(lock);
      }

      if (m_Stop)
      {
        return;
      }

      if (m_Sort)
      {
        //Sort could be done at insert
        //but probabily this thread has time to do
        std::sort(m_Timers.begin(),
                  m_Timers.end(),
                  [](const TimerInfo & ti1, const TimerInfo & ti2)
        {
          return ti1.m_TimePoint > ti2.m_TimePoint;
        });
        m_Sort = false;
      }

      auto now = clock_t::now();
      auto expire = m_Timers.back().m_TimePoint;

      if (expire > now) //can I take a nap?
      {
        auto napTime = expire - now;
        m_Condition.wait_for(lock, napTime);

        //check again
        auto expire = m_Timers.back().m_TimePoint;
        auto now = clock_t::now();

        if (expire <= now)
        {
          TimerCall(m_Timers.back().m_User);
          m_Timers.pop_back();
        }
      }
      else
      {
        TimerCall(m_Timers.back().m_User);
        m_Timers.pop_back();
      }
    }
  }

  template<class T, class TArg1>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1);

  template<class T, class TArg1, class TArg2>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2);

public:
  TimerThread() : m_Stop(false), m_Sort(false)
  {
    m_Thread.reset(new std::thread(std::bind(&TimerThread::TimerLoop, this)));
  }

  ~TimerThread()
  {
    m_Stop = true;
    m_Condition.notify_all();
    m_Thread->join();
  }
};

template<class T, class TArg1>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

template<class T, class TArg1, class TArg2>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1),
                                      std::forward<TArg2>(arg2)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

//sample
#include <iostream>
#include <string>

void TimerCall(int i)
{
  std::cout << i << std::endl;
}

int main()
{
  std::cout << "start" << std::endl;
  TimerThread<int> timers;

  CreateTimer(timers, 2000, 1);
  CreateTimer(timers, 5000, 2);
  CreateTimer(timers, 100, 3);

  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "end" << std::endl;
}

How can I run a html file from terminal?

You could always use the Lynx terminal-based web browser, which can be got by running $ sudo apt-get install lynx.

With Lynx, I believe the file can then be viewed using lynx <filename>

C char array initialization

The relevant part of C11 standard draft n1570 6.7.9 initialization says:

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

Changing the color of an hr element

hr {
  height:0; 
  border:0; 
  border-top:1px solid #083972; 
}

This will keep the Horizontal Rule 1px thick while also changing the color of it

Build Android Studio app via command line

You're likely here because you want to install it too!

Build

gradlew

(On Windows gradlew.bat)

Then Install

adb install -r exampleApp.apk

(The -r makes it replace the existing copy, add an -s if installing on an emulator)

Bonus

I set up an alias in my ~/.bash_profile, to make it a 2char command.

alias bi="gradlew && adb install -r exampleApp.apk"

(Short for Build and Install)

How can I take a screenshot with Selenium WebDriver?

Java (Robot Framework)

I used this method for taking a screenshot.

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000)
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

You may use this method wherever required.

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Does Java support default parameter values?

This is how I did it ... it's not as convenient perhaps as having an 'optional argument' against your defined parameter, but it gets the job done:

public void postUserMessage(String s,boolean wipeClean)
{
    if(wipeClean)
    {
        userInformation.setText(s + "\n");
    }
    else
    {
        postUserMessage(s);
    }
}

public void postUserMessage(String s)
{
    userInformation.appendText(s + "\n");
}

Notice I can invoke the same method name with either just a string or I can invoke it with a string and a boolean value. In this case, setting wipeClean to true will replace all of the text in my TextArea with the provided string. Setting wipeClean to false or leaving it out all together simply appends the provided text to the TextArea.

Also notice I am not repeating code in the two methods, I am merely adding the functionality of being able to reset the TextArea by creating a new method with the same name only with the added boolean.

I actually think this is a little cleaner than if Java provided an 'optional argument' for our parameters since we would need to then code for default values etc. In this example, I don't need to worry about any of that. Yes, I have added yet another method to my class, but it's easier to read in the long run in my humble opinion.

Export P7b file with all the certificate chain into CER file

I had similar problem extracting certificates from a file. This might not be the most best way to do it but it worked for me.

openssl pkcs7 -inform DER -print_certs -in <path of the file> | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'

Find index of last occurrence of a sub-string using T-SQL

If you are using Sqlserver 2005 or above, using REVERSE function many times is detrimental to performance, below code is more efficient.

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

-- Shows text before last slash
SELECT LEFT(@FilePath, LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath))) AS Before
-- Shows text after last slash
SELECT RIGHT(@FilePath, CHARINDEX(@FindChar,REVERSE(@FilePath))-1) AS After
-- Shows the position of the last slash
SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

How would you make two <div>s overlap?

I might approach it like so (CSS and HTML):

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
  position: absolute; /* Reposition logo from the natural layout */_x000D_
  left: 75px;_x000D_
  top: 0px;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  z-index: 2;_x000D_
}_x000D_
#content {_x000D_
  margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
  height: 75px;_x000D_
  margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
  <img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
  _x000D_
  <div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hour from DateTime? in 24 hours format

date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM

Refer this link for other Formatters in DateTime.

"Uncaught Error: [$injector:unpr]" with angular after deployment

This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html',
        controller: function ($scope) {
            $scope.selectThisOption = function () {
                // some code
            };
        }
    };
});

When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html'
        controller: ['$scope', function ($scope) { //<-- difference
            $scope.selectThisOption = function () {
                // some code
            };
        }]
    };
});

Why std::cout instead of simply cout?

If you are working in ROOT, you do not even have to write #include<iostream> and using namespace std; simply start from int filename().

This will solve the issue.

How to pass an array into a SQL Server stored procedure

Use a table-valued parameter for your stored procedure.

When you pass it in from C# you'll add the parameter with the data type of SqlDb.Structured.

See here: http://msdn.microsoft.com/en-us/library/bb675163.aspx

Example:

// Assumes connection is an open SqlConnection object.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories =
  CategoriesDataTable.GetChanges(DataRowState.Added);

// Configure the SqlCommand and SqlParameter.
SqlCommand insertCommand = new SqlCommand(
    "usp_InsertCategories", connection);
insertCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
    "@tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;

// Execute the command.
insertCommand.ExecuteNonQuery();
}

How to check if ping responded or not in a batch file

I've seen three results to a ping - The one we "want" where the IP replies, "Host Unreachable" and "timed out" (not sure of exact wording).

The first two return ERRORLEVEL of 0.

Timeout returns ERRORLEVEL of 1.

Are the other results and error levels that might be returned? (Besides using an invalid switch which returns the allowable switches and an errorlevel of 1.)

Apparently Host Unreachable can use one of the previously posted methods (although it's hard to figure out when someone replies which case they're writing code for) but does the timeout get returned in a similar manner that it can be parsed?

In general, how does one know what part of the results of the ping can be parsed? (Ie, why might Sent and/or Received and/or TTL be parseable, but not host unreachable?

Oh, and iSid, maybe there aren't many upvotes because the people that read this don't have enough points. So they get their question answered (or not) and leave.

I wasn't posting the above as an answer. It should have been a comment but I didn't see that choice.

Use grep to report back only line numbers

using only grep:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

LINQ select in C# dictionary

If you are searching by the fieldname1 value, try this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .Where(d => d.ContainsKey("fieldname1"))
   .Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

If you are looking by the type of the value in the subDictionary (Dictionary<string, object> explicitly), you may do this:

var r = exitDictionary
   .Select(i => i.Value).Cast<Dictionary<string, object>>()
   .SelectMany(d=>d.Values)
   .OfType<List<Dictionary<string, string>>>()
   .SelectMany(d1 => 
       d1
        .Where(d => d.ContainsKey("valueTitle"))
        .Select(d => d["valueTitle"])
        .Where(v => v != null)).ToList();

Both alternatives will return:

title1
title2
title3
title1
title2
title3

How to update an object in a List<> in C#

You can do somthing like :

if (product != null) {
    var products = Repository.Products;
    var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
    Repository.Products[indexOf] = product;
    // or 
    Repository.Products[indexOf].prop = product.prop;
}

Iterate through 2 dimensional array

Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.

  int longestRow = 0;
  for (int i = 0; i < array.length; i++) {
    if (array[i].length > longestRow) {
      longestRow = array[i].length;
    }
  }

  for (int j = 0; j < longestRow; j++) {
    for (int i = 0; i < array.length; i++) {
      if(array[i].length > j) {
        System.out.println(array[i][j]);
      }
    }
  }

How do you connect to multiple MySQL databases on a single webpage?

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

What difference does .AsNoTracking() make?

If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking(), otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:

http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/

SQL Server - inner join when updating

This should do it:

UPDATE ProductReviews
SET    ProductReviews.status = '0'
FROM   ProductReviews
       INNER JOIN products
         ON ProductReviews.pid = products.id
WHERE  ProductReviews.id = '17190'
       AND products.shopkeeper = '89137'

Textarea Auto height

Jsfiddle

textarea#note {
    width:100%;
    direction:rtl;
    display:block;
    max-width:100%;
    line-height:1.5;
    padding:15px 15px 30px;
    border-radius:3px;
    border:1px solid #F7E98D;
    font:13px Tahoma, cursive;
    transition:box-shadow 0.5s ease;
    box-shadow:0 4px 6px rgba(0,0,0,0.1);
    font-smoothing:subpixel-antialiased;
    background:-o-linear-gradient(#F9EFAF, #F7E98D);
    background:-ms-linear-gradient(#F9EFAF, #F7E98D);
    background:-moz-linear-gradient(#F9EFAF, #F7E98D);
    background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
    background:linear-gradient(#F9EFAF, #F7E98D);
    height:100%;
}
html{
    height:100%;
}
body{

   height:100%;    
}

or javascript

var s_height = document.getElementById('note').scrollHeight;
document.getElementById('note').setAttribute('style','height:'+s_height+'px');

Jsfiddle

How to simulate a click by using x,y coordinates in JavaScript?

You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.

All modern browsers support document.elementFromPoint and HTMLElement.prototype.click(), since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:

document.elementFromPoint(x, y).click();

https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

Editable 'Select' element

Another sort of workaround might be...

Use the HTML:

<input type="text" id="myselect"/>
<datalist id="myselect">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
</datalist>

In Firefox at least a focus followed by a click drops down the list of known valid values as the <datalist> elements IFF the field happens to be empty. Otherwise, one must clear the field to see valid choices as one types in data. A new value is accepted as typed. One must handle new values in JS or other to persist them.

This is not perfect, but it suffices for my minimalist needs, so I thought I would share.

How to activate an Anaconda environment

Below is how it worked for me

  1. C:\Windows\system32>set CONDA_ENVS_PATH=d:\your\location
  2. C:\Windows\system32>conda info

Shows new environment path

  1. C:\Windows\system32>conda create -n YourNewEnvironment --clone=root

Clones default root environment

  1. C:\Windows\system32>activate YourNewEnvironment

Deactivating environment "d:\YourDefaultAnaconda3"... Activating environment "d:\your\location\YourNewEnvironment"...

  1. [YourNewEnvironment] C:\Windows\system32>conda info -e

conda environments: #

YourNewEnvironment
* d:\your\location\YourNewEnvironment

root d:\YourDefaultAnaconda3

Using GSON to parse a JSON array

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
    "number": "...",
    "title": ".." ,  //<- see that comma?
}

If you remove them your data will become

[
    {
        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"
    }
]

and

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

should work fine.

Merge or combine by rownames

Use match to return your desired vector, then cbind it to your matrix

cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])

             [,1]         [,2]         [,3]         [,4]   
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674" NA     
LEVEL        "8"          "6"          "7"          NA     
Annotated    "342"        "343"        "350"        NA     
Significant  "1"          "1"          "1"          NA     
Expected     "0.07"       "0.07"       "0.07"       NA     
resultFisher "0.679"      "0.065"      "0.065"      NA     
ILMN_1652464 "0"          "0"          "1"          "PLAC8"
ILMN_1651838 "0"          "0"          "0"          "RND1" 
ILMN_1711311 "1"          "1"          "0"          NA     
ILMN_1653026 "0"          "0"          "0"          "GRA"  

PS. Be warned that t is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.

The transaction log for the database is full

My problem solved with multiple execute of limited deletes like

Before

DELETE FROM TableName WHERE Condition

After

DELETE TOP(1000) FROM TableName WHERECondition

Lumen: get URL parameter in a Blade view

Laravel 5.8

{{ request()->a }}

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

you should do it like this

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( +)", " ");

put + inside round brackets.

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

Animate text change in UILabel

There is one more solution to achieve this. It was described here. The idea is subclassing UILabel and overriding action(for:forKey:) function in the following way:

class LabelWithAnimatedText: UILabel {
    override var text: String? {
        didSet {
            self.layer.setValue(self.text, forKey: "text")
        }
    }

    override func action(for layer: CALayer, forKey event: String) -> CAAction? {
        if event == "text" {
            if let action = self.action(for: layer, forKey: "backgroundColor") as? CAAnimation {
                let transition = CATransition()
                transition.type = kCATransitionFade

                //CAMediatiming attributes
                transition.beginTime = action.beginTime
                transition.duration = action.duration
                transition.speed = action.speed
                transition.timeOffset = action.timeOffset
                transition.repeatCount = action.repeatCount
                transition.repeatDuration = action.repeatDuration
                transition.autoreverses = action.autoreverses
                transition.fillMode = action.fillMode

                //CAAnimation attributes
                transition.timingFunction = action.timingFunction
                transition.delegate = action.delegate

                return transition
            }
        }
        return super.action(for: layer, forKey: event)
    }
}

Usage examples:

// do not forget to set the "Custom Class" IB-property to "LabelWithAnimatedText"
// @IBOutlet weak var myLabel: LabelWithAnimatedText!
// ...

UIView.animate(withDuration: 0.5) {
    myLabel.text = "I am animated!"
}
myLabel.text = "I am not animated!"

Counting number of lines, words, and characters in a text file

I agree with @Cthulhu answer. In your code you can reset your Scanner object (in).

in.reset();

This will reset your in object at the first line of your file.

How do I call a SQL Server stored procedure from PowerShell?

Use sqlcmd instead of osql if it's a 2005 database

How to change environment's font size?

enter image description here

I have mine set to "editor.fontSize": 12,

Save the file, you will see the effect right the way.

enter image description here

Enjoy !

HTTP Request in Swift with POST method

let session = URLSession.shared
        let url = "http://...."
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        var params :[String: Any]?
        params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
            let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                if let response = response {
                    let nsHTTPResponse = response as! HTTPURLResponse
                    let statusCode = nsHTTPResponse.statusCode
                    print ("status code = \(statusCode)")
                }
                if let error = error {
                    print ("\(error)")
                }
                if let data = data {
                    do{
                        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                        print ("data = \(jsonResponse)")
                    }catch _ {
                        print ("OOps not good JSON formatted response")
                    }
                }
            })
            task.resume()
        }catch _ {
            print ("Oops something happened buddy")
        }

how to run mysql in ubuntu through terminal

You need to log in with the correct username and password. Does the user root have permission to access the database? or did you create a specific user to do this?

The other issue might be that you are not using a password when trying to log in.

Creating a simple XML file using python

For the simplest choice, I'd go with minidom: http://docs.python.org/library/xml.dom.minidom.html . It is built in to the python standard library and is straightforward to use in simple cases.

Here's a pretty easy to follow tutorial: http://www.boddie.org.uk/python/XML_intro.html

PHP equivalent of .NET/Java's toString()

I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) or String.valueOf() does, and it works as well in PHP.

// Java
String myText = (string) myVar;

// PHP
$myText = (string) $myVar;

Note that this can be problematic as Java is type-safe (see here for more details).

But as I said, this is casting and therefore not the equivalent of Java's toString().

toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.

// Java
class SomeClass{
    public String toString(){
        return "some string representation";
    }
}

// PHP
class SomeClass{
    public function __toString()
    {
        return "some string representation";
    }
}

And from the other side:

// Java
new SomeClass().toString(); // "Some string representation"

// PHP
strval(new SomeClass); // "Some string representation"

What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.

  • Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful either.
  • To String instead will give you the String representation, i.e., only the name of the library. This is shorter and therefore gives you less, but more important information.

These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.

Sure, there are even more options:

$no = 421337  // A number in PHP
$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too

All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

How can I get Android Wifi Scan Results into a list?

Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

Replace whole line containing a string using Sed

It is as similar to above one..

sed 's/[A-Za-z0-9]*TEXT_TO_BE_REPLACED.[A-Za-z0-9]*/This line is removed by the admin./'

How do I determine k when using k-means clustering?

km=[]
for i in range(num_data.shape[1]):
    kmeans = KMeans(n_clusters=ncluster[i])#we take number of cluster bandwidth theory
    ndata=num_data[[i]].dropna()
    ndata['labels']=kmeans.fit_predict(ndata.values)
    cluster=ndata
    co=cluster.groupby(['labels'])[cluster.columns[0]].count()#count for frequency
    me=cluster.groupby(['labels'])[cluster.columns[0]].median()#median
    ma=cluster.groupby(['labels'])[cluster.columns[0]].max()#Maximum
    mi=cluster.groupby(['labels'])[cluster.columns[0]].min()#Minimum
    stat=pd.concat([mi,ma,me,co],axis=1)#Add all column
    stat['variable']=stat.columns[1]#Column name change
    stat.columns=['Minimum','Maximum','Median','count','variable']
    l=[]
    for j in range(ncluster[i]):
        n=[mi.loc[j],ma.loc[j]] 
        l.append(n)

    stat['Class']=l
    stat=stat.sort(['Minimum'])
    stat=stat[['variable','Class','Minimum','Maximum','Median','count']]
    if missing_num.iloc[i]>0:
        stat.loc[ncluster[i]]=0
        if stat.iloc[ncluster[i],5]==0:
            stat.iloc[ncluster[i],5]=missing_num.iloc[i]
            stat.iloc[ncluster[i],0]=stat.iloc[0,0]
    stat['Percentage']=(stat[[5]])*100/count_row#Freq PERCENTAGE
    stat['Cumulative Percentage']=stat['Percentage'].cumsum()
    km.append(stat)
cluster=pd.concat(km,axis=0)## see documentation for more info
cluster=cluster.round({'Minimum': 2, 'Maximum': 2,'Median':2,'Percentage':2,'Cumulative Percentage':2})

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

How to Programmatically Add Views to Views

LinearLayout is a subclass of ViewGroup, which has a method called addView. The addView method should be what you are after.

Table border left and bottom

you can use these styles:

style="border-left: 1px solid #cdd0d4;"  
style="border-bottom: 1px solid #cdd0d4;"
style="border-top: 1px solid #cdd0d4;"
style="border-right: 1px solid #cdd0d4;"

with this you want u must use

<td style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;">  

or

<img style="border-left: 1px solid #cdd0d4;border-bottom: 1px solid #cdd0d4;"> 

How to count frequency of characters in a string?

#From C language

 #include<stdio.h>`
 #include <string.h>`
  int main()
{
    char s[1000];  
    int  i,j,k,count=0,n;
    printf("Enter  the string : ");
    gets(s);
    for(j=0;s[j];j++);
    n=j; 
    printf(" frequency count character in string:\n");
    for(i=0;i<n;i++)  
    {
        count=1;
        if(s[i])
        {
        
          for(j=i+1;j<n;j++)  
          {   
            
            if(s[i]==s[j])
            {
                 count++;
                 s[j]='\0';
            }
          }  
          printf(" '%c' = %d \n",s[i],count);
       }
    } 
    return 0;
}

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

explode string in jquery

The split function separates each part of text with the separator you provide, and you provided "|". So the result would be an array containing "Shimla", "1" and "http://vinspro.org/travel/ind/". You could manipulate that to get the third one, "http://vinspro.org/travel/ind/", and here's an example:

var str="Shimla|1|http://vinspro.org/travel/ind/";
var n = str.split('|');
alert(n[2]); 

As mentioned in other answers, this code would differ depending on if it was a string ($(str).split('|');), a textbox input ($(str).val().split('|');), or a DOM element ($(str).text().split('|');).

You could also just use plain JavaScript to get all the stuff after 9 characters, which would be "http://vinspro.org/travel/ind/". Here's an example:

var str="Shimla|1|http://vinspro.org/travel/ind/";
var n=str.substr(9);
alert(n);

How can I multiply all items in a list together with Python?

nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))

How to read fetch(PDO::FETCH_ASSOC);

/* Design Pattern "table-data gateway" */

class Gateway
{
    protected $connection = null;

    public function __construct()
    {
        $this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
    }

    public function loadAll()
    {
        $sql = 'SELECT * FROM users';
        $rows = $this->connection->query($sql);

        return $rows;
    }

    public function loadById($id)
    {
        $sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
        $result = $this->connection->query($sql);

        return $result->fetch(PDO::FETCH_ASSOC);
        // http://php.net/manual/en/pdostatement.fetch.php //                   
    }
}

/* Print all row with column 'user_id' only */

$gateway  = new Gateway();
$users    = $gateway->loadAll();

$no = 1;
foreach ($users as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
    $no++;
}

/* Print user_id = 1 with all column */

$user = $gateway->loadById(1);

$no = 1;
foreach ($user as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value . '<br />';
    $no++;
}

/* Print user_id = 1 with column 'email and password' */

$user = $gateway->loadById(1);

echo $user['email'];
echo $user['password'];

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I'm having the same problem, reading some answers (posted here), I saw my certificate expired.

Just create a new one from my start project. Then at certificates manager deleted the expired certificate.

Now everything compiles fine.

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

If REST applications are supposed to be stateless, how do you manage sessions?

When you develop a RESTful service, in order to be logged in you will need your user to be authenticated. A possible option would be to send the username and password each time you intend to do a user action. In this case the server will not store session-data at all.

Another option is to generate a session-id on the server and send it to the client, so the client will be able to send session-id to the server and authenticate with that. This is much much safer than sending username and password each time, since if somebody gets their hand on that data, then he/she can impersonate the user until the username and password is changed. You may say that even the session id can be stolen and the user will be impersonated in that case and you are right. However, in this case impersonating the user will only be possible while the session id is valid.

If the RESTful API expects username and password in order to change username and password, then even if somebody impersonated the user using the session id, the hacker will not be able to lock out the real user.

A session-id could be generated by one-way-locking (encryption) of something which identifies the user and adding the time to the session id, this way the session's expiry time could be defined.

The server may or may not store session ids. Of course, if the server stores the session id, then it would violate the criteria defined in the question. However, it is only important to make sure that the session id can be validated for the given user, which does not necessitate storing the session id. Imagine a way that you have a one-way-encryption of email, user id and some user-specific private data, like favorite color, this would be the first level and somehow adding the username date to the encrypted string and apply a two-way encryption. As a result when a session id is received, the second level could be decrypted to be able to determine which username the user claims to be and whether the session time is right. If this is valid, then the first level of encryption could be validated by doing that encryption again and checking whether it matches the string. You do not need to store session data in order to achieve that.

Get bitcoin historical data

Bitstamp has live bitcoin data that are publicly available in JSON at this link. Do not try to access it more than 600 times in ten minutes or else they'll block your IP (plus, it's unnecessary anyway; read more here). The below is a C# approach to getting live data:

using (var WebClient = new System.Net.WebClient())
{
     var json = WebClient.DownloadString("https://www.bitstamp.net/api/ticker/");
     string value = Convert.ToString(json);
     // Parse/use from here
}

From here, you can parse the JSON and store it in a database (or with MongoDB insert it directly) and then access it.

For historic data (depending on the database - if that's how you approach it), do an insert from a flat file, which most databases allow you to use (for instance, with SQL Server you can do a BULK INSERT from a CSV file).

Unable to resolve host "<URL here>" No address associated with host name

You probably don't have the INTERNET permission. Try adding this to your AndroidManifest.xml file, right before </manifest>:

<uses-permission android:name="android.permission.INTERNET" />

Note: the above doesn't have to be right before the </manifest> tag, but that is a good / correct place to put it.

Note: if this answer doesn't help in your case, read the other answers!

How to display the value of the bar on each bar with pyplot.barh()?

I have noticed api example code contains an example of barchart with the value of the bar displayed on each bar:

"""
========
Barchart
========

A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt

N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)

women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))


def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

output:

enter image description here

FYI What is the unit of height variable in "barh" of matplotlib? (as of now, there is no easy way to set a fixed height for each bar)

Generic deep diff between two objects

I'd like to offer an ES6 solution...This is a one-way diff, meaning that it will return keys/values from o2 that are not identical to their counterparts in o1:

let o1 = {
  one: 1,
  two: 2,
  three: 3
}

let o2 = {
  two: 2,
  three: 3,
  four: 4
}

let diff = Object.keys(o2).reduce((diff, key) => {
  if (o1[key] === o2[key]) return diff
  return {
    ...diff,
    [key]: o2[key]
  }
}, {})

Java: Get month Integer from Date

java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

What are the rules for casting pointers in C?

Casting pointers is usually invalid in C. There are several reasons:

  1. Alignment. It's possible that, due to alignment considerations, the destination pointer type is not able to represent the value of the source pointer type. For example, if int * were inherently 4-byte aligned, casting char * to int * would lose the lower bits.

  2. Aliasing. In general it's forbidden to access an object except via an lvalue of the correct type for the object. There are some exceptions, but unless you understand them very well you don't want to do it. Note that aliasing is only a problem if you actually dereference the pointer (apply the * or -> operators to it, or pass it to a function that will dereference it).

The main notable cases where casting pointers is okay are:

  1. When the destination pointer type points to character type. Pointers to character types are guaranteed to be able to represent any pointer to any type, and successfully round-trip it back to the original type if desired. Pointer to void (void *) is exactly the same as a pointer to a character type except that you're not allowed to dereference it or do arithmetic on it, and it automatically converts to and from other pointer types without needing a cast, so pointers to void are usually preferable over pointers to character types for this purpose.

  2. When the destination pointer type is a pointer to structure type whose members exactly match the initial members of the originally-pointed-to structure type. This is useful for various object-oriented programming techniques in C.

Some other obscure cases are technically okay in terms of the language requirements, but problematic and best avoided.

How do I extract data from JSON with PHP?

https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w

Check below code for converting json to array in PHP, If JSON is correct then json_decode() works well, and will return an array, But if malformed JSON, then It will return NULL,

<?php
function jsonDecode1($json){
    $arr = json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );

If malformed JSON, and you are expecting only array, then you can use this function,

<?php
function jsonDecode2($json){
    $arr = (array) json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );

If malformed JSON, and you want to stop code execution, then you can use this function,

<?php
function jsonDecode3($json){
    $arr = (array) json_decode($json, true);

    if(empty(json_last_error())){
        return $arr;
    }
    else{
        throw new ErrorException( json_last_error_msg() );
    }
}

// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );

You can use any function depends on your requirement,

Zip lists in Python

In Python 2.7 this might have worked fine:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

Improving bulk insert performance in Entity framework

There is no way to force EF to improve performance when doing it this way. The problem is that EF executes each insert in separate round trip to the database. Awesome isn't it? Even DataSets supported batch processing. Check this article for some workaround. Another workaround can be using custom stored procedure accepting table valued parameter but you need raw ADO.NET for that.

How can I declare dynamic String array in Java

Maybe you are looking for Vector. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList instead.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

How do I output coloured text to a Linux terminal?

try my header here for a quick and easy way to color text: Aedi's Color Header


Escape-Sequence-Color-Header

Color Your Output in Unix using C++!!


Text Attribute Options:

ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED


Color Options:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE


Format:

General Format, include value you want in $variable$

COLOR_$Foreground_Color$_$Background_Color$
COLOR_$Text_Attribute$_$Foreground_Color$_$Background_Color$
COLOR_NORMAL  // To set color to default

e.g.

COLOR_BLUE_BLACK // Leave Text Attribute Blank if no Text Attribute appied
COLOR_UNDERSCORE_YELLOW_RED
COLOR_NORMAL


Usage:

Just use to stream the color you want before outputting text and use again to set the color to normal after outputting text.

cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;

How to take a first character from the string

Try this..

Dim S As String
S = "RAJAN"
Dim answer As Char
answer = S.Substring(0, 1)

Docker Error bind: address already in use

I resolve the issue by restarting Docker.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

If you use angular remove the ng-storage profile from your browser console. It is not a general solution bit It worked in my case.

In Chrome F12->Resources->Local Storage

How to save a dictionary to a file?

For a dictionary of strings such as the one you're dealing with, it could be done using only Python's built-in text processing capabilities.

(Note this wouldn't work if the values are something else.)

with open('members.txt') as file:
    mdict={}
    for line in file:
        a, b, c, d = line.strip().split(':')
        mdict[a] = b + ':' + c + ':' + d

a = input('ID: ')
if a not in mdict:
    print('ID {} not found'.format(a))
else:
    b, c, d = mdict[a].split(':')
    d = input('phone: ')
    mdict[a] = b + ':' + c + ':' + d  # update entry
    with open('members.txt', 'w') as file:  # rewrite file
        for id, values in mdict.items():
            file.write(':'.join([id] + values.split(':')) + '\n')

how to fix Cannot call sendRedirect() after the response has been committed?

you have already forwarded the response in catch block:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");

dd.forward(request, response);

so, you can not again call the :

response.sendRedirect("usertaskpage.jsp");

because it is already forwarded (committed).

So what you can do is: keep a string to assign where you need to forward the response.

    String page = "";
    try {

    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }

RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

Java URL encoding of query string parameters

  1. Use this: URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); or this:URLEncoder.encode(query, "UTF-8");
  2. You can use the follwing code.

    String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8");//not change 
    String encodedUrl2 = URLEncoder.encode(query, "UTF-8");//changed
    String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());//changed
    
    System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);
    

How do you read a file into a list in Python?

You need to pass a filename string to open. There's an extra complication when the string has \ in it, because that's a special string escape character to Python. You can fix this by doubling up each as \\ or by putting a r in front of the string as follows: r'C:\name\MyDocuments\numbers'.

Edit: The edits to the question make it completely different from the original, and since none of them was from the original poster I'm not sure they're warrented. However it does point out one obvious thing that might have been overlooked, and that's how to add "My Documents" to a filename.

In an English version of Windows XP, My Documents is actually C:\Documents and Settings\name\My Documents. This means the open call should look like:

open(r"C:\Documents and Settings\name\My Documents\numbers", 'r')

I presume you're using XP because you call it My Documents - it changed in Vista and Windows 7. I don't know if there's an easy way to look this up automatically in Python.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

Run MySQLDump without Locking Tables

If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks
to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file.

How to draw checkbox or tick mark in GitHub Markdown table?

Now emojis are supported! :white_check_mark: / :heavy_check_mark: gives a good impression and is widely supported:

Function | MySQL / MariaDB | PostgreSQL | SQLite
:------------ | :-------------| :-------------| :-------------
substr | :heavy_check_mark: |  :white_check_mark: | :heavy_check_mark:

renders to (here on older chromium 65.0.3x) :

enter image description here

Plotting a fast Fourier transform in Python

I write this additional answer to explain the origins of the diffusion of the spikes when using FFT and especially discuss the scipy.fftpack tutorial with which I disagree at some point.

In this example, the recording time tmax=N*T=0.75. The signal is sin(50*2*pi*x) + 0.5*sin(80*2*pi*x). The frequency signal should contain two spikes at frequencies 50 and 80 with amplitudes 1 and 0.5. However, if the analysed signal does not have a integer number of periods diffusion can appear due to the truncation of the signal:

  • Pike 1: 50*tmax=37.5 => frequency 50 is not a multiple of 1/tmax => Presence of diffusion due to signal truncation at this frequency.
  • Pike 2: 80*tmax=60 => frequency 80 is a multiple of 1/tmax => No diffusion due to signal truncation at this frequency.

Here is a code that analyses the same signal as in the tutorial (sin(50*2*pi*x) + 0.5*sin(80*2*pi*x)), but with the slight differences:

  1. The original scipy.fftpack example.
  2. The original scipy.fftpack example with an integer number of signal periods (tmax=1.0 instead of 0.75 to avoid truncation diffusion).
  3. The original scipy.fftpack example with an integer number of signal periods and where the dates and frequencies are taken from the FFT theory.

The code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# 1. Linspace
N = 600
# Sample spacing
tmax = 3/4
T = tmax / N # =1.0 / 800.0
x1 = np.linspace(0.0, N*T, N)
y1 = np.sin(50.0 * 2.0*np.pi*x1) + 0.5*np.sin(80.0 * 2.0*np.pi*x1)
yf1 = scipy.fftpack.fft(y1)
xf1 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 2. Integer number of periods
tmax = 1
T = tmax / N # Sample spacing
x2 = np.linspace(0.0, N*T, N)
y2 = np.sin(50.0 * 2.0*np.pi*x2) + 0.5*np.sin(80.0 * 2.0*np.pi*x2)
yf2 = scipy.fftpack.fft(y2)
xf2 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 3. Correct positioning of dates relatively to FFT theory ('arange' instead of 'linspace')
tmax = 1
T = tmax / N # Sample spacing
x3 = T * np.arange(N)
y3 = np.sin(50.0 * 2.0*np.pi*x3) + 0.5*np.sin(80.0 * 2.0*np.pi*x3)
yf3 = scipy.fftpack.fft(y3)
xf3 = 1/(N*T) * np.arange(N)[:N//2]

fig, ax = plt.subplots()
# Plotting only the left part of the spectrum to not show aliasing
ax.plot(xf1, 2.0/N * np.abs(yf1[:N//2]), label='fftpack tutorial')
ax.plot(xf2, 2.0/N * np.abs(yf2[:N//2]), label='Integer number of periods')
ax.plot(xf3, 2.0/N * np.abs(yf3[:N//2]), label='Correct positioning of dates')
plt.legend()
plt.grid()
plt.show()

Output:

As it can be here, even with using an integer number of periods some diffusion still remains. This behaviour is due to a bad positioning of dates and frequencies in the scipy.fftpack tutorial. Hence, in the theory of discrete Fourier transforms:

  • the signal should be evaluated at dates t=0,T,...,(N-1)*T where T is the sampling period and the total duration of the signal is tmax=N*T. Note that we stop at tmax-T.
  • the associated frequencies are f=0,df,...,(N-1)*df where df=1/tmax=1/(N*T) is the sampling frequency. All harmonics of the signal should be multiple of the sampling frequency to avoid diffusion.

In the example above, you can see that the use of arange instead of linspace enables to avoid additional diffusion in the frequency spectrum. Moreover, using the linspace version also leads to an offset of the spikes that are located at slightly higher frequencies than what they should be as it can be seen in the first picture where the spikes are a little bit at the right of the frequencies 50 and 80.

I'll just conclude that the example of usage should be replace by the following code (which is less misleading in my opinion):

import numpy as np
from scipy.fftpack import fft

# Number of sample points
N = 600
T = 1.0 / 800.0
x = T*np.arange(N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = 1/(N*T)*np.arange(N//2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()

Output (the second spike is not diffused anymore):

I think this answer still bring some additional explanations on how to apply correctly discrete Fourier transform. Obviously, my answer is too long and there is always additional things to say (ewerlopes talked briefly about aliasing for instance and a lot can be said about windowing), so I'll stop.

I think that it is very important to understand deeply the principles of discrete Fourier transform when applying it because we all know so much people adding factors here and there when applying it in order to obtain what they want.

Constructors in JavaScript objects

I guess I'll post what I do with javascript closure since no one is using closure yet.

var user = function(id) {
  // private properties & methods goes here.
  var someValue;
  function doSomething(data) {
    someValue = data;
  };

  // constructor goes here.
  if (!id) return null;

  // public properties & methods goes here.
  return {
    id: id,
    method: function(params) {
      doSomething(params);
    }
  };
};

Comments and suggestions to this solution are welcome. :)

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

To answer the question asked, here is the most accurate SQL to accomplish the job, you can combine it with PL/SQL loop to actually run kill statements:

select ses.USERNAME,
    substr(MACHINE,1,10) as MACHINE, 
    substr(module,1,25) as module,
    status, 
    'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill
from v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)
where schemaname <> 'SYS'
    and not exists
    (select 1 
        from DBA_ROLE_PRIVS 
        where GRANTED_ROLE='DBA' 
            and schemaname=grantee)
    and machine!='yourlocalhostname' 
order by LAST_CALL_ET desc;

How to convert int to date in SQL Server 2008

If your integer is timestamp in milliseconds use:

SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name

It will format milliseconds to yyyy-mm-dd string.

'any' vs 'Object'

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

Java 8: Difference between two LocalDateTime in multiple units

I found the best way to do this is with ChronoUnit.

long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
long hours = ChronoUnit.HOURS.between(fromDate, toDate);

Additional documentation is here: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

Call Javascript onchange event by programmatically changing textbox value

Onchange is only fired when user enters something by keyboard. A possible workarround could be to first focus the textfield and then change it.

But why not fetch the event when the user clicks on a date? There already must be some javascript.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

How do I get the current time zone of MySQL?

To anyone come to find timezone of mysql db.

With this query you can get current timezone :

mysql> SELECT @@system_time_zone as tz;
+-------+
|  tz   |
+-------+
|  CET  |
+-------+

Detecting which UIButton was pressed in a UITableView

A slight variation on Cocoanuts answer (that helped me solve this) when the button was in the footer of a table (which prevents you from finding the 'clicked cell':

-(IBAction) buttonAction:(id)sender;
{
    id parent1 = [sender superview];   // UiTableViewCellContentView
    id parent2 = [parent1 superview];  // custom cell containing the content view
    id parent3 = [parent2 superview];  // UITableView containing the cell
    id parent4 = [parent3 superview];  // UIView containing the table

    UIView *myContentView = (UIView *)parent1;
    UITableViewCell *myTableCell = (UITableViewCell *)parent2;
    UITableView *myTable = (UITableView *)parent3;
    UIView *mainView = (UIView *)parent4;

    CGRect footerViewRect = myTableCell.frame;
    CGRect rect3 = [myTable convertRect:footerViewRect toView:mainView];    

    [cc doSomethingOnScreenAtY:rect3.origin.y];
}

twitter bootstrap typeahead ajax example

 $('#runnerquery').typeahead({
        source: function (query, result) {
            $.ajax({
                url: "db.php",
                data: 'query=' + query,            
                dataType: "json",
                type: "POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
        },
        updater: function (item) {
        //selectedState = map[item].stateCode;

       // Here u can obtain the selected suggestion from the list


        alert(item);
            }

    }); 

 //Db.php file
<?php       
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');

$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);            
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $Resut[] = $row["name"];
    }
    echo json_encode($Result);
}
$conn->close();

?>

Render partial from different folder (not shared)

Just include the path to the view, with the file extension.

Razor:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

What are XAND and XOR

First comes the logic, then the name, possibly patterned on previous naming.

Thus 0+0=0; 0+1=1; 1+0=1; 1+1=1 - for some reason this is called OR.

Then 0-0=0; 0-1=1; 1-0=1; 1-1=0 - it looks like OR except ... let's call it XOR.

Also 0*0=0; 0*1=0; 1*0=0; 1*1=1 - for some reason this is called AND.

Then 0~0=0; 0~1=0; 1~0=0; 1~1=0 - it looks like AND except ... let's call it XAND.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to convert NUM to INT in R?

Use as.integer:

set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819


as.integer(x)
[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

Oracle SQL update based on subquery between two tables

Try it ..

UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
        FROM STAGING b
        WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
    FROM STAGING b
    WHERE a.ID=b.ID
 );

Javascript (+) sign concatenates instead of giving sum of variables

divID = "question-" + parseInt(i+1,10);

check it here, it's a JSFiddle

How do I iterate through table rows and cells in JavaScript?

Try

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}

_x000D_
_x000D_
for (let row of mytab1.rows) _x000D_
{_x000D_
    for(let cell of row.cells) _x000D_
    {_x000D_
       console.log(cell.innerText)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
for ( let [i,row] of [...mytab1.rows].entries() ) _x000D_
{_x000D_
    for( let [j,cell] of [...row.cells].entries() ) _x000D_
    {_x000D_
       console.log(`[${i},${j}] = ${cell.innerText}`)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Choose newline character in Notepad++

"Edit -> EOL Conversion". You can convert to Windows/Linux/Mac EOL there. The current format is displayed in the status bar.

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

If you get errors trying to install mysqlclient with pip, you may lack the mysql dev library. Install it by running:

apt-get install libmysqlclient-dev

and try again to install mysqlclient:

pip install mysqlclient

Difference between an API and SDK

API = Dictionary of available words and their meanings (and the required grammar to combine them)

SDK = A Word processing system… for 2 year old babies… that writes right from ideas

Although you COULD go to school and become a master in your language after a few years, using the SDK will help you write whole meaningful sentences in no time (Forgiving the fact that, in this example, as a baby you haven't even gotten to learn any other language for at least to learn to use the SDK.)

How can I close a login form and show the main form without my application closing?

Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash

in frm-main

public partial class frmMain : Form
{
    public frmMain()
    { 
        frmSplash frm = new frmSplash();
        frm.Show(); // new splash screen will shows
        this.Opacity=0; // will hide your main form
        InitializeComponent();
    }
 }

in the frm-Splash

private void timer1_Tick(object sender, EventArgs e)
{
 int cnt = progressBar1.Value;

    switch (cnt)
    {
        case 0:
                //Do sum stuff
            break;
        case 100:

            this.Close(); //close the frm-splash
            frmMain.ActiveForm.Opacity = 100; // show the frm-main

            break;
    }

    progressBar1.Value = progressBar1.Value+1;
}

if you use it for login form

private void btlogin_Click(object sender, EventArgs e)
{
 bool login = false;

    //try your login here 
    //connect your database or whatever
    //and then when it success update login variable as true

        if(login == true){

            this.Close(); //close the frm-login
            frmMain.ActiveForm.Opacity = 100; // show the frm-main

        }else{
              //inform user about failed login
        }
}

note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Note that this last variable allows you to for example run Android Studio with Java 7 on OSX (which normally picks Java 6 from the version specified in Info.plist):

$ export STUDIO_JDK=/Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk

$ open /Applications/Android\ Studio.app

Worked for me

Find column whose name contains a specific string

You also can use this code:

spike_cols =[x for x in df.columns[df.columns.str.contains('spike')]]

How to remove all callbacks from a Handler?

Define a new handler and runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do what ever you want
        }
    };

Call post delayed:

handler.postDelayed(runnable, sleep_time);

Remove your callback from your handler:

handler.removeCallbacks(runnable);

Oracle SqlPlus - saving output in a file but don't show on screen

Try This:

sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null

Clearing localStorage in javascript?

Use this to clear localStorage:

localStorage.clear();

How to check if a string contains only digits in Java

One more solution, that hasn't been posted, yet:

String regex = "\\p{Digit}+"; // uses POSIX character class

Correct way to push into state array

Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,

this.setState({ 
     myArray: [...this.state.myArray, 'new value'] 
})

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

Restore the mysql database from .frm files

Yes this is possible. It is not enough you just copy the .frm files to the to the databse folder but you also need to copy the ib_logfiles and ibdata file into your data folder. I have just copy the .frm files and copy those files and just restart the server and my database is restored.

After copying the above files execute the following command -

sudo chown -R mysql:mysql /var/lib/mysql

The above command will change the file owner under mysql and it's folder to MySql user. Which is important for mysql to read the .frm and ibdata files.

Exploitable PHP functions

Also be aware of the class of "interruption vulnerabilities" that allow arbitrary memory locations to be read and written!

These affect functions such as trim(), rtrim(), ltrim(), explode(), strchr(), strstr(), substr(), chunk_split(), strtok(), addcslashes(), str_repeat() and more. This is largely, but not exclusively, due to the call-time pass-by-reference feature of the language that has been deprecated for 10 years but not disabled.

Fore more info, see Stefan Esser’s talk about interruption vulnerabilities and other lower-level PHP issues at BlackHat USA 2009 Slides Paper

This paper/presentation also shows how dl() can be used to execute arbitrary system code.

How to sum up elements of a C++ vector?

Why perform the summation forwards when you can do it backwards? Given:

std::vector<int> v;     // vector to be summed
int sum_of_elements(0); // result of the summation

We can use subscripting, counting backwards:

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v[i-1];

We can use range-checked "subscripting," counting backwards (just in case):

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v.at(i-1);

We can use reverse iterators in a for loop:

for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
    sum_of_elements += *i;

We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):

for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
    sum_of_elements += *(i - 1);

We can use accumulate with reverse iterators:

sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);

We can use for_each with a lambda expression using reverse iterators:

std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });

So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.

Using Python 3 in virtualenv

On Mac I had to do the following to get it to work.

mkvirtualenv --python=/usr/bin/python3 YourEnvNameHere

.htaccess mod_rewrite - how to exclude directory from rewrite rule

We used the following mod_rewrite rule:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/test/
RewriteCond %{REQUEST_URI} !^/my-folder/
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

This redirects (permanently with a 301 redirect) all traffic to the site to http://www.newdomain.com, except requests to resources in the /test and /my-folder directories. We transfer the user to the exact resource they requested by using the (.*) capture group and then including $1 in the new URL. Mind the spaces.

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

Why are only final variables accessible in anonymous class?

Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.

How do I get the number of elements in a list?

To get the number of element in any iterable object, your goto method in Python is len() eg.

a = range(1000) # range
b = 'abcdefghijklmnopqrstuvwxyz' # string
c = [10, 20, 30] # List
d = (30, 40, 50, 60, 70) # tuple
e = {11, 21, 31, 41} # set

len() method can work on all the above data types because they are iterable i.e You can iterate over them.

all_var = [a, b, c, d, e] # All variables are stored to a list
for var in all_var:
    print(len(var))

Rough estimate of the len() method

def len(iterable, /):
    total = 0
    for i in iterable:
        total += 1
    return total

Add "Are you sure?" to my excel button, how can I?

Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

Excel VBA: Copying multiple sheets into new workbook

Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.

How to find a value in an array of objects in JavaScript?

var getKeyByDinner = function(obj, dinner) {
    var returnKey = -1;

    $.each(obj, function(key, info) {
        if (info.dinner == dinner) {
           returnKey = key;
           return false; 
        };   
    });

    return returnKey;       

}

jsFiddle.

So long as -1 isn't ever a valid key.

How to fix ReferenceError: primordials is not defined in node

This might have come in late but for anyone still interested in keeping their Node v12 while using the latest gulp ^4.0, follow these steps:

Update the command-line interface (just for precaution) using:

npm i gulp-cli -g

Add/Update the gulp under dependencies section of your package.json

"dependencies": {
  "gulp": "^4.0.0"
}

Delete your package-lock.json file

Delete your node_modules folder

Finally, Run npm i to upgrade and recreate brand new node_modules folder and package-lock.json file with correct parameters for Gulp ^4.0

npm i

Note Gulp.js 4.0 introduces the series() and parallel() methods to combine tasks instead of the array methods used in Gulp 3, and so you may or may not encounter an error in your old gulpfile.js script.

To learn more about applying these new features, this site have really done justice to it: https://www.sitepoint.com/how-to-migrate-to-gulp-4/

(If it helps, please leave a thumps up)

Regex number between 1 and 100

Regular Expression for 0 to 100 with the decimal point.

^100(\.[0]{1,2})?|([0-9]|[1-9][0-9])(\.[0-9]{1,2})?$

How can I add reflection to a C++ application?

EDIT: Updated broken link as of February, the 7th, 2017.

I think noone mentioned this:

At CERN they use a full reflection system for C++:

CERN Reflex. It seems to work very well.

What do hjust and vjust do when making a plot using ggplot?

Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.

enter image description here

However, it is not quite that simple. hjust and vjust as described there are how it works in geom_text and theme_text (sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust of 0.5 and a vjust of 0.5 center the box on the reference point. Reducing hjust moves the box right by an amount of the box width times 0.5-hjust. Thus when hjust=0, the left edge of the box is at the reference point. Increasing hjust moves the box left by an amount of the box width times hjust-0.5. When hjust=1, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5 box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].

But, sometimes this doesn't work. For example

DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))

The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider

p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))

The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.

Programmatically create a UIView with color gradient

This is my recommended approach.

To promote reusability, I'd say create a category of CAGradientLayer and add your desired gradients as class methods. Specify them in the header file like this :

#import <QuartzCore/QuartzCore.h>

@interface CAGradientLayer (SJSGradients)

+ (CAGradientLayer *)redGradientLayer;
+ (CAGradientLayer *)blueGradientLayer;
+ (CAGradientLayer *)turquoiseGradientLayer;
+ (CAGradientLayer *)flavescentGradientLayer;
+ (CAGradientLayer *)whiteGradientLayer;
+ (CAGradientLayer *)chocolateGradientLayer;
+ (CAGradientLayer *)tangerineGradientLayer;
+ (CAGradientLayer *)pastelBlueGradientLayer;
+ (CAGradientLayer *)yellowGradientLayer;
+ (CAGradientLayer *)purpleGradientLayer;
+ (CAGradientLayer *)greenGradientLayer;

@end

Then in your implementation file, specify each gradient with this syntax :

+ (CAGradientLayer *)flavescentGradientLayer
{
    UIColor *topColor = [UIColor colorWithRed:1 green:0.92 blue:0.56 alpha:1];
    UIColor *bottomColor = [UIColor colorWithRed:0.18 green:0.18 blue:0.18 alpha:1];

    NSArray *gradientColors = [NSArray arrayWithObjects:(id)topColor.CGColor, (id)bottomColor.CGColor, nil];
    NSArray *gradientLocations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:1.0], nil];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = gradientColors;
    gradientLayer.locations = gradientLocations;

    return gradientLayer;
}

Then simply import this category in your ViewController or any other required subclass, and use it like this :

CAGradientLayer *backgroundLayer = [CAGradientLayer purpleGradientLayer];
backgroundLayer.frame = self.view.frame;
[self.view.layer insertSublayer:backgroundLayer atIndex:0];

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

How to connect to a remote Git repository?

It's simple and follow the small Steps to proceed:

  • Install git on the remote server say some ec2 instance
  • Now create a project folder `$mkdir project.git
  • $cd project and execute $git init --bare

Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git, forex- ec2 - /home/ubuntu/workspace/project.git

Now in your local machine, $cd into the project folder which you want to push to git execute the below commands:

  • git init .

  • git remote add origin [email protected]:/home/ubuntu/workspace/project.git

  • git add .
  • git commit -m "Initial commit"

Below is an optional command but found it has been suggested as i was working to setup the same thing

git config --global remote.origin.receivepack "git receive-pack"

  • git pull origin master
  • git push origin master

This should work fine and will push the local code to the remote git repository.

To check the remote fetch url, cd project_folder/.git and cat config, this will give the remote url being used for pull and push operations.

You can also use an alternative way, after creating the project.git folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.

Can I fade in a background image (CSS: background-image) with jQuery?

You can give opacity value as

div {opacity: 0.4;}

For IE, you can specify as

div { filter:alpha(opacity=10));}

Lower the value - Higher the transparency.

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

How to convert byte array to string

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

Most efficient way to see if an ArrayList contains an object in Java

If you are a user of my ForEach DSL, it can be done with a Detect query.

Foo foo = ...
Detect<Foo> query = Detect.from(list);
for (Detect<Foo> each: query) 
    each.yield = each.element.a == foo.a && each.element.b == foo.b;
return query.result();

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

Possible reason for NGINX 499 error codes

This error is pretty easy to reproduce using standard nginx configuration with php-fpm.

Keeping the F5 button down on a page will create dozens of refresh requests to the server. Each previous request is canceled by the browser at new refresh. In my case I found dozens of 499's in my client's online shop log file. From an nginx point of view: If the response has not been delivered to the client before the next refresh request nginx logs the 499 error.

mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:32 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:35 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:35 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)

If the php-fpm processing takes longer (like a heavyish WP page) it may cause problems, of course. I have heard of php-fpm crashes, for instance, but I believe they can be prevented configuring services properly like handling calls to xmlrpc.php.

Creating a PHP header/footer

You can do it by using include_once() function in php. Construct a header part in the name of header.php and construct the footer part by footer.php. Finally include all the content in one file.

For example:

header.php

<html>
<title>
<link href="sample.css">

footer.php

</html>

So the final files look like

include_once("header.php") 

body content(The body content changes based on the file dynamically)

include_once("footer.php") 

How do I obtain crash-data from my Android application?

Just Started to use ACRA https://github.com/ACRA/acra using Google Forms as backend and it's very easy to setup & use, it's the default.

BUT Sending reports to Google Forms are going to be deprecated (then removed): https://plus.google.com/118444843928759726538/posts/GTTgsrEQdN6 https://github.com/ACRA/acra/wiki/Notice-on-Google-Form-Spreadsheet-usage

Anyway it's possible to define your own sender https://github.com/ACRA/acra/wiki/AdvancedUsage#wiki-Implementing_your_own_sender you can give a try to email sender for example.

With minimum effort it's possible to send reports to bugsense: http://www.bugsense.com/docs/android#acra

NB The bugsense free account is limited to 500 report/month

Disabling and enabling a html input button

Disabling/enabling an html input button with JavaScript:

(And React with refs. Replace "elementRef.current" with element selection if not using React)

 elementRef.current.setAttribute('disabled', 'disabled');

Enable:

 elementRef.current.removeAttribute('disabled');

How can I use JQuery to post JSON data?

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

Laravel Eloquent where field is X or null

It sounds like you need to make use of advanced where clauses.

Given that search in field1 and field2 is constant we will leave them as is, but we are going to adjust your search in datefield a little.

Try this:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(function ($query) {
        $query->where('datefield', '<', $date)
            ->orWhereNull('datefield');
    }
);

If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql() to the end of your eloquent query to generate the SQL.

What is the right way to check for a null string in Objective-C?

There are two situations:

It is possible that an object is [NSNull null], or it is impossible.
Your application usually shouldn't use [NSNull null]; you only use it if you want to put a "null" object into an array, or use it as a dictionary value. And then you should know which arrays or dictionaries might contain null values, and which might not.
If you think that an array never contains [NSNull null] values, then don't check for it. If there is an [NSNull null], you might get an exception but that is fine: Objective-C exceptions indicate programming errors. And you have a programming error that needs fixing by changing some code.

If an object could be [NSNull null], then you check for this quite simply by testing
(object == [NSNull null]). Calling isEqual or checking the class of the object is nonsense. There is only one [NSNull null] object, and the plain old C operator checks for it just fine in the most straightforward and most efficient way.

If you check an NSString object that cannot be [NSNull null] (because you know it cannot be [NSNull null] or because you just checked that it is different from [NSNull null], then you need to ask yourself how you want to treat an empty string, that is one with length 0. If you treat it is a null string like nil, then test (object.length == 0). object.length will return 0 if object == nil, so this test covers nil objects and strings with length 0. If you treat a string of length 0 different from a nil string, just check if object == nil.

Finally, if you want to add a string to an array or a dictionary, and the string could be nil, you have the choice of not adding it, replacing it with @"", or replacing it with [NSNull null]. Replacing it with @"" means you lose the ability to distinguish between "no string" and "string of length 0". Replacing it with [NSNull null] means you have to write code when you access the array or dictionary that checks for [NSNull null] objects.

C# looping through an array

i++ is the standard use of a loop, but not the only way. Try incrementing by 3 each time:

 for (int i = 0; i < theData.Length - 2; i+=3) 
    { 

        // use theData[i], theData[i+1], theData[i+2]

    } 

Component is part of the declaration of 2 modules

Solution is very simple. Find *.module.ts files and comment declarations. In your case find addevent.module.ts file and remove/comment one line below:

@NgModule({
  declarations: [
    // AddEvent, <-- Comment or Remove This Line
  ],
  imports: [
    IonicPageModule.forChild(AddEvent),
  ],
})

This solution worked in ionic 3 for pages that generated by ionic-cli and works in both ionic serve and ionic cordova build android --prod --release commands!

Be happy...

Last Key in Python Dictionary

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

How to create windows service from java jar?

With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:

set PR_PATH=%CD%
SET PR_SERVICE_NAME=MyService
SET PR_JAR=MyService.jar
SET START_CLASS=org.my.Main
SET START_METHOD=main
SET STOP_CLASS=java.lang.System
SET STOP_METHOD=exit
rem ; separated values
SET STOP_PARAMS=0
rem ; separated values
SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%

I presume to

  • run this from the same directory where the jar and prunsrv.exe is
  • the jar has its working MANIFEST.MF
  • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
  • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

Check the procrun manual and this tutorial for more information.

Determine the line of code that causes a segmentation fault?

You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g flag.

Whenever you get the message:

 Segmentation fault (core dumped)

a core file is written into your current directory. And you can examine it with the command

 gdb your_program core_file

The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software.

Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:

ulimit -c unlimited

Careful though! that core dumps can become huge.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

What is exactly the base pointer and stack pointer? To what do they point?

esp stands for "Extended Stack Pointer".....ebp for "Something Base Pointer"....and eip for "Something Instruction Pointer"...... The stack Pointer points to the offset address of the stack segment. The Base Pointer points to the offset address of the extra segment. The Instruction Pointer points to the offset address of the code segment. Now, about the segments...they are small 64KB divisions of the processors memory area.....This process is known as Memory Segmentation. I hope this post was helpful.

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

How do you stylize a font in Swift?

A great resource is iosfonts.com, which says that the name for that font is HelveticaNeue-UltraLight. So you'd use this code:

label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30)

If the system can't find the font, it defaults to a 'normal' font - I think it's something like 11-point Helvetica. This can be quite confusing, always check your font names.

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

How can I find script's directory?

This worked for me (and I found it via the this stackoverflow question)

os.path.realpath(__file__)

How to read embedded resource text file

I read an embedded resource text file use:

    /// <summary>
    /// Converts to generic list a byte array
    /// </summary>
    /// <param name="content">byte array (embedded resource)</param>
    /// <returns>generic list of strings</returns>
    private List<string> GetLines(byte[] content)
    {
        string s = Encoding.Default.GetString(content, 0, content.Length - 1);
        return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
    }

Sample:

var template = GetLines(Properties.Resources.LasTemplate /* resource name */);

template.ForEach(ln =>
{
    Debug.WriteLine(ln);
});

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

For an Ant project:

Make sure, you have servlet-api.jar in the lib folder.

For a Maven project:

Make sure, you have the dependency added in POM.xml.

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

Another way to do it is: Update the project facets to pick up the right server.

Check this box in this location:

Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)

Adb install failure: INSTALL_CANCELED_BY_USER

For Redmi and Mi devices turn off MIUI Optimization

Settings > Additional Settings > Developer Options > MIUI Optimization

How to search all loaded scripts in Chrome Developer Tools?

Open a new Search pane in Developer Tools by:

  • pressing Ctrl+Shift+F (Cmd+Option+I on mac)
  • clicking the overflow menu (?) in DevTools, DevTools overflow menu
  • clicking the overflow menu in the Console (?) and choosing the Search option

You can search across all your scripts with support for regular expressions and case sensitivity.

Click any match to load that file/section in the scripts panel.

Search all files - results

Make sure 'Search in anonymous and content scripts' is checked in the DevTools Preferences (F1). This will return results from within iframes and HTML inline scripts:

Search in anonymous and content scripts DevTools Settings Preferences

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

Create an Application class and start your service:

public class App extends Application {

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

        startService(new Intent(this, YourService.class));
    }
}

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

UPDATE

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

EDIT: RESTRICTED OEMS

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)

Create Pandas DataFrame from a string

A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.

Select the content of the string with your mouse:

Copy data for pasting into a Pandas dataframe

In the Python shell use read_clipboard()

>>> pd.read_clipboard()
  col1;col2;col3
0       1;4.4;99
1      2;4.5;200
2       3;4.7;65
3      4;3.2;140

Use the appropriate separator:

>>> pd.read_clipboard(sep=';')
   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

>>> df = pd.read_clipboard(sep=';') # save to dataframe

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use