Programs & Examples On #Boost serialization

Boost.Serialization is a cross-platform C++ serialization library.

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"

here is the sample

  <connectionStrings>
    <add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
  </connectionStrings>

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How do I send a file in Android from a mobile device to server using http?

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

Hosting ASP.NET in IIS7 gives Access is denied?

This is what happened to me:

Get - Post is ok. Working well.

When I try to use Options verb, the server return error like that.

403

Then, beware with urlScan

I add OPTIONS verb to urlscan configuration .ini file, then everything works well.

To check if urlscan is installed or not, open your iis manager, and open ISAPI FILTERS url scan should appear at the list.

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to split a line into words separated by one or more spaces in bash?

s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...

Regular Expression to reformat a US phone number in Javascript

Assuming you want the format "(123) 456-7890":

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3]
  }
  return null
}

Here's a version that allows the optional +1 international code:

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    var intlCode = (match[1] ? '+1 ' : '')
    return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
  }
  return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900')   // => "(234) 567-8900"

Uncaught TypeError: Cannot set property 'value' of null

h_url=document.getElementById("u") is null here

There is no element exist with id as u

In Tkinter is there any way to make a widget not visible?

import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
    lb.config(visible=visible)
visiblelabel(x, False)  # Hide
visiblelabel(x, True)  # Show

P.S. config can change any attribute:

x.config(text='Hello')  # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold'))  # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white')  # Background: red, Foreground: white

It's a bypass of StringVar, IntVar etc.

How to merge every two lines into one from the command line?

Alternative to sed, awk, grep:

xargs -n2 -d'\n'

This is best when you want to join N lines and you only need space delimited output.

My original answer was xargs -n2 which separates on words rather than lines. -d can be used to split the input by any single character.

How to get client's IP address using JavaScript?

Use ipdata.co.

The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#response").html(response.ip);_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

String to char array Java

A string to char array is as simple as

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

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

* Update *

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

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

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

With the following output

0x65 0x10 0xf3 0x29

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

How to make div occupy remaining height?

Demo

One way is to set the the div to position:absolute and give it a top of 50px and bottom of 0px;

#div2
{
    position:absolute;
    bottom:0px;
    top:50px
}

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Efficient iteration with index in Scala

A simple and efficient way, inspired from the implementation of transform in SeqLike.scala

    var i = 0
    xs foreach { el =>
      println("String #" + i + " is " + xs(i))
      i += 1
    }

What is the purpose of Looper and how to use it?

Understanding Looper Threads

A java Thread a unit of execution which was designed to perform a task in its run() method & terminate after that: enter image description here

But in Android there are many use cases where we need to keep a Thread alive and wait for user inputs/events for eg. UI thread aka Main Thread.

Main thread in Android is a Java thread which is first started by JVM at the launch of an app and keeps on running till the user choose to close it or encounters unhandled exception.

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events.

enter image description here

Now point to note here is although main thread is Java thread yet it keeps on listening to user events and draw 60 fps frames on screen and still it wont die after each cycle. how is it so?

The answer is Looper Class: Looper is a class which is used to keep a thread alive and manage a message queue to execute tasks on that thread.

Threads by default do not have a message loop associated with them but you can assign one by calling Looper.prepare() in the run method and then call the Looper.loop().

Purpose of Looper is to keep a Thread alive and wait for next cycle of input Message object to perform computation which otherwise will get destroyed after first cycle of execution.

If you want to dig deeper how Looper manage Message object queue then you can have a look at source code of Looperclass:

https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/Looper.java

Below is an example of how you can create a Looper Thread and communicate with Activity class using LocalBroadcast

class LooperThread : Thread() {

    // sendMessage success result on UI
    private fun sendServerResult(result: String) {
        val resultIntent = Intent(ServerService.ACTION)
        resultIntent.putExtra(ServerService.RESULT_CODE, Activity.RESULT_OK)
        resultIntent.putExtra(ServerService.RESULT_VALUE, result)
        LocalBroadcastManager.getInstance(AppController.getAppController()).sendBroadcast(resultIntent)
    }

    override fun run() {
        val looperIsNotPreparedInCurrentThread = Looper.myLooper() == null

        // Prepare Looper if not already prepared
        if (looperIsNotPreparedInCurrentThread) {
            Looper.prepare()
        }

        // Create a handler to handle messaged from Activity
        handler = Handler(Handler.Callback { message ->
            // Messages sent to Looper thread will be visible here
            Log.e(TAG, "Received Message" + message.data.toString())

            //message from Activity
            val result = message.data.getString(MainActivity.BUNDLE_KEY)

            // Send Result Back to activity
            sendServerResult(result)
            true
        })

        // Keep on looping till new messages arrive
        if (looperIsNotPreparedInCurrentThread) {
            Looper.loop()
        }
    }

    //Create and send a new  message to looper
    fun sendMessage(messageToSend: String) {
        //Create and post a new message to handler
        handler!!.sendMessage(createMessage(messageToSend))
    }


    // Bundle Data in message object
    private fun createMessage(messageToSend: String): Message {
        val message = Message()
        val bundle = Bundle()
        bundle.putString(MainActivity.BUNDLE_KEY, messageToSend)
        message.data = bundle
        return message
    }

    companion object {
        var handler: Handler? = null // in Android Handler should be static or leaks might occur
        private val TAG = javaClass.simpleName

    }
}

Usage:

 class MainActivity : AppCompatActivity() {

    private var looperThread: LooperThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // start looper thread
        startLooperThread()

        // Send messages to Looper Thread
        sendMessage.setOnClickListener {

            // send random messages to looper thread
            val messageToSend = "" + Math.random()

            // post message
            looperThread!!.sendMessage(messageToSend)

        }   
    }

    override fun onResume() {
        super.onResume()

        //Register to Server Service callback
        val filterServer = IntentFilter(ServerService.ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(serverReceiver, filterServer)

    }

    override fun onPause() {
        super.onPause()

        //Stop Server service callbacks
     LocalBroadcastManager.getInstance(this).unregisterReceiver(serverReceiver)
    }


    // Define the callback for what to do when data is received
    private val serverReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val resultCode = intent.getIntExtra(ServerService.RESULT_CODE, Activity.RESULT_CANCELED)
            if (resultCode == Activity.RESULT_OK) {
                val resultValue = intent.getStringExtra(ServerService.RESULT_VALUE)
                Log.e(MainActivity.TAG, "Server result : $resultValue")

                serverOutput.text =
                        (serverOutput.text.toString()
                                + "\n"
                                + "Received : " + resultValue)

                serverScrollView.post( { serverScrollView.fullScroll(View.FOCUS_DOWN) })
            }
        }
    }

    private fun startLooperThread() {

        // create and start a new LooperThread
        looperThread = LooperThread()
        looperThread!!.name = "Main Looper Thread"
        looperThread!!.start()

    }

    companion object {
        val BUNDLE_KEY = "handlerMsgBundle"
        private val TAG = javaClass.simpleName
    }
}

Can we use Async task or Intent Services instead?

  • Async tasks are designed to perform a short operation in background and give progres & results on UI thread. Async tasks have limits like you cant create more than 128 Async tasks and ThreadPoolExecutor will allow only upto 5 Async tasks.

  • IntentServices are also designed to do background task for a little longer duration and you can use LocalBroadcast to communicate with Activity. But services get destroyed after task execution. If you want to keep it running for a long time than you need to do hecks like while(true){...}.

Other meaningful use cases for Looper Thread:

  • Used for 2 way socket communication where server keep on listening to Client socket and write back acknowledgment

  • Bitmap processing in background. Pass the image url to Looper thread and it will apply filter effects and store it in tempe rory location and then broadcast temp path of image.

Postgresql GROUP_CONCAT equivalent?

Try like this:

select field1, array_to_string(array_agg(field2), ',')
from table1
group by field1;

How to use and style new AlertDialog from appCompat 22.1 and above

    <item name="editTextColor">@color/white</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">@color/gray</item>
    <item name="android:textColorPrimary">@color/gray</item>
    <item name="colorControlNormal">@color/gray</item>
    <item name="colorControlActivated">@color/white</item>
    <item name="colorControlHighlight">#30FFFFFF</item>

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

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

On iOS with Safari they expire whenever you switch apps!

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

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

How to create number input field in Flutter?

You can specify the number as keyboardType for the TextField using:

keyboardType: TextInputType.number

Check my main.dart file

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      home: new HomePage(),
      theme: new ThemeData(primarySwatch: Colors.blue),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      body: new Container(
          padding: const EdgeInsets.all(40.0),
          child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new TextField(
            decoration: new InputDecoration(labelText: "Enter your number"),
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
          ),
        ],
      )),
    );
  }
}

enter image description here

Get Specific Columns Using “With()” Function in Laravel Eloquent

If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:

Post::with(['user' => fn ($query) => $query->select('id','username')])->get();

Reading and displaying data from a .txt file

If your file is strictly text, I prefer to use the java.util.Scanner class.

You can create a Scanner out of a file by:

Scanner fileIn = new Scanner(new File(thePathToYourFile));

Then, you can read text from the file using the methods:

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file

And, you can check if there is any more text left with:

fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file

Once you have read the text, and saved it into a String, you can print the string to the command line with:

System.out.print(aString);
System.out.println(aString);

The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

How to update a value in a json file and save it through node.js

addition to the previous answer add file path directory for the write operation

 fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}

OS detecting makefile

There are many good answers here already, but I wanted to share a more complete example that both:

  • doesn't assume uname exists on Windows
  • also detects the processor

The CCFLAGS defined here aren't necessarily recommended or ideal; they're just what the project to which I was adding OS/CPU auto-detection happened to be using.

ifeq ($(OS),Windows_NT)
    CCFLAGS += -D WIN32
    ifeq ($(PROCESSOR_ARCHITEW6432),AMD64)
        CCFLAGS += -D AMD64
    else
        ifeq ($(PROCESSOR_ARCHITECTURE),AMD64)
            CCFLAGS += -D AMD64
        endif
        ifeq ($(PROCESSOR_ARCHITECTURE),x86)
            CCFLAGS += -D IA32
        endif
    endif
else
    UNAME_S := $(shell uname -s)
    ifeq ($(UNAME_S),Linux)
        CCFLAGS += -D LINUX
    endif
    ifeq ($(UNAME_S),Darwin)
        CCFLAGS += -D OSX
    endif
    UNAME_P := $(shell uname -p)
    ifeq ($(UNAME_P),x86_64)
        CCFLAGS += -D AMD64
    endif
    ifneq ($(filter %86,$(UNAME_P)),)
        CCFLAGS += -D IA32
    endif
    ifneq ($(filter arm%,$(UNAME_P)),)
        CCFLAGS += -D ARM
    endif
endif

React native ERROR Packager can't listen on port 8081

This might be because of McAfee using that port. Doing simple lsof -i 8081 may not show the application and you may have to sudo it.

Do sudo lsof -i 8081 and if this command gives an output you can kill it by using sudo launchctl remove com.mcafee.agent.macmn. After this start packager again.

Could not load file or assembly ... The parameter is incorrect

Sometimes you, also, need to clean this folder: C:\Windows\Temp\Temporary ASP.NET

Makefiles with source files in different directories

I suggest to use autotools:

//## Place generated object files (.o) into the same directory as their source files, in order to avoid collisions when non-recursive make is used.

AUTOMAKE_OPTIONS = subdir-objects

just including it in Makefile.am with the other quite simple stuff.

Here is the tutorial.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

How to use Python's pip to download and keep the zipped files for a package?

Use pip download <package1 package2 package n> to download all the packages including dependencies

Use pip install --no-index --find-links . <package1 package2 package n> to install all the packages including dependencies. It gets all the files from CWD. It will not download anything

Changing the width of Bootstrap popover

On Bootstrap 4, you can easily review the template option, by overriding the max-width :

$('#myButton').popover({
    placement: 'bottom',
    html: true,
    trigger: 'click',
    template: '<div class="popover" style="max-width: 500px;" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
});

This is a good solution if you have several popovers on page.

How to scroll up or down the page to an anchor using jQuery?

$(function() {
    $('a#top').click(function() {
        $('html,body').animate({'scrollTop' : 0},1000);
    });
});

Test it here:

http://jsbin.com/ucati4

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

Convert all data frame character columns to factors

As @Raf Z commented on this question, dplyr now has mutate_if. Super useful, simple and readable.

> str(df)
'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

> df <- df %>% mutate_if(is.character,as.factor)

> str(df)
'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
 $ E: Factor w/ 5 levels "A a","B b","C c",..: 1 2 3 4 5

Better way to sum a property value in an array

I was already using jquery. But I think its intuitive enough to just have:

var total_amount = 0; 
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });

This is basically just a short-hand version of @akhouri's answer.

Running Selenium WebDriver python bindings in chrome

For Linux

  1. Check you have installed latest version of chrome brwoser-> chromium-browser -version

  2. If not, install latest version of chrome sudo apt-get install chromium-browser

  3. get appropriate version of chrome driver from here

  4. Unzip the chromedriver.zip

  5. Move the file to /usr/bin directory sudo mv chromedriver /usr/bin

  6. Goto /usr/bin directory cd /usr/bin

  7. Now, you would need to run something like sudo chmod a+x chromedriver to mark it executable.

  8. finally you can execute the code.

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.google.com")
    print driver.page_source.encode('utf-8')
    driver.quit()
    

What's the difference between ng-model and ng-bind

We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>

Get the year from specified date php

$Y_date = split("-","2068-06-15");
$year = $Y_date[0];

You can use explode also

Find document with array that contains a specific value

In case you need to find documents which contain NULL elements inside an array of sub-documents, I've found this query which works pretty well:

db.collection.find({"keyWithArray":{$elemMatch:{"$in":[null], "$exists":true}}})

This query is taken from this post: MongoDb query array with null values

It was a great find and it works much better than my own initial and wrong version (which turned out to work fine only for arrays with one element):

.find({
    'MyArrayOfSubDocuments': { $not: { $size: 0 } },
    'MyArrayOfSubDocuments._id': { $exists: false }
})

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

this happened again around last quarter of 2017 . greasemonkey firing too late . after domcontentloaded event already been fired.

what to do:

  • i used @run-at document-start instead of document-end
  • updated firefox to 57.

from : https://github.com/greasemonkey/greasemonkey/issues/2769

Even as a (private) script writer I'm confused why my script isn't working.

The most likely problem is that the 'DOMContentLoaded' event is fired before the script is run. Now before you come back and say @run-at document-start is set, that directive isn't fully supported at the moment. Due to the very asynchronous nature of WebExtensions there's little guarantee on when something will be executed. When FF59 rolls around we'll have #2663 which will help. It'll actually help a lot of things, debugging too.

HTML button onclick event

This example will help you:

<form>
    <input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>

You can open next page on same page by:

<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">

Stop setInterval call in JavaScript

In nodeJS you can you use the "this" special keyword within the setInterval function.

You can use this this keyword to clearInterval, and here is an example:

setInterval(
    function clear() {
            clearInterval(this) 
       return clear;
    }()
, 1000)

When you print the value of this special keyword within the function you outpout a Timeout object Timeout {...}

How should a model be structured in MVC?

More oftenly most of the applications will have data,display and processing part and we just put all those in the letters M,V and C.

Model(M)-->Has the attributes that holds state of application and it dont know any thing about V and C.

View(V)-->Has displaying format for the application and and only knows about how-to-digest model on it and does not bother about C.

Controller(C)---->Has processing part of application and acts as wiring between M and V and it depends on both M,V unlike M and V.

Altogether there is separation of concern between each. In future any change or enhancements can be added very easily.

Passing parameter via url to sql server reporting service

I've just solved this problem myself. I found the solution on MSDN: http://msdn.microsoft.com/en-us/library/ms155391.aspx.

The format basically is

http://<server>/reportserver?/<path>/<report>&rs:Command=Render&<parameter>=<value>

How to handle query parameters in angular 2

(For Childs Route Only such as /hello-world)

In the case you would like to make this kind of call :

/hello-world?foo=bar&fruit=banana

Angular2 doesn't use ? nor & but ; instead. So the correct URL should be :

/hello-world;foo=bar;fruit=banana

And to get those data :

import { Router, ActivatedRoute, Params } from '@angular/router';

private foo: string;
private fruit: string;

constructor(
  private route: ActivatedRoute,
  private router: Router
  ) {}

ngOnInit() {
  this.route.params.forEach((params: Params) => {
      this.foo = params['foo'];
      this.fruit = params['fruit'];
  });
  console.log(this.foo, this.fruit); // you should get your parameters here
}

Source : https://angular.io/docs/ts/latest/guide/router.html

Eclipse: Java was started but returned error code=13

Like Vito mentions, this error occurs after Java updates as the path:

C:\ProgramData\Oracle\Java\javapath

is added to the Path environment variable, causing Eclipse to run using the wrong java version.

To fix the problem:

1) Right-click on Computer and choose Properties.

2) Click Advanced system settings

3) Click Environment Variables...

4) Find the Path variable in the System variables section.

5) Choose it and click Edit...

6) Find and delete the above mentioned path.

This fixed it for me. I should mention that I already have the path:

c:\Program Files\Java\jdk1.7.0_21\bin

in the Path variable, but the new path was added to the beginning of the Path variable and therefore resolution would use that path first.

Jquery, Clear / Empty all contents of tbody element?

Example for Remove table header or table body with jquery

_x000D_
_x000D_
function removeTableHeader(){_x000D_
  $('#myTableId thead').empty();_x000D_
}_x000D_
_x000D_
function removeTableBody(){_x000D_
    $('#myTableId tbody').empty();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id='myTableId'  border="1">_x000D_
  <thead>_x000D_
    <th>1st heading</th>_x000D_
    <th>2nd heading</th>_x000D_
    <th>3rd heading</th>_x000D_
  </thead>  _x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br/>_x000D_
<form>_x000D_
  <input type='button' value='Remove Table Header' onclick='removeTableHeader()'/>_x000D_
  <input type='button' value='Remove Table Body' onclick='removeTableBody()'/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Something better than .NET Reflector?

Also take a look at ILSpy by SharpDevelop. It's in early stages of development and they just made a release on the 24th of February. That in itself works pretty good for me. From their website:

ILSpy is the open-source .NET assembly browser and decompiler.

Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.

Update: JetBrains has released dotPeek, its free .NET decompiler.

Update 2: Telerik also has a free decompiler: JustDecompile.

How does the vim "write with sudo" trick work?

:w - Write a file.

!sudo - Call shell sudo command.

tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):

tutorial link

Regular expression to match numbers with or without commas and decimals in text

(,*[\d]+,*[\d]*)+

This would match any small or large number as following with or without comma

1
100
1,262
1,56,262
10,78,999
12,34,56,789

or

1
100
1262
156262
1078999
123456789

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

How do I find if a string starts with another string in Ruby?

Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:

irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
=> 12.477248
irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
=> 9.593959
irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
=> 9.086909
irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
=> 6.973697

So it looks like start_with? ist the fastest of the bunch.

Updated results with Ruby 2.2.2p95 and a newer machine:

require 'benchmark'
Benchmark.bm do |x|
  x.report('regex[]')    { 10000000.times { "foobar"[/\Afoo/] }}
  x.report('regex')      { 10000000.times { "foobar" =~ /\Afoo/ }}
  x.report('[]')         { 10000000.times { "foobar"["foo"] }}
  x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
end

            user       system     total       real
regex[]     4.020000   0.000000   4.020000 (  4.024469)
regex       3.160000   0.000000   3.160000 (  3.159543)
[]          2.930000   0.000000   2.930000 (  2.931889)
start_with  2.010000   0.000000   2.010000 (  2.008162)

Creating a div element in jQuery

alternatively to append() you can also use appendTo() which has a different syntax:

$("#foo").append("<div>hello world</div>");
$("<div>hello world</div>").appendTo("#foo");    

What does OpenCV's cvWaitKey( ) function do?

Note for anybody who may have had problems with the cvWaitKey( ) function. If you are finding that cvWaitKey(x) is not waiting at all, make sure you actually have a window open (i.e. cvNamedWindow(...)). Put the cvNamedWindow(...) declaration BEFORE any cvWaitKey() function calls.

Valid characters in a Java class name

As already stated by Jason Cohen, the Java Language Specification defines what a legal identifier is in section 3.8:

"An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. [...] A 'Java letter' is a character for which the method Character.isJavaIdentifierStart(int) returns true. A 'Java letter-or-digit' is a character for which the method Character.isJavaIdentifierPart(int) returns true."

This hopefully answers your second question. Regarding your first question; I've been taught both by teachers and (as far as I can remember) Java compilers that a Java class name should be an identifier that begins with a capital letter A-Z, but I can't find any reliable source on this. When trying it out with OpenJDK there are no warnings when beginning class names with lower-case letters or even a $-sign. When using a $-sign, you do have to escape it if you compile from a bash shell, however.

What is object slicing?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

class Base { int x, y; };

class Derived : public Base { int z, w; };

int main() 
{
    Derived d;
    Base b = d; // Object Slicing,  z and w of d are sliced off
}

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

href="javascript:" vs. href="javascript:void(0)"

you could make them all #'s.

You would then need to add return false; to the end of any function that is called onclick of the anchor to not have the page jump up to the top.

Android webview slow

I was having this same issue and I had to work it out. I tried these solutions, but at the end the performance, at least for the scrolling didn't improve at all. So here the workaroud that I did perform and the explanation of why it did work for me.

If you had the chance to explore the drag events, just a little, by creating a "MiWebView" Class, overwriting the "onTouchEvent" method and at least printed the time in which every drag event occurs, you'll see that they are separated in time for (down to) 9ms away. That is a very short time in between events.

Take a look at the WebView Source Code, and just see the onTouchEvent function. It is just impossible for it to be handled by the processor in less than 9ms (Keep on dreaming!!!). That's why you constantly see the "Miss a drag as we are waiting for WebCore's response for touch down." message. The code just can't be handled on time.

How to fix it? First, you can not re-write the onTouchEvent code to improve it, it is just too much. But, you can "mock it" in order to limit the event rate for dragging movements let's say to 40ms or 50ms. (this depends on the processor).

All touch events go like this: ACTION_DOWN -> ACTION_MOVE......ACTION_MOVE -> ACTION_UP. So we need to keep the DOWN and UP movements and filter the MOVE rate (these are the bad guys).

And here is a way to do it (you can add more event types like 2 fingers touch, all I'm interested here is the single finger scrolling).

import android.content.Context;
import android.view.MotionEvent;
import android.webkit.WebView;


public class MyWebView extends WebView{

    public MyWebView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    private long lastMoveEventTime = -1;
    private int eventTimeInterval = 40;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        long eventTime = ev.getEventTime();
        int action = ev.getAction();

        switch (action){
            case MotionEvent.ACTION_MOVE: {
                if ((eventTime - lastMoveEventTime) > eventTimeInterval){
                    lastMoveEventTime = eventTime;
                    return super.onTouchEvent(ev);
                }
                break;
            }
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP: {
                return super.onTouchEvent(ev);
            }
        }
        return true;
    }
}

Of course Use this class instead of WebView and you'll see the difference when scrolling.

This is just an approach to a solution, yet still not fully implemented for all lag cases due to screen touching when using WebView. However it is the best solution I found, at least for my specific needs.

How to determine if binary tree is balanced?

Balance is a truly subtle property; you think you know what it is, but it's so easy to get wrong. In particular, even Eric Lippert's (good) answer is off. That's because the notion of height is not enough. You need to have the concept of minimum and maximum heights of a tree (where the minimum height is the least number of steps from the root to a leaf, and the maximum is... well, you get the picture). Given that, we can define balance to be:

A tree where the maximum height of any branch is no more than one more than the minimum height of any branch.

(This actually implies that the branches are themselves balanced; you can pick the same branch for both maximum and minimum.)

All you need to do to verify this property is a simple tree traversal keeping track of the current depth. The first time you backtrack, that gives you a baseline depth. Each time after that when you backtrack, you compare the new depth against the baseline

  • if it's equal to the baseline, then you just continue
  • if it is more than one different, the tree isn't balanced
  • if it is one off, then you now know the range for balance, and all subsequent depths (when you're about to backtrack) must be either the first or the second value.

In code:

class Tree {
    Tree left, right;
    static interface Observer {
        public void before();
        public void after();
        public boolean end();
    }
    static boolean traverse(Tree t, Observer o) {
        if (t == null) {
            return o.end();
        } else {
            o.before();
            try {
                if (traverse(left, o))
                    return traverse(right, o);
                return false;
            } finally {
                o.after();
            }
        }
    }
    boolean balanced() {
        final Integer[] heights = new Integer[2];
        return traverse(this, new Observer() {
            int h;
            public void before() { h++; }
            public void after() { h--; }
            public boolean end() {
                if (heights[0] == null) {
                    heights[0] = h;
                } else if (Math.abs(heights[0] - h) > 1) {
                    return false;
                } else if (heights[0] != h) {
                    if (heights[1] == null) {
                        heights[1] = h;
                    } else if (heights[1] != h) {
                        return false;
                    }
                }
                return true;
            }
        });
    }
}

I suppose you could do this without using the Observer pattern, but I find it easier to reason this way.


[EDIT]: Why you can't just take the height of each side. Consider this tree:

        /\
       /  \
      /    \
     /      \_____
    /\      /     \_
   /  \    /      / \
  /\   C  /\     /   \
 /  \    /  \   /\   /\
A    B  D    E F  G H  J

OK, a bit messy, but each side of the root is balanced: C is depth 2, A, B, D, E are depth 3, and F, G, H, J are depth 4. The height of the left branch is 2 (remember the height decreases as you traverse the branch), the height of the right branch is 3. Yet the overall tree is not balanced as there is a difference in height of 2 between C and F. You need a minimax specification (though the actual algorithm can be less complex as there should be only two permitted heights).

What's a good hex editor/viewer for the Mac?

  1. Open file with Xcode and press Command + Shift + J
  2. Right click file name in left pane
  3. Open as -> Hex

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Android update activity UI from service

Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.

I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:

class MyService extends Service {
    MyFragment mMyFragment = null;
    MyFragment mMyOtherFragment = null;

    private void networkLoop() {
        ...

        //received new data for list.
        if(myFragment != null)
            myFragment.updateList();
        }

        ...

        //received new data for textView
        if(myFragment !=null)
            myFragment.updateText();

        ...

        //received new data for textView
        if(myOtherFragment !=null)
            myOtherFragment.updateSomething();

        ...
    }
}


class MyFragment extends Fragment {

    public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=null;
    }

    public void updateList() {
        runOnUiThread(new Runnable() {
            public void run() {
                //Update the list.
            }
        });
    }

    public void updateText() {
       //as above
    }
}

class MyOtherFragment extends Fragment {
             public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=null;
    }

    public void updateSomething() {//etc... }
}

I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.

Copy an entire worksheet to a new worksheet in Excel 2010

'Make the excel file that runs the software the active workbook
ThisWorkbook.Activate

'The first sheet used as a temporary place to hold the data 
ThisWorkbook.Worksheets(1).Cells.Copy

'Create a new Excel workbook
Dim NewCaseFile As Workbook
Dim strFileName As String

Set NewCaseFile = Workbooks.Add
With NewCaseFile
    Sheets(1).Select
    Cells(1, 1).Select
End With

ActiveSheet.Paste

PyCharm shows unresolved references error for valid code

Worked for me with much simplier action:


File > Settings > Project > Project Interpreter 
> Select "No interpreter" in the "Project interpreter" list 
> Apply > Set your python interpreter again > Click Apply

Profit - Pycharm is updating skeletons and everything is fine.

Javascript Src Path

If you have

<base href="/" />

It's will not load file right. Just delete it.

How to fix SSL certificate error when running Npm on Windows?

The problem lies on your proxy. Because the location provider of your install package creates its own certificate and does not buy a verified one from an accepted authority, your proxy does not allow access to the targeted host. I assume that you bypass the proxy when using the Chrome Browser. So there is no checking.

There are some solutions to this problem. But all imply that you trust the package provider.

Possible solutions:

  1. As mentioned in other answers you can make an http:// access which may bypass your proxy. That's a bit dangerous, because the man in the middle can inject malware into you downloads.
  2. The wget suggests you to use a flag --no-check-certificate. This will add a proxy directive to your request. The proxy, if it understands the directive, does not check if the servers certificate is verified by an authority and passes the request. Perhaps there is a config with npm that does the same as the wget flag.
  3. You configure your proxy to accept CA npm. I don't know your proxy, so I can't give you a hint.

Send data from activity to fragment in Android

I ran into a similar issue while using the latest Navigation architecture component. Tried out all the above-mentioned code with passing a bundle from my calling activity to Fragment.

The best solution, following the latest development trends in Android, is by using View Model (part of Android Jetpack).

Create and Initialize a ViewModel class in the parent Activity, Please note that this ViewModel has to be shared between the activity and fragment.

Now, Inside the onViewCreated() of the fragment, Initialize the Same ViewModel and setup Observers to listen to the ViewModel fields.

Here is a helpful, in-depth tutorial if you need.

https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c

Breaking to a new line with inline-block?

If you're OK with not using <p>s (only <div>s and <span>s), this solution might even allow you to align your inline-blocks center or right, if you want to (or just keep them left, the way you originally asked for). While the solution might still work with <p>s, I don't think the resulting HTML code would be quite correct, but it's up to you anyways.

The trick is to wrap each one of your <span>s with a corresponding <div>. This way we're taking advantage of the line break caused by the <div>'s display: block (default), while still keeping the visual green box tight to the limits of the text (with your display: inline-block declaration).

_x000D_
_x000D_
.text span {_x000D_
   background:rgba(165, 220, 79, 0.8);_x000D_
   display:inline-block;_x000D_
   padding:7px 10px;_x000D_
   color:white;_x000D_
}_x000D_
.large {  font-size:80px }
_x000D_
<div class="text">_x000D_
  <div><span class="medium">We</span></div>_x000D_
  <div><span class="large">build</span></div>_x000D_
  <div><span class="medium">the</span></div>_x000D_
  <div><span class="large">Internet</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to access the correct `this` inside a callback?

You Should know about "this" Keyword.

As per my view you can implement "this" in three ways (Self/Arrow function/Bind Method)

A function's this keyword behaves a little differently in JavaScript compared to other languages.

It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called.

It can't be set by assignment during execution, and it may be different each time the function is called.

ES5 introduced the bind() method to set the value of a function's this regardless of how it's called,

and ES2015 introduced arrow functions which don't provide their own this binding (it retains this value of the enclosing lexical context).

Method1: Self - Self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

function MyConstructor(data, transport) {
    this.data = data;
    var self = this;
    transport.on('data', function () {
        alert(self.data);
    });
}

Method2: Arrow function - An arrow function expression is a syntactically compact alternative to a regular function expression,

although without its own bindings to the this, arguments, super, or new.target keywords.

Arrow function expressions are ill-suited as methods, and they cannot be used as constructors.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data',()=> {
        alert(this.data);
    });
}

Method3:Bind- The bind() method creates a new function that,

when called, has its this keyword set to the provided value,

with a given sequence of arguments preceding any provided when the new function is called.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

  function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data',(function() {
        alert(this.data);
    }).bind(this);

How to install Python packages from the tar.gz file without using pip install

Install it by running

python setup.py install

Better yet, you can download from github. Install git via apt-get install git and then follow this steps:

git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install

Regular Expression Match to test for a valid year

/^\d{4}$/ This will check if a string consists of only 4 numbers. In this scenario, to input a year 989, you can give 0989 instead.

ASP.Net MVC: Calling a method from a view

Building on Amine's answer, create a helper like:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString CurrencyFormat(this HtmlHelper helper, string value)
    {
        var result = string.Format("{0:C2}", value);
        return new MvcHtmlString(result);
    }
}

in your view: use @Html.CurrencyFormat(model.value)

If you are doing simple formating like Standard Numeric Formats, then simple use string.Format() in your view like in the helper example above:

@string.Format("{0:C2}", model.value)

Play infinitely looping video on-load in HTML5

For iPhone it works if you add also playsinline so:

<video width="320" height="240" autoplay loop muted playsinline>
  <source src="movie.mp4" type="video/mp4" />
</video>

"No backupset selected to be restored" SQL Server 2012

I got the same error message even though I backup and restore on the same single machine.

The issue was from here: when backup, i had 2 item in the destination box.

So the fix would be: make sure only 1 item in the 'destination' box. Remove all the others if there are.

Preloading @font-face fonts?

This answer is no longer up to date

Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815


Deprecated answer

I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Learning Ruby on Rails

There is a site called Softies on Rails that is written by a couple of ex-.NET developers that may be of some use. They have a book called Rails for .NET Developers coming out in the next few months...

I started out on a Windows box using the RadRails plugin for Eclipse and the RubyWeaver extension for Dreamweaver (back during the 1.x days of Rails). Since then I have moved to a Mac running TextMate and haven't thought of going back.

As for books, I started with The Ruby Way and Agile Web Development with Rails. It definately helps to build a background in Ruby as you start to make your way into Rails development.

Definately watch the Railscast series by Ryan Bates.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I have encountered this error on "an empty branch" on my local gitlab server. Some people mentioned that "you can not push for the first time on an empty branch". I tried to create a simple README file on the gitlab via my browser. Then everything fixed amazingly and the problem sorted out!! I mention that I was the master and the branch was not protected.

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

Alphabet range in Python

This is the easiest way I can figure out:

#!/usr/bin/python3
for i in range(97, 123):
    print("{:c}".format(i), end='')

So, 97 to 122 are the ASCII number equivalent to 'a' to and 'z'. Notice the lowercase and the need to put 123, since it will not be included).

In print function make sure to set the {:c} (character) format, and, in this case, we want it to print it all together not even letting a new line at the end, so end=''would do the job.

The result is this: abcdefghijklmnopqrstuvwxyz

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

Start service in Android

I like to make it more dynamic

Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }

do not forget the Manifest

<service android:enabled="true" android:name=".MyService.class" />

Using Tkinter in python to edit the title bar

Easy method:

root = Tk()
root.title('Hello World')

How to convert string to integer in PowerShell

Use:

$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory

What's the difference between Unicode and UTF-8?

There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.

ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).

At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).

Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.

By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).

Text blinking jQuery

Try this :

setInterval( function() { $(".me").fadeOut(500).fadeIn(500) } , 500);

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to print time in format: 2009-08-10 18:17:54.811

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

json_encode() escaping forward slashes

I had to encounter a situation as such, and simply, the

str_replace("\/","/",$variable)

did work for me.

Store an array in HashMap

You can store objects in a HashMap.

HashMap<String, Object> map = new HashMap<String, Object>();

You'll just need to cast it back out correctly.

Guid is all 0's (zeros)?

Lessons to learn from this:

1) Guid is a value type, not a reference type.

2) Calling the default constructor new S() on any value type always gives you back the all-zero form of that value type, whatever it is. It is logically the same as default(S).

How to create a file on Android Internal Storage?

You should use ContextWrapper like this:

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

As always, refer to documentation, ContextWrapper has a lot to offer.

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

react-router go back a page how do you configure history?

According to https://reacttraining.com/react-router/web/api/history

For "react-router-dom": "^5.1.2",,

const { history } = this.props;
<Button onClick={history.goBack}>
  Back
</Button>
YourComponent.propTypes = {
  history: PropTypes.shape({
    goBack: PropTypes.func.isRequired,
  }).isRequired,
};

How to load URL in UIWebView in Swift?

in swift 5

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
   var webView: WKWebView!
   override func viewDidLoad() {
      super.viewDidLoad()
      let myURL = URL(string:"https://www.apple.com")
      let myRequest = URLRequest(url: myURL!)
      webView.load(myRequest)
   }
   override func loadView() {
      let webConfiguration = WKWebViewConfiguration()
      webView = WKWebView(frame: .zero, configuration: webConfiguration)
      webView.uiDelegate = self
      view = webView
   }
}

android pick images from gallery

You can use this method to pick image from gallery. Only images will be displayed.

public void pickImage() {
    Intent intent = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    intent.setType("image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("scale", true);
    intent.putExtra("outputX", 256);
    intent.putExtra("outputY", 256);
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 1);
}

and override onActivityResult as

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 1) {
            final Bundle extras = data.getExtras();
            if (extras != null) {
                //Get image
                Bitmap newProfilePic = extras.getParcelable("data");
            }
        }
    }

Javascript - Track mouse position

The mouse's position is reported on the event object received by a handler for the mousemove event, which you can attach to the window (the event bubbles):

(function() {
    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var eventDoc, doc, body;

        event = event || window.event; // IE-ism

        // If pageX/Y aren't available and clientX/Y are,
        // calculate pageX/Y - logic taken from jQuery.
        // (This is to support old IE)
        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        // Use event.pageX / event.pageY here
    }
})();

(Note that the body of that if will only run on old IE.)

Example of the above in action - it draws dots as you drag your mouse over the page. (Tested on IE8, IE11, Firefox 30, Chrome 38.)

If you really need a timer-based solution, you combine this with some state variables:

(function() {
    var mousePos;

    document.onmousemove = handleMouseMove;
    setInterval(getMousePosition, 100); // setInterval repeats every X ms

    function handleMouseMove(event) {
        var dot, eventDoc, doc, body, pageX, pageY;

        event = event || window.event; // IE-ism

        // If pageX/Y aren't available and clientX/Y are,
        // calculate pageX/Y - logic taken from jQuery.
        // (This is to support old IE)
        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        mousePos = {
            x: event.pageX,
            y: event.pageY
        };
    }
    function getMousePosition() {
        var pos = mousePos;
        if (!pos) {
            // We haven't seen any movement yet
        }
        else {
            // Use pos.x and pos.y
        }
    }
})();

As far as I'm aware, you can't get the mouse position without having seen an event, something which this answer to another Stack Overflow question seems to confirm.

Side note: If you're going to do something every 100ms (10 times/second), try to keep the actual processing you do in that function very, very limited. That's a lot of work for the browser, particularly older Microsoft ones. Yes, on modern computers it doesn't seem like much, but there is a lot going on in browsers... So for example, you might keep track of the last position you processed and bail from the handler immediately if the position hasn't changed.

Spaces in URLs?

The information there is I think partially correct:

That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.

As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the + is defined, though %20 is standard.

How to affect other elements when one element is hovered

Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover state of the main element.

For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...

The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.

Here is an example:

_x000D_
_x000D_
#container {_x000D_
  width: 200px;_x000D_
  height: 30px;_x000D_
  border: 1px solid var(--c);_x000D_
  --c:red;_x000D_
}_x000D_
#container:hover {_x000D_
  --c:blue;_x000D_
}_x000D_
#container > div {_x000D_
  width: 30px;_x000D_
  height: 100%;_x000D_
  background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
  <div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why this can be better than using specific selector combined with hover?

I can provide at least 2 reasons that make this method a good one to consider:

  1. If we have many nested elements that share the same styles, this will avoid us complex selector to target all of them on hover. Using Custom properties, we simply change the value when hovering on the parent element.
  2. A custom property can be used to replace a value of any property and also a partial value of it. For example we can define a custom property for a color and we use it within a border, linear-gradient, background-color, box-shadow etc. This will avoid us reseting all these properties on hover.

Here is a more complex example:

_x000D_
_x000D_
.container {_x000D_
  --c:red;_x000D_
  width:400px;_x000D_
  display:flex;_x000D_
  border:1px solid var(--c);_x000D_
  justify-content:space-between;_x000D_
  padding:5px;_x000D_
  background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
  width:30%;_x000D_
  background:var(--c);_x000D_
  box-shadow:0px 0px 5px var(--c);_x000D_
  position:relative;_x000D_
}_x000D_
.box:before {_x000D_
  content:"A";_x000D_
  display:block;_x000D_
  width:15px;_x000D_
  margin:0 auto;_x000D_
  height:100%;_x000D_
  color:var(--c);_x000D_
  background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
  --c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

As we can see above, we only need one CSS declaration in order to change many properties of different elements.

Can I use a :before or :after pseudo-element on an input field?

try next:

_x000D_
_x000D_
label[for="userName"] {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
label[for="userName"]::after {_x000D_
  content: '[after]';_x000D_
  width: 22px;_x000D_
  height: 22px;_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  right: -30px;_x000D_
}
_x000D_
<label for="userName">_x000D_
 Name: _x000D_
 <input type="text" name="userName" id="userName">_x000D_
 </label>
_x000D_
_x000D_
_x000D_

Remove accents/diacritics in a string in JavaScript

I took the wiki answer and I translated it into typescript static class, for people that come from for example angular.

export class DiacriticsRemover {

  private static diacriticsMap: Map<string, string> = new Map<string, string>();

  private static defaultDiacriticsRemovalMap = [
    {
      base: 'A',
      letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F'
    },
    {
      base: 'AA',
      letters: '\uA732'
    },
    {
      base: 'AE',
      letters: '\u00C6\u01FC\u01E2'
    },
    {
      base: 'AO',
      letters: '\uA734'
    },
    {
      base: 'AU',
      letters: '\uA736'
    },
    {
      base: 'AV',
      letters: '\uA738\uA73A'
    },
    {
      base: 'AY',
      letters: '\uA73C'
    },
    {
      base: 'B',
      letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181'
    },
    {
      base: 'C',
      letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E'
    },
    {
      base: 'D',
      letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0'
    },
    {
      base: 'DZ',
      letters: '\u01F1\u01C4'
    },
    {
      base: 'Dz',
      letters: '\u01F2\u01C5'
    },
    {
      base: 'E',
      letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E'
    },
    {
      base: 'F',
      letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B'
    },
    {
      base: 'G',
      letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E'
    },
    {
      base: 'H',
      letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D'
    },
    {
      base: 'I',
      letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197'
    },
    {
      base: 'J',
      letters: '\u004A\u24BF\uFF2A\u0134\u0248'
    },
    {
      base: 'K',
      letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2'
    },
    {
      base: 'L',
      letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780'
    },
    {
      base: 'LJ',
      letters: '\u01C7'
    },
    {
      base: 'Lj',
      letters: '\u01C8'
    },
    {
      base: 'M',
      letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C'
    },
    {
      base: 'N',
      letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4'
    },
    {
      base: 'NJ',
      letters: '\u01CA'
    },
    {
      base: 'Nj',
      letters: '\u01CB'
    },
    {
      base: 'O',
      letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C'
    },
    {
      base: 'OI',
      letters: '\u01A2'
    },
    {
      base: 'OO',
      letters: '\uA74E'
    },
    {
      base: 'OU',
      letters: '\u0222'
    },
    {
      base: 'OE',
      letters: '\u008C\u0152'
    },
    {
      base: 'oe',
      letters: '\u009C\u0153'
    },
    {
      base: 'P',
      letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754'
    },
    {
      base: 'Q',
      letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A'
    },
    {
      base: 'R',
      letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782'
    },
    {
      base: 'S',
      letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784'
    },
    {
      base: 'T',
      letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786'
    },
    {
      base: 'TZ',
      letters: '\uA728'
    },
    {
      base: 'U',
      letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244'
    },
    {
      base: 'V',
      letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245'
    },
    {
      base: 'VY',
      letters: '\uA760'
    },
    {
      base: 'W',
      letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72'
    },
    {
      base: 'X',
      letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C'
    },
    {
      base: 'Y',
      letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE'
    },
    {
      base: 'Z',
      letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762'
    },
    {
      base: 'a',
      letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250'
    },
    {
      base: 'aa',
      letters: '\uA733'
    },
    {
      base: 'ae',
      letters: '\u00E6\u01FD\u01E3'
    },
    {
      base: 'ao',
      letters: '\uA735'
    },
    {
      base: 'au',
      letters: '\uA737'
    },
    {
      base: 'av',
      letters: '\uA739\uA73B'
    },
    {
      base: 'ay',
      letters: '\uA73D'
    },
    {
      base: 'b',
      letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253'
    },
    {
      base: 'c',
      letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184'
    },
    {
      base: 'd',
      letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A'
    },
    {
      base: 'dz',
      letters: '\u01F3\u01C6'
    },
    {
      base: 'e',
      letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD'
    },
    {
      base: 'f',
      letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C'
    },
    {
      base: 'g',
      letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F'
    },
    {
      base: 'h',
      letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265'
    },
    {
      base: 'hv',
      letters: '\u0195'
    },
    {
      base: 'i',
      letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131'
    },
    {
      base: 'j',
      letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249'
    },
    {
      base: 'k',
      letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3'
    },
    {
      base: 'l',
      letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747'
    },
    {
      base: 'lj',
      letters: '\u01C9'
    },
    {
      base: 'm',
      letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F'
    },
    {
      base: 'n',
      letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5'
    },
    {
      base: 'nj',
      letters: '\u01CC'
    },
    {
      base: 'o',
      letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275'
    },
    {
      base: 'oi',
      letters: '\u01A3'
    },
    {
      base: 'ou',
      letters: '\u0223'
    },
    {
      base: 'oo',
      letters: '\uA74F'
    },
    {
      base: 'p',
      letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755'
    },
    {
      base: 'q',
      letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759'
    },
    {
      base: 'r',
      letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783'
    },
    {
      base: 's',
      letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B'
    },
    {
      base: 't',
      letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787'
    },
    {
      base: 'tz',
      letters: '\uA729'
    },
    {
      base: 'u',
      letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289'
    },
    {
      base: 'v',
      letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C'
    },
    {
      base: 'vy',
      letters: '\uA761'
    },
    {
      base: 'w',
      letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73'
    },
    {
      base: 'x',
      letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D'
    },
    {
      base: 'y',
      letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF'
    },
    {
      base: 'z',
      letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763'
    }
  ];

  private static isSetUp = false;

  public static removeDiacritics(text: string): string {
    if (!this.isSetUp) {
      this.setUp();
    }

    return text.replace(/[^\u0000-\u007E]/g, (a: string) => this.diacriticsMap.get(a) || a);
  }

  private static setUp(): void {
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.defaultDiacriticsRemovalMap.length; i++) {
      const letters = this.defaultDiacriticsRemovalMap[i].letters;

      // tslint:disable-next-line:prefer-for-of
      for (let j = 0; j < letters.length; j++) {
        this.diacriticsMap.set(letters[j], this.defaultDiacriticsRemovalMap[i].base);
      }
    }
    this.isSetUp = true;
  }
}

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

How to get a view table query (code) in SQL Server 2008 Management Studio

Additionally, if you have restricted access to the database (IE: Can't use "Script Function as > CREATE To"), there is another option to get this query.

Find your View > right click > "Design".

This will give you the query you are looking for.

How to check if Location Services are enabled?

If no provider is enabled, "passive" is the best provider returned. See https://stackoverflow.com/a/4519414/621690

    public boolean isLocationServiceEnabled() {
        LocationManager lm = (LocationManager)
                this.getSystemService(Context.LOCATION_SERVICE);
        String provider = lm.getBestProvider(new Criteria(), true);
        return (StringUtils.isNotBlank(provider) &&
                !LocationManager.PASSIVE_PROVIDER.equals(provider));
    }

How do I escape double quotes in attributes in an XML String in T-SQL?

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

When do I need a fb:app_id or fb:admins?

I think the documentation is reasonably helpful!

If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.

So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.

If you do use og, then set type to: blog

Finally: fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.

I forgot the password I entered during postgres installation

  1. find the file pg_hba.conf - it may be located, for example in /etc/postgresql-9.1/pg_hba.conf.

    cd /etc/postgresql-9.1/

  2. Back it up

    cp pg_hba.conf pg_hba.conf-backup

  3. place the following line (as either the first uncommented line, or as the only one):

For all occurrence of below (local and host) , exepct replication section if you don't have any it has to be changed as follow ,no MD5 or Peer autehication should be present.

local  all   all   trust
  1. restart your PostgreSQL server (e.g., on Linux:)

    sudo /etc/init.d/postgresql restart

    If the service (daemon) doesn't start reporting in log file:

    local connections are not supported by this build

    you should change

    local all all trust

    to

    host all all 127.0.0.1/32 trust

  2. you can now connect as any user. Connect as the superuser postgres (note, the superuser name may be different in your installation. In some systems it is called pgsql, for example.)

    psql -U postgres

    or

    psql -h 127.0.0.1 -U postgres

    (note that with the first command you will not always be connected with local host)

  3. Reset password ('replace my_user_name with postgres since you are resetting postgres user)

    ALTER USER my_user_name with password 'my_secure_password';

  4. Restore the old pg_hba.conf as it is very dangerous to keep around

    cp pg_hba.conf-backup pg_hba.conf

  5. restart the server, in order to run with the safe pg_hba.conf

    sudo /etc/init.d/postgresql restart

Further Reading about that pg_hba file: http://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html

How to fix error Base table or view not found: 1146 Table laravel relationship table?

It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How do I kill all the processes in Mysql "show processlist"?

KILL ALL SELECT QUERIES

select concat('KILL ',id,';') 
from information_schema.processlist 
where user='root' 
  and INFO like 'SELECT%' into outfile '/tmp/a.txt'; 
source /tmp/a.txt;

jQuery - How to dynamically add a validation rule

As well as making sure that you have first called $("#myForm").validate();, make sure that your dynamic control has been added to the DOM before adding the validation rules.

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

How to coerce a list object to type 'double'

There are problems with some data. Consider:

as.double(as.character("2.e")) # This results in 2

Another solution:

get_numbers <- function(X) {
    X[toupper(X) != tolower(X)] <- NA
    return(as.double(as.character(X)))
}

Add new element to an existing object

Use this:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

Including JavaScript class definition from another file in Node.js

I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.

// MyClass

module.exports.Ninja = class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}
//Using MyClass in seprate File


const ninjaFw = require('./NinjaFw');

let ninja = new ninjaFw.Ninja();
ninja.test();

  • This is the method I am currently using. I like this syntax, becuase module.exports sits on the same line as the class declaration and that cleans the code up a little imo. The other way you can do it is like this:
//  Ninja Framework File


class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}


module.exports.Ninja = Ninja;

  • Two different syntax but, in the end, the same result. Just a matter of syntax anesthetics.

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

public static class DbEx {
    public static IEnumerable<T> SqlQueryPrm<T>(this System.Data.Entity.Database database, string sql, object parameters) {
        using (var tmp_cmd = database.Connection.CreateCommand()) {
            var dict = ToDictionary(parameters);
            int i = 0;
            var arr = new object[dict.Count];
            foreach (var one_kvp in dict) {
                var param = tmp_cmd.CreateParameter();
                param.ParameterName = one_kvp.Key;
                if (one_kvp.Value == null) {
                    param.Value = DBNull.Value;
                } else {
                    param.Value = one_kvp.Value;
                }
                arr[i] = param;
                i++;
            }
            return database.SqlQuery<T>(sql, arr);
        }
    }
    private static IDictionary<string, object> ToDictionary(object data) {
        var attr = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;
        var dict = new Dictionary<string, object>();
        foreach (var property in data.GetType().GetProperties(attr)) {
            if (property.CanRead) {
                dict.Add(property.Name, property.GetValue(data, null));
            }
        }
        return dict;
    }
}

Usage:

var names = db.Database.SqlQueryPrm<string>("select name from position_category where id_key=@id_key", new { id_key = "mgr" }).ToList();

How do I convert csv file to rdd

As of Spark 2.0, CSV can be read directly into a DataFrame.

If the data file does not have a header row, then it would be:

val df = spark.read.csv("file://path/to/data.csv")

That will load the data, but give each column generic names like _c0, _c1, etc.

If there are headers then adding .option("header", "true") will use the first row to define the columns in the DataFrame:

val df = spark.read
  .option("header", "true")
  .csv("file://path/to/data.csv")

For a concrete example, let's say you have a file with the contents:

user,topic,hits
om,scala,120
daniel,spark,80
3754978,spark,1

Then the following will get the total hits grouped by topic:

import org.apache.spark.sql.functions._
import spark.implicits._

val rawData = spark.read
  .option("header", "true")
  .csv("file://path/to/data.csv")

// specifies the query, but does not execute it
val grouped = rawData.groupBy($"topic").agg(sum($"hits))

// runs the query, pulling the data to the master node
// can fail if the amount of data is too much to fit 
// into the master node's memory!
val collected = grouped.collect

// runs the query, writing the result back out
// in this case, changing format to Parquet since that can
//   be nicer to work with in Spark
grouped.write.parquet("hdfs://some/output/directory/")

// runs the query, writing the result back out
// in this case, in CSV format with a header and 
// coalesced to a single file.  This is easier for human 
// consumption but usually much slower.
grouped.coalesce(1)
  .write
  .option("header", "true")
  .csv("hdfs://some/output/directory/")

Difference between a user and a schema in Oracle?

It's very simple.

If USER has OBJECTS
then call it SCHEMA
else
     call it USER
end if;

A user may be given access to schema objects owned by different Users.

How to get the path of a running JAR file?

The simplest solution is to pass the path as an argument when running the jar.

You can automate this with a shell script (.bat in Windows, .sh anywhere else):

java -jar my-jar.jar .

I used . to pass the current working directory.

UPDATE

You may want to stick the jar file in a sub-directory so users don't accidentally click it. Your code should also check to make sure that the command line arguments have been supplied, and provide a good error message if the arguments are missing.

How to print Unicode character in Python?

Replace '+' with '000'. For example, 'U+1F600' will become 'U0001F600' and prepend the Unicode code with "\" and print. Example:

>>> print("Learning : ", "\U0001F40D")
Learning :  
>>> 

Check this maybe it will help python unicode emoji

How to add constraints programmatically using Swift

Do you plan to have a squared UIView of width: 100 and Height: 100 centered inside the UIView of an UIViewController? If so, you may try one of the 6 following Auto Layout styles (Swift 5 / iOS 12.2):


1. Using NSLayoutConstraint initializer

override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
    let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
    let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
    let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
    view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
    let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
    let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
    let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
    NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
}

2. Using Visual Format Language

override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let views = ["view": view!, "newView": newView]
    let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=0)-[newView(100)]", options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views)
    let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=0)-[newView(100)]", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
    view.addConstraints(horizontalConstraints)
    view.addConstraints(verticalConstraints)
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let views = ["view": view!, "newView": newView]
    let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=0)-[newView(100)]", options: NSLayoutConstraint.FormatOptions.alignAllCenterY, metrics: nil, views: views)
    let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=0)-[newView(100)]", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
    NSLayoutConstraint.activate(horizontalConstraints)
    NSLayoutConstraint.activate(verticalConstraints)
}

3. Using a mix of NSLayoutConstraint initializer and Visual Format Language

override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let views = ["newView": newView]
    let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
    let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
    view.addConstraints(widthConstraints)
    view.addConstraints(heightConstraints)
    view.addConstraints([horizontalConstraint, verticalConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let views = ["newView": newView]
    let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
    let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
    NSLayoutConstraint.activate(widthConstraints)
    NSLayoutConstraint.activate(heightConstraints)
    NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = false
    let views = ["newView": newView]
    let widthConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    let heightConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[newView(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views)
    NSLayoutConstraint.activate(widthConstraints)
    NSLayoutConstraint.activate(heightConstraints)
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item: newView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true
}

4. Using UIView.AutoresizingMask

Note: Springs and Struts will be translated into corresponding auto layout constraints at runtime.

override func viewDidLoad() {
    let newView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)

    newView.translatesAutoresizingMaskIntoConstraints = true
    newView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
    newView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin]
}

5. Using NSLayoutAnchor

override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)
    
    newView.translatesAutoresizingMaskIntoConstraints = false
    let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
    let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
    let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100)
    let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100)
    view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)
    
    newView.translatesAutoresizingMaskIntoConstraints = false
    let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
    let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
    let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100)
    let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100)
    NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
override func viewDidLoad() {
    let newView = UIView()
    newView.backgroundColor = UIColor.red
    view.addSubview(newView)
    
    newView.translatesAutoresizingMaskIntoConstraints = false
    newView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    newView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    newView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}

6. Using intrinsicContentSize and NSLayoutAnchor

import UIKit

class CustomView: UIView {
    
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 100, height: 100)
    }
    
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        let newView = CustomView()
        newView.backgroundColor = UIColor.red
        view.addSubview(newView)
        
        newView.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
    }
    
}

Result:

enter image description here

Pure CSS multi-level drop-down menu

<div class="example" align="center">
    <div class="menuholder">
        <ul class="menu slide">
            <li><a href="index.php?id=1" class="blue">Home</a></li>
        <li><a href="index.php?id=14" class="blue">About Us</a></li>
            <li><a href="index.php?id=4" class="blue">Mens</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                        <dd><a href="index.php?id=22">Chinos</a></dd>
                        <dd><a href="index.php?id=23">Jeans</a></dd>
                        <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                        <dd><a href="index.php?id=25">Linen</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                        <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                        <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                        <dd><a href="index.php?id=28">Shorts</a></dd>
                        <dd><a href="index.php?id=18">Sportswear</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                        <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                        <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                        <dd><a href="index.php?id=30">Nightwear</a></dd>
                        <dd><a href="index.php?id=17">Socks</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=21">Underwear</a></dd>
                        <dd><a href="index.php?id=31">Swimwear</a></dd>
                    </dl>
                </div>
            </li>
            <!--menu-->
                        <li><a href="index.php?id=5" class="blue">Ladie's</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=33">Dresses</a></dd>
                          <dd><a href="index.php?id=34">Jeans</a></dd>
                          <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                          <dd><a href="index.php?id=38">Linen</a></dd>
                          <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                          <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                          <dd><a href="index.php?id=41">Nightwear</a></dd>
                    </dl>
                    <dl>
                     <dd><a href="index.php?id=42">Shorts</a></dd>
                          <dd><a href="index.php?id=43">Skirts</a></dd>
                          <dd><a href="index.php?id=44">Sportswear</a></dd>
                          <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                          <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=47">Thermals</a></dd>
                          <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                          <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                          <dd><a href="index.php?id=50">Socks</a></dd>
                    </dl>
                </div>
            </li><!--menu end-->
                        <!--menu-->
                        <li><a href="index.php?id=7" class="blue">Girls</a>
                <div class="subs">
                    <dl>
                            <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=52">Dresses</a></dd>
                          <dd><a href="index.php?id=53">Jeans</a></dd>
                          <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                    </dl>
                    <dl>
                                <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                              <dd><a href="index.php?id=57">Leggings</a></dd>
                              <dd><a href="index.php?id=58">Nightwear</a></dd>
                              <dd><a href="index.php?id=59">Shorts</a></dd>
                              <dd><a href="index.php?id=60">Skirts</a></dd>
                    </dl>
                    <dl>
                              <dd><a href="index.php?id=61">Swimwear</a></dd>
                              <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=64">Socks</a></dd>
                              <dd><a href="index.php?id=65">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
                            <!--menu-->
                        <li><a href="index.php?id=8" class="blue">Boys</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=67">Jeans</a></dd>
                          <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=70">Nightwear</a></dd>
                    </dl>
                    <dl>
                            <dd><a href="index.php?id=71">Shirts</a></dd>
                          <dd><a href="index.php?id=72">Shorts</a></dd>
                          <dd><a href="index.php?id=73">Sportswear</a></dd>
                          <dd><a href="index.php?id=74">Swimwear</a></dd>
                          <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                          <dd><a href="index.php?id=77">Socks</a></dd>
                          <dd><a href="index.php?id=78">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=9" class="blue">Toddlers</a>
                <div class="subs">
                    <dl>
                      <dd><a href="index.php?id=79">Newborn</a></dd>
                      <dd><a href="index.php?id=80">0-2 Years</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=10" class="blue">Accessories</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=81">Shoes</a></dd>
                          <dd><a href="index.php?id=82">Ties</a></dd>
                          <dd><a href="index.php?id=83">Caps</a></dd>
                          <dd><a href="index.php?id=84">Belts</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
        </ul>
        <div class="back"></div>
        <div class="shadow"></div>
    </div>
    <div style="clear:both"></div>
</div>

CSS 3 Coding- Copy and Paste

<style>

body{margin:0px;}
.example {
    width:980px;
    height:40px;
    margin:0px auto;
 position:absolute;
 margin-bottom:60px;
 top:95px;
}

.menuholder {
    float:left;
    font:normal bold 11px/35px verdana, sans-serif;
    overflow:hidden;
    position:relative;
}
.menuholder .shadow {
    -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    background:#888;
    box-shadow:0 0 20px rgba(0, 0, 0, 1);
    height:10px;
    left:5%;
    position:absolute;
    top:-9px;
    width:100%;
    z-index:100;
}
.menuholder .back {
    -moz-transition-duration:.4s;
    -o-transition-duration:.4s;
    -webkit-transition-duration:.4s;
    background-color:rgba(0, 0, 0, 0.88);
    height:0;
    width:980px; /*100%*/
}
.menuholder:hover div.back {
    height:280px;
}
ul.menu {
    display:block;
    float:left;
    list-style:none;
    margin:0;
    padding:0 125px;
    position:relative;
}
ul.menu li {
    float:left;
    margin:0 10px 0 0;
}
ul.menu li > a {
    -moz-border-radius:0 0 10px 10px;
    -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -moz-transition:all 0.3s ease-in-out;
    -o-border-radius:0 0 10px 10px;
    -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -o-transition:all 0.3s ease-in-out;
    -webkit-border-bottom-left-radius:10px;
    -webkit-border-bottom-right-radius:10px;
    -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -webkit-transition:all 0.3s ease-in-out;
    border-radius:0 0 10px 10px;
    box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    color:#eee;
    display:block;
    padding:0 10px;
    text-decoration:none;
    transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
    background:#a00;
}
ul.menu li a.orange {
    background:#da0;
}
ul.menu li a.yellow {
    background:#aa0;
}
ul.menu li a.green {
    background:#060;
}
ul.menu li a.blue {
    background:#073263;
}
ul.menu li a.violet {
    background:#682bc2;
}
.menu li div.subs {
    left:0;
    overflow:hidden;
    position:absolute;
    top:35px;
    width:0;
}
.menu li div.subs dl {
    -moz-transition-duration:.2s;
    -o-transition-duration:.2s;
    -webkit-transition-duration:.2s;
    float:left;
    margin:0 130px 0 0;
    overflow:hidden;
    padding:40px 0 5% 2%;
    width:0;
}
.menu dt {
    color:#fc0;
    font-family:arial, sans-serif;
    font-size:12px;
    font-weight:700;
    height:20px;
    line-height:20px;
    margin:0;
    padding:0 0 0 10px;
    white-space:nowrap;
}
.menu dd {
    margin:0;
    padding:0;
    text-align:left;
}
.menu dd a {
    background:transparent;
    color:#fff;
    font-size:12px;
    height:20px;
    line-height:20px;
    padding:0 0 0 10px;
    text-align:left;
    white-space:nowrap;
    width:80px;
}
.menu dd a:hover {
    color:#fc0;
}
.menu li:hover div.subs dl {
    -moz-transition-delay:0.2s;
    -o-transition-delay:0.2s;
    -webkit-transition-delay:0.2s;
    margin-right:2%;
    width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
    background:#aaa;
    color:#fff;
    padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
    background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
    background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
    background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
    background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
    background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
    width:100%;
}

Extract the maximum value within each group in a dataframe

Using sqldf and standard sql to get the maximum values grouped by another variable

https://cran.r-project.org/web/packages/sqldf/sqldf.pdf

library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")

or

Using the excellent Hmisc package for a groupby application of function (max) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

library(Hmisc)
summarize(df1$Value,df1$Gene,max)

How to use WinForms progress bar?

There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

First Heroku deploy failed `error code=H10`

My port was set to config.httpPort which resolves to 80. I fixed it by doing this:

const PORT = process.env.PORT || config.httpPort;

app.listen(PORT, ...)

Thanks a lot, it wasted me a lot of hours last night.

How to get first character of a string in SQL?

It is simple to achieve by the following

DECLARE @SomeString NVARCHAR(20) = 'This is some string'
DECLARE @Result NVARCHAR(20)

Either

SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result

@Result = his

or

SET @Result = LEFT(@SomeString, 6)
SELECT @Result

@Result = This i

Can scripts be inserted with innerHTML?

For anyone still trying to do this, no, you can't inject a script using innerHTML, but it is possible to load a string into a script tag using a Blob and URL.createObjectURL.

I've created an example that lets you run a string as a script and get the 'exports' of the script returned through a promise:

function loadScript(scriptContent, moduleId) {
    // create the script tag
    var scriptElement = document.createElement('SCRIPT');

    // create a promise which will resolve to the script's 'exports'
    // (i.e., the value returned by the script)
    var promise = new Promise(function(resolve) {
        scriptElement.onload = function() {
            var exports = window["__loadScript_exports_" + moduleId];
            delete window["__loadScript_exports_" + moduleId];
            resolve(exports);
        }
    });

    // wrap the script contents to expose exports through a special property
    // the promise will access the exports this way
    var wrappedScriptContent =
        "(function() { window['__loadScript_exports_" + moduleId + "'] = " + 
        scriptContent + "})()";

    // create a blob from the wrapped script content
    var scriptBlob = new Blob([wrappedScriptContent], {type: 'text/javascript'});

    // set the id attribute
    scriptElement.id = "__loadScript_module_" + moduleId;

    // set the src attribute to the blob's object url 
    // (this is the part that makes it work)
    scriptElement.src = URL.createObjectURL(scriptBlob);

    // append the script element
    document.body.appendChild(scriptElement);

    // return the promise, which will resolve to the script's exports
    return promise;
}

...

function doTheThing() {
    // no evals
    loadScript('5 + 5').then(function(exports) {
         // should log 10
        console.log(exports)
    });
}

I've simplified this from my actual implementation, so no promises that there aren't any bugs in it. But the principle works.

If you don't care about getting any value back after the script runs, it's even easier; just leave out the Promise and onload bits. You don't even need to wrap the script or create the global window.__load_script_exports_ property.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

Simple explanation about what a Index out of bound exception is:

Just think one train is there its compartments are D1,D2,D3. One passenger came to enter the train and he have the ticket for D4. now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.

Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0] and array[1] are existing. If we try to access array[3], it's not there actually, so an index out of bound exception will arise.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

Remove property for all objects in array

The only other ways are cosmetic and are in fact loops.

For example :

array.forEach(function(v){ delete v.bad });

Notes:

  • if you want to be compatible with IE8, you'd need a shim for forEach. As you mention prototype, prototype.js also has a shim.
  • delete is one of the worst "optimization killers". Using it often breaks the performances of your applications. You can't avoid it if you want to really remove a property but you often can either set the property to undefined or just build new objects without the property.

write a shell script to ssh to a remote machine and execute commands

For this kind of tasks, I repeatedly use Ansible which allows to duplicate coherently bash scripts in several containets or VM. Ansible (more precisely Red Hat) now has an additional web interface AWX which is the open-source edition of their commercial Tower.

Ansible: https://www.ansible.com/
AWX:https://github.com/ansible/awx
Ansible Tower: commercial product, you will probably fist explore the free open-source AWX, rather than the 15days free-trail of Tower

How to add extra whitespace in PHP?

PHP is an easy language with multiple solutions. A Quick Solution would be using Double Quotes " ". Example Below.

$var1 = "Hello";
$var2 = "World";
$var3 = "How";
$var4 = "are";
$var5 = "you";
$var6 = "?";
$var7 = ",";

echo "$var1 $var2$var7 $var3 $var4 $var5$var6";

//Output: Hello World, How are you?

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

R - Concatenate two dataframes?

You may use rbind but in this case you need to have the same number of columns in both tables, so try the following:

b$b<-as.double(NA) #keeping numeric format is essential for further calculations
new<-rbind(a,b)

base64 encode in MySQL

If you need this for < 5.6, I tripped across this UDF which seems to work fine:

https://github.com/y-ken/mysql-udf-base64

How to set timeout for a line of c# code

You can use the IAsyncResult and Action class/interface to achieve this.

public void TimeoutExample()
{
    IAsyncResult result;
    Action action = () =>
    {
        // Your code here
    };

    result = action.BeginInvoke(null, null);

    if (result.AsyncWaitHandle.WaitOne(10000))
         Console.WriteLine("Method successful.");
    else
         Console.WriteLine("Method timed out.");
}

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Remove 'standalone="yes"' from generated XML

You can either use

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

or

marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false)

to disable the default XML declaration, and then add your custom XML declaration,

<?xml version="1.0" encoding="UTF-8"?>

by

marshaller.setProperty("com.sun.xml.bind.xmlHeaders",
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

to the generated xml, thus avoiding the standalone="yes" property.

Current Subversion revision command

Just used @badcat's answer in a modified version, using subprocess.check_output():

import subprocess
revision = subprocess.check_output("svn info | awk '/^Revision:/ {print $2}'", shell=True).strip()

I believe you can also, install and use pysvn if you want to use python to interface with svn.

PG COPY error: invalid input syntax for integer

All in python (using psycopg2), create the empty table first then use copy_expert to load the csv into it. It should handle for empty values.

import psycopg2
conn = psycopg2.connect(host="hosturl", database="db_name", user="username", password="password")
cur = conn.cursor()
cur.execute("CREATE TABLE schema.destination_table ("
            "age integer, "
            "first_name varchar(20), "
            "last_name varchar(20)"
            ");")

with open(r'C:/tmp/people.csv', 'r') as f:
    next(f)  # Skip the header row. Or remove this line if csv has no header.
    conn.cursor.copy_expert("""COPY schema.destination_table FROM STDIN WITH (FORMAT CSV)""", f)

HTML - Change\Update page contents without refreshing\reloading the page

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

Using Case/Switch and GetType to determine the object

This won't directly solve your problem as you want to switch on your own user-defined types, but for the benefit of others who only want to switch on built-in types, you can use the TypeCode enumeration:

switch (Type.GetTypeCode(node.GetType()))
{
    case TypeCode.Decimal:
        // Handle Decimal
        break;

    case TypeCode.Int32:
        // Handle Int32
        break;
     ...
}

How can I rename a field for all documents in MongoDB?

You can use:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Or you can use the former way:

remap = function (x) {
  if (x.additional){
    db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
  }
}

db.foo.find().forEach(remap);

In MongoDB 3.2 you can also use

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )

The general syntax of this is

db.collection.updateMany(filter, update, options)

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

List<String> to ArrayList<String> conversion issue

Arrays.asList does not return instance of java.util.ArrayListbut it returns instance of java.util.Arrays.ArrayList.

You will need to convert to ArrayList if you want to access ArrayList specific information

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Virtualenv Command Not Found

this works in ubuntu 18 and above (not tested in previous versions):

sudo apt install python3-virtualenv

Jquery select change not firing

Try this

$('body').on('change', '#multiid', function() {
    // your stuff
})

please check .on() selector

How to find length of digits in an integer?

Python 2.* ints take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. sys.maxint (2**31-1 for 32-bit ints, 2**63-1 for 64-bit ints) will tell you which of the two possibilities obtains.

In Python 3, ints (like longs in Python 2) can take arbitrary sizes up to the amount of available memory; sys.getsizeof gives you a good indication for any given value, although it does also count some fixed overhead:

>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28

If, as other answers suggests, you're thinking about some string representation of the integer value, then just take the len of that representation, be it in base 10 or otherwise!

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

You would have used inline styles at many places, which CSP(Content Security Policy) prohibits because it could be dangerous.

Just try removing those inline styles and put it inside dedicated stylesheet.

Ordering by the order of values in a SQL IN() clause

Two solutions that spring to mind:

  1. order by case id when 123 then 1 when 456 then 2 else null end asc

  2. order by instr(','||id||',',',123,456,') asc

(instr() is from Oracle; maybe you have locate() or charindex() or something like that)

Is there a Google Sheets formula to put the name of the sheet into a cell?

Here is what I found for Google Sheets:

To get the current sheet name in Google sheets, the following simple script can help you without entering the name manually, please do as this:

  1. Click Tools > Script editor

  2. In the opened project window, copy and paste the below script code into the blank Code window, see screenshot:

......................

function sheetName() {
  return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}

Then save the code window, and go back to the sheet that you want to get its name, then enter this formula: =sheetName() in a cell, and press Enter key, the sheet name will be displayed at once.

See this link with added screenshots: https://www.extendoffice.com/documents/excel/5222-google-sheets-get-list-of-sheets.html

What is the difference between 'git pull' and 'git fetch'?

Here is Oliver Steele's image of how all it all fits together:

enter image description here

If there is sufficient interest, I suppose I could update the image to add git clone and git merge...

Remove the title bar in Windows Forms

if by Blue Border thats on top of the Window Form you mean titlebar, set Forms ControlBox property to false and Text property to empty string ("").

here's a snippet:

this.ControlBox = false;
this.Text = String.Empty;

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

The answer by @ajcr explains how the dot and matmul (invoked by the @ symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.

To clarify the differences take a 4x4 array and return the dot product and matmul product with a 3x4x2 'stack of matricies' or tensor.

import numpy as np
fourbyfour = np.array([
                       [1,2,3,4],
                       [3,2,1,4],
                       [5,4,6,7],
                       [11,12,13,14]
                      ])


threebyfourbytwo = np.array([
                             [[2,3],[11,9],[32,21],[28,17]],
                             [[2,3],[1,9],[3,21],[28,7]],
                             [[2,3],[1,9],[3,21],[28,7]],
                            ])

print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))

The products of each operation appear below. Notice how the dot product is,

...a sum product over the last axis of a and the second-to-last of b

and how the matrix product is formed by broadcasting the matrix together.

4x4*3x4x2 dot:
 [[[232 152]
  [125 112]
  [125 112]]

 [[172 116]
  [123  76]
  [123  76]]

 [[442 296]
  [228 226]
  [228 226]]

 [[962 652]
  [465 512]
  [465 512]]]

4x4*3x4x2 matmul:
 [[[232 152]
  [172 116]
  [442 296]
  [962 652]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]]

Selenium WebDriver can't find element by link text

Use xpath and text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));

Get the short Git version hash

A really simple way is to:

git describe --always

Simplest JQuery validation rules example

rules: {
    cname: {
        required: true,
        minlength: 2
    }
},
messages: {
    cname: {
        required: "<li>Please enter a name.</li>",
        minlength: "<li>Your name is not long enough.</li>"
    }
}

What is the default maximum heap size for Sun's JVM from Java SE 6?

java 1.6.0_21 or later, or so...

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize                         := 12660904960      {product}

It looks like the min(1G) has been removed.

Or on Windows using findstr

C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize

How do you merge two Git repositories?

If you want to put the files from a branch in repo B in a subtree of repo A and also preserve the history, keep reading. (In the example below, I am assuming that we want repo B's master branch merged into repo A's master branch.)

In repo A, first do the following to make repo B available:

git remote add B ../B # Add repo B as a new remote.
git fetch B

Now we create a brand new branch (with only one commit) in repo A that we call new_b_root. The resulting commit will have the files that were committed in the first commit of repo B's master branch but put in a subdirectory called path/to/b-files/.

git checkout --orphan new_b_root master
git rm -rf . # Remove all files.
git cherry-pick -n `git rev-list --max-parents=0 B/master`
mkdir -p path/to/b-files
git mv README path/to/b-files/
git commit --date="$(git log --format='%ai' $(git rev-list --max-parents=0 B/master))"

Explanation: The --orphan option to the checkout command checks out the files from A's master branch but doesn't create any commit. We could have selected any commit because next we clear out all the files anyway. Then, without committing yet (-n), we cherry-pick the first commit from B's master branch. (The cherry-pick preserves the original commit message which a straight checkout doesn't seem to do.) Then we create the subtree where we want to put all files from repo B. We then have to move all files that were introduced in the cherry-pick to the subtree. In the example above, there's only a README file to move. Then we commit our B-repo root commit, and, at the same time, we also preserve the timestamp of the original commit.

Now, we'll create a new B/master branch on top of the newly created new_b_root. We call the new branch b:

git checkout -b b B/master
git rebase -s recursive -Xsubtree=path/to/b-files/ new_b_root

Now, we merge our b branch into A/master:

git checkout master
git merge --allow-unrelated-histories --no-commit b
git commit -m 'Merge repo B into repo A.'

Finally, you can remove the B remote and temporary branches:

git remote remove B
git branch -D new_b_root b

The final graph will have a structure like this:

enter image description here

Class Diagrams in VS 2017

  1. Open Visual Studio Installer from the Windows Start menu, or by selecting Tools > Get Tools and Features from the menu bar in Visual Studio.

    Visual Studio Installer opens.

  2. Select the Individual components tab, and then scroll down to the Code tools category.

  3. Select Class Designer and then select Modify.

Visual Studio Installer Window

The Class Designer component starts installing.

For more details, visit this link: How to: Add class diagrams to projects

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

 -- Simple way without "functions" or "IF" or "CASE"
 -- Query to select maximum value
 SELECT o.OrderId
  ,(SELECT MAX(v)
   FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) AS MaxValue
  FROM Order o;

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

In Java, how do I parse XML as a String instead of a file?

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

What does 'x packages are looking for funding' mean when running `npm install`?

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

Best /Fastest way to read an Excel Sheet into a DataTable?

If you want to do the same thing in C# based on Ciarán Answer

string sSheetName = null;
string sConnection = null;
DataTable dtTablesList = default(DataTable);
OleDbCommand oleExcelCommand = default(OleDbCommand);
OleDbDataReader oleExcelReader = default(OleDbDataReader);
OleDbConnection oleExcelConnection = default(OleDbConnection);

sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Test.xls;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";

oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();

dtTablesList = oleExcelConnection.GetSchema("Tables");

if (dtTablesList.Rows.Count > 0) 
{
    sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}

dtTablesList.Clear();
dtTablesList.Dispose();


if (!string.IsNullOrEmpty(sSheetName)) {
    oleExcelCommand = oleExcelConnection.CreateCommand();
    oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
    oleExcelCommand.CommandType = CommandType.Text;
    oleExcelReader = oleExcelCommand.ExecuteReader();
    nOutputRow = 0;

    while (oleExcelReader.Read())
    {
    }
    oleExcelReader.Close();
}
oleExcelConnection.Close();

here is another way read Excel into a DataTable without using OLEDB very quick Keep in mind that the file ext would have to be .CSV for this to work properly

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    csvData = new DataTable(defaultTableName);
    try
    {
        using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[]
            {
                tableDelim 
            });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == string.Empty)
                    {
                        fieldData[i] = string.Empty; //fieldData[i] = null
                    }
                    //Skip rows that have any csv header information or blank rows in them
                    if (fieldData[0].Contains("Disclaimer") || string.IsNullOrEmpty(fieldData[0]))
                    {
                        continue;
                    }
                }
                csvData.Rows.Add(fieldData);
            }
        }
    }
    catch (Exception ex)
    {
    }
    return csvData;
}

Java better way to delete file if exists

Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:

Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. The difference between File.delete() and this method are:

  • A directory to be deleted does not have to be empty.
  • No exceptions are thrown when a file or directory cannot be deleted.

This offers a one-liner delete call that won't complain if the file fails to be deleted:

FileUtils.deleteQuietly(new File("test.txt"));

How to convert milliseconds to "hh:mm:ss" format?

DateFormat df = new SimpleDateFormat("HH:mm:ss");
String formatted = df.format(aDateObject);

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Base64 encoding and decoding in oracle

Solution with utl_encode.base64_encode and utl_encode.base64_decode have one limitation, they work only with strings up to 32,767 characters/bytes.

In case you have to convert bigger strings you will face several obstacles.

  • For BASE64_ENCODE the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€ stored at UTF-8, aka AL32UTF8) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB into BLOB first.
  • The same problem applies for BASE64_DECODE. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 Characters
  • Typically a BASE64-String has NEW_LINE (CR and/or LF) character each 64 characters. Such new-line characters have to be ignored while decoding.

Taking all this into consideration the full featured solution could be this one:

CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS

    blob_loc BLOB;
    clob_trim CLOB;
    res CLOB;

    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);

    amount INTEGER := 1440; -- must be a whole multiple of 4
    buffer RAW(1440);
    stringBuffer VARCHAR2(1440);
    -- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient

BEGIN

    IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen<= 32000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
    END IF;        
    -- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger    

    -- Remove all NEW_LINE from base64 string
    ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
    DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
        DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
        read_offset := read_offset + amount;
    END LOOP;

    read_offset := 1;
    ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
    DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
    LOOP
        EXIT WHEN read_offset > ClobLen;
        buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
        DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
        read_offset := read_offset + amount;
    END LOOP;

    DBMS_LOB.CREATETEMPORARY(res, TRUE);
    DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset,  DBMS_LOB.DEFAULT_CSID, lang_context, warning);

    DBMS_LOB.FREETEMPORARY(blob_loc);
    DBMS_LOB.FREETEMPORARY(clob_trim);
    RETURN res;    

END DecodeBASE64;




CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS

    dest_lob BLOB;  
    lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
    dest_offset INTEGER := 1;
    src_offset INTEGER := 1;
    read_offset INTEGER := 1;
    warning INTEGER;
    ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);

    amount INTEGER := 1440; -- must be a whole multiple of 3
    -- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters 
    buffer RAW(1440);
    res CLOB := EMPTY_CLOB();

BEGIN

    IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN 
        RETURN NULL;
    ELSIF ClobLen <= 24000 THEN
        RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
    END IF;
    -- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger    

    DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
    DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
    LOOP
        EXIT WHEN read_offset >= dest_offset;
        DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
        res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));       
        read_offset := read_offset + amount;
    END LOOP;
    DBMS_LOB.FREETEMPORARY(dest_lob);
    RETURN res;

END EncodeBASE64;

How to refresh an IFrame using Javascript?

This should help:

document.getElementById('FrameID').contentWindow.location.reload(true);

EDIT: Fixed the object name as per @Joro's comment.

405 method not allowed Web API

My problem turned out to be Attribute Routing in WebAPI. I created a custom route, and it treated it like a GET instead of WebAPI discovering it was a POST

    [Route("")]
    [HttpPost] //I added this attribute explicitly, and it worked
    public void Post(ProductModel data)
    {
        ...
    }

I knew it had to be something silly (that consumes your entire day)

python global name 'self' is not defined

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Difference between View and table in sql

In view there is not any direct or physical relation with the database. And Modification through a view (e.g. insert, update, delete) is not permitted.Its just a logical set of tables

How do I add a resources folder to my Java project in Eclipse

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

How do I deal with installing peer dependencies in Angular CLI?

NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.

I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!

Question mark characters displaying within text, why is this?

This is going to be something to do with character encodings.

Are you sure the mirrored site has the same properties with regards to character encodings as your main server?

Depending on what sort of server you have, this may be a property of the server process itself, or it could be an environment variable.

For example, if this is a UNIX environment, perhaps try comparing LANG or LC_ALL?

See also here

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

svn over HTTP proxy

when you use the svn:// URI it uses port 3690 and probably won't use http proxy

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

What is the difference between an interface and abstract class?

Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface?

class Circle {

protected $radius;

public function __construct($radius)

{
    $this->radius = $radius
}

public function area()
{
    return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square);
}

}

//Our area calculator class would look like

class Areacalculator {

$protected $circle;

public function __construct(Circle $circle)
{
    $this->circle = $circle;
}

public function areaCalculate()
{
    return $circle->area(); //returns the circle area now
}

}

We would simply do

$areacalculator = new Areacalculator(new Circle(7)); 

Few days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. Solution would be:

Interface Shape {

public function area(); //Defining contract for the classes

}

Class Square implements Shape {

$protected length;

public function __construct($length) {
    //settter for length like we did on circle class
}

public function area()
{
    //return l square for area of square
}

Class Rectangle implements Shape {

$protected length;
$protected breath;

public function __construct($length,$breath) {
    //settter for length, breath like we did on circle,square class
}

public function area()
{
    //return l*b for area of rectangle
}

}

Now for area calculator

class Areacalculator {

$protected $shape;

public function __construct(Shape $shape)
{
    $this->shape = $shape;
}

public function areaCalculate()
{
    return $shape->area(); //returns the circle area now
}

}

$areacalculator = new Areacalculator(new Square(1));
$areacalculator->areaCalculate();

$areacalculator = new Areacalculator(new Rectangle(1,2));
$areacalculator->;areaCalculate();

Isn't that more flexible? If we would code without interface we would check the instance for each shape redundant code.

Now when to use abstract?

Abstract Animal {

public function breathe(){

//all animals breathe inhaling o2 and exhaling co2

}

public function hungry() {

//every animals do feel hungry 

}

abstract function communicate(); 
// different communication style some bark, some meow, human talks etc

}

Now abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract.

Retrofit 2.0 how to get deserialised error response.body

Tested and works

 public BaseModel parse(Response<BaseModel> response , Retrofit retrofit){
            BaseModel error = null;
            Converter<ResponseBody, BaseModel> errorConverter =
                    retrofit.responseBodyConverter(BaseModel.class, new Annotation[0]);
            try {
                if (response.errorBody() != null) {
                    error = errorConverter.convert(response.errorBody());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return error;
        }

How to get the user input in Java?

One of the simplest ways is to use a Scanner object as follows:

import java.util.Scanner;

Scanner reader = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();

How do I get the Session Object in Spring?

I try with next code and work excellent

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    /**
     * Created by jaime on 14/01/15.
     */

    @Controller
    public class obteinUserSession {
        @RequestMapping(value = "/loginds", method = RequestMethod.GET)
        public String UserSession(ModelMap modelMap) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName();
            modelMap.addAttribute("username", name);
            return "hellos " + name;
        }

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

How to get the absolute coordinates of a view

Use This code to find exact X and Y cordinates :

int[] array = new int[2];
ViewForWhichLocationIsToBeFound.getLocationOnScreen(array);
if (AppConstants.DEBUG)
    Log.d(AppConstants.TAG, "array  X = " + array[0] + ", Y = " + array[1]);
ViewWhichToBeMovedOnFoundLocation.setTranslationX(array[0] + 21);
ViewWhichToBeMovedOnFoundLocation.setTranslationY(array[1] - 165);

I have added/subtracted some values to adjust my view. Please do these lines only after whole view has been inflated.

How to get Javascript Select box's selected text

In order to get the value of the selected item you can do the following:

this.options[this.selectedIndex].text

Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.

Read more about the select DOM here.