Programs & Examples On #Realm

The Realm Platform is a data synchronization platform for mobile applications. It includes the Realm Database, the Realm Object Server, and Realm Studio. It can save you thousands of lines of code and weeks of work, and lets you craft amazing new user experiences.

How to find my realm file?

Finding a Realm File

For Android

How to view my Realm file in the Realm Browser?

For iOS

If your App is on Device

Make sure that your device is connected and go to the devices window in the Xcode menu Window > Devices (??2). There you will be able to choose your device and your app from a list of installed apps with debugging permissions.

After selecting your app, go to the cog in the toolbar at the bottom of the table view and select “Download Container…“. There you will be able to pull the file from the documents location to your Mac. It will be saved as an xcappdata bundle.

When you open the local path in Finder, where you saved it, you can tap into that by selecting “Show Package Contents” in the context menu of the finder, when you select the file. A new finder window will open, where you find your Realm inside in the following path (e.g.): AppData/Documents/default.realm (The directory '/private/var/mobile' is the path, which is used by iOS on the device filesystem.

If your App is on the Simulator

Go to your user’s directory:

/Users/<username>/Library/Developer/CoreSimulator/Devices/<simulator-uuid>/data/Containers/Data/Application/<application-uuid>/Documents/default.realm

Probably the easiest way to get the current path of the default realm is to pause the simulator and enter the following into the LLDB console:

Objective-C:
(lldb) po [RLMRealmConfiguration defaultConfiguration].fileURL

Swift using Realm Objective-C:
(lldb) po RLMRealmConfiguration.defaultConfiguration().fileURL

Swift using Realm Swift:
(lldb) po Realm.Configuration.defaultConfiguration.fileURL

Or if you have an RLMRealm instance at hand, you can use:
(lldb) po myRealm.configuration.fileURL

Then just copy this path, open your terminal, and type open [Pasted path here]

NOTE: Some paths have a space in them so be sure to use "\" before the space to escape it

Helper Tool SimPholders

This is probably the fastest way to find the file of an app in the simulator. Install SimPholders. This will allow you to access your app’s documents directory directly from your menu bar.

Note Some people have mentioned that SimPholders has taken them to the wrong simulator app folder, if that's the case for you, print out your realm path by following the steps above, printing out your realm.path

wget/curl large file from google drive

The default behavior of google drive is to scan files for viruses if the file is to big it will prompte the user and notifies him that the file could not be scanned.

At the moment the only workaround I found is to share the file with the web and create a web resource.

Quote from the google drive help page:

With Drive, you can make web resources — like HTML, CSS, and Javascript files — viewable as a website.

To host a webpage with Drive:

  1. Open Drive at drive.google.com and select a file.
  2. Click the Share button at the top of the page.
  3. Click Advanced in the bottom right corner of the sharing box.
  4. Click Change....
  5. Choose On - Public on the web and click Save.
  6. Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
  7. Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
    Anyone can now view your webpage.

Found here: https://support.google.com/drive/answer/2881970?hl=en

So for example when you share a file on google drive publicly the sharelink looks like this:

https://drive.google.com/file/d/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U/view?usp=sharing

Then you copy the file id and create a googledrive.com linke that look like this:

https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U

CSS set li indent

I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.

ul {
    margin-left: 1.5em;
}

ul > ul {
    margin-left: 1.5em;
}

Git commit with no commit message

You don't need git to accomplish this. Creative use of a bash function will do the trick just fine. If you don't care about messages, just set a default one and forget it.

function gitcom() {
  git commit -m "my default commit message"
}

If you were feeling really adventurous you could add, commit and push with one command

function gitzap() {
  git add . && git commit -m "whatevs" && git push $1 $2
}

Which you would then run as

gitzap origin master

You could even get deeper and use parse_git_branch to save yourself some keystrokes there, or set a common default of "origin" and "master".

How to use in jQuery :not and hasClass() to get a specific element without a class

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');

How to fit Windows Form to any screen resolution?

simply set Autoscroll = true for ur windows form.. (its not good solution but helpful)..

try for panel also(Autoscroll property = true)

Getting current directory in VBScript

'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
    Property Get Path()
          Dim sTmp
          If IsObject(Server) Then
               'Classic ASP
               Path = Server.MapPath("../")
          ElseIf IsObject(WScript) Then 
               'Windows Scripting Host
               Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
          ElseIf IsObject(window) Then
               'Internet Explorer HTML Application (HTA)
               sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
               Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
          End If
    End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path

How do I alter the position of a column in a PostgreSQL database table?

I was working on re-ordering a lot of tables and didn't want to have to write the same queries over and over so I made a script to do it all for me. Essentially, it:

  1. Gets the table creation SQL from pg_dump
  2. Gets all available columns from the dump
  3. Puts the columns in the desired order
  4. Modifies the original pg_dump query to create a re-ordered table with data
  5. Drops old table
  6. Renames new table to match old table

It can be used by running the following simple command:

./reorder.py -n schema -d database table \
    first_col second_col ... penultimate_col ultimate_col --migrate

It prints out the sql so you can verify and test it, that was a big reason I based it on pg_dump. You can find the github repo here.

C#: Printing all properties of an object

Don't think so. I've always had to write them or use someone else's work to get that info. Has to be reflection as far as i'm aware.

EDIT:
Check this out. I was investigating some debugging on long object graphs and noticed this when i Add Watches, VS throws in this class: Mscorlib_CollectionDebugView<>. It's an internal type for displaying collections nicely for viewing in the watch windows/code debug modes. Now coz it's internal you can reference it, but u can use Reflector to copy (from mscorlib) the code and have your own (the link above has a copy/paste example). Looks really useful.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

  1. Under Window Administrative Tools, run ODBC Data Sources (32-bit).

  2. Under the Drivers tab, check you have the Microsoft Excel Driver (*.xls, *.xlsx etc...) - the file name is ACEODBC.DLL

  3. If this is missing, you will need to install the Microsoft Access Database Engine 2016 Redistributable.

You'll find the installer here https://www.microsoft.com/en-us/download/details.aspx?id=54920

  1. Your connection should be:
Set objConn1 = Server.CreateObject("ADODB.Connection") 
objConn1.Provider = "Microsoft.ACE.OLEDB.12.0"   
objConn1.ConnectionString = "Data Source=" & pPath & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1""" 

Alternative to deprecated getCellType

You can use:

cell.getCellTypeEnum()

Further to compare the cell type, you have to use CellType as follows:-

if(cell.getCellTypeEnum() == CellType.STRING){
      .
      .
      .
}

You can Refer to the documentation. Its pretty helpful:-

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

What is the largest Safe UDP Packet Size on the Internet

512 is your best bet. It's used elsewhere and is a nice even number (half of 1024).

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

Accessing last x characters of a string in Bash

1. Generalized Substring

To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:

${string: -7:4}

Where 4 is the length of course (7-3).

2. Alternative using cut

In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:

echo $string | cut -c $((${#string}-2))-

Here, ${#string} is the length of the string, and the "-" means cut to the end.

3. Alternative using awk

This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length) going to the end if the length is omitted. length($string)-2) thus picks up the last three characters.

echo $string | awk '{print substr($1,length($1)-2) }'

Google Maps v2 - set both my location and zoom in

The simpliest way to do it is to use CancelableCallback. You should check the first action is complete and then call the second:

mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, size.x, height, 0), new CancelableCallback() {

                @Override
                public void onFinish() {
                    CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(0, 500);
                    mMap.animateCamera(cu_scroll);
                }

                @Override
                public void onCancel() {
                }
            });

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Missing XML comment for publicly visible type or member

File > Edit > View Project (click)

Bottom of the drop down bow (click on Open/Current work > Properties), opened project properties page at "Build" under "Output". "Uncheck" XML Documentation checkbox.

Rebuild and no warnings.

How to convert an integer to a string in any base?

A recursive solution for those interested. Of course, this will not work with negative binary values. You would need to implement Two's Complement.

def generateBase36Alphabet():
    return ''.join([str(i) for i in range(10)]+[chr(i+65) for i in range(26)])

def generateAlphabet(base):
    return generateBase36Alphabet()[:base]

def intToStr(n, base, alphabet):
    def toStr(n, base, alphabet):
        return alphabet[n] if n < base else toStr(n//base,base,alphabet) + alphabet[n%base]
    return ('-' if n < 0 else '') + toStr(abs(n), base, alphabet)

print('{} -> {}'.format(-31, intToStr(-31, 16, generateAlphabet(16)))) # -31 -> -1F

How can I hide/show a div when a button is clicked?

Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.

$('#btn').click(function() {
    $('#wizard').toggle();
});

Refer to the JQuery website for more information.

This can also be done without JQuery. Using only standard JavaScript:

<script type="text/javascript">
   function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
   }
</script>

Then add onclick="toggle_visibility('id_of_element_to_toggle');" to the button that is used to show and hide the div.

Java: Calling a super method which calls an overridden method

If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.

Here's a suggestion:

public class SuperClass {

  public void method1() {
    System.out.println("superclass method1");
    this.internalMethod2();
  }

  public void method2()  {
    // this method can be overridden.  
    // It can still be invoked by a childclass using super
    internalMethod2();
  }

  private void internalMethod2()  {
    // this one cannot.  Call this one if you want to be sure to use
    // this implementation.
    System.out.println("superclass method2");
  }

}

public class SubClass extends SuperClass {

  @Override
  public void method1() {
    System.out.println("subclass method1");
    super.method1();
  }

  @Override
  public void method2() {
    System.out.println("subclass method2");
  }
}

If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).

bodyParser is deprecated express 4

What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages appeared in your log

run this command

npm install express-generator -g

Now, create new Express.js starter application by type this command in your Node projects folder.

express node-express-app

That command tell express to generate new Node.js application with the name node-express-app.

then Go to the newly created project directory, install npm packages and start the app using the command

cd node-express-app && npm install && npm start

How do I include a pipe | in my linux find -exec command?

find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

How to scroll to bottom in react?

The easiest and best way I would recommend is.

My ReactJS version: 16.12.0


For Class Components

HTML structure inside render() function

    render()
        return(
            <body>
                <div ref="messageList">
                    <div>Message 1</div>
                    <div>Message 2</div>
                    <div>Message 3</div>
                </div>
            </body>
        )
    )

scrollToBottom() function which will get reference of the element. and scroll according to scrollIntoView() function.

  scrollToBottom = () => {
    const { messageList } = this.refs;
    messageList.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
  }

and call the above function inside componentDidMount() and componentDidUpdate()


For Functional Components (Hooks)

Import useRef() and useEffect()

import { useEffect, useRef } from 'react'

Inside your export function, (same as calling a useState())

const messageRef = useRef();

And let's assume you have to scroll when page load,

useEffect(() => {
    if (messageRef.current) {
      messageRef.current.scrollIntoView(
        {
          behavior: 'smooth',
          block: 'end',
          inline: 'nearest'
        })
    }
  })

OR if you want it to trigger once an action performed,

useEffect(() => {
  if (messageRef.current) {
    messageRef.current.scrollIntoView(
      {
        behavior: 'smooth',
        block: 'end',
        inline: 'nearest'
      })
  }
},
[stateVariable])

And Finally, to your HTML structure

return(
    <body>
        <div ref={messageRef}> // <= The only different is we are calling a variable here
            <div>Message 1</div>
            <div>Message 2</div>
            <div>Message 3</div>
        </div>
    </body>
)

for more explanation about Element.scrollIntoView() visit developer.mozilla.org

More detailed explanation in Callback refs visit reactjs.org

pycharm convert tabs to spaces automatically

Just ot note: Pycharm's to spaces function only works on indent tabs at the beginning of a line, not interstitial tabs within a line of text. for example, when you are trying to format columns in monospaced text.

glob exclude pattern

You can't exclude patterns with the glob function, globs only allow for inclusion patterns. Globbing syntax is very limited (even a [!..] character class must match a character, so it is an inclusion pattern for every character that is not in the class).

You'll have to do your own filtering; a list comprehension usually works nicely here:

files = [fn for fn in glob('somepath/*.txt') 
         if not os.path.basename(fn).startswith('eph')]

no module named urllib.parse (How should I install it?)

If you need to write code which is Python2 and Python3 compatible you can use the following import

try:
    from urllib.parse import urlparse
except ImportError:
     from urlparse import urlparse

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

What's a decent SFTP command-line client for windows?

WinSCP has the command line functionality:

c:\>winscp.exe /console /script=example.txt

where scripting is done in example.txt.

See http://winscp.net/eng/docs/guide_automation

Refer to http://winscp.net/eng/docs/guide_automation_advanced for details on how to use a scripting language such as Windows command interpreter/php/perl.

FileZilla does have a command line but it is limited to only opening the GUI with a pre-defined server that is in the Site Manager.

What is the apply function in Scala?

TLDR for people comming from c++

It's just overloaded operator of ( ) parentheses

So in scala:

class X {
   def apply(param1: Int, param2: Int, param3: Int) : Int = {
     // Do something
   }
}

Is same as this in c++:

class X {
   int operator()(int param1, int param2, int param3) {
      // do something
   }
};

How do I delete an item or object from an array using ng-click?

Pass the id that you want to remove from the array to the given function 

from the controller( Function can be in the same controller but prefer to keep it in a service)

    function removeInfo(id) {
    let item = bdays.filter(function(item) {
      return bdays.id=== id;
    })[0];
    let index = bdays.indexOf(item);
    data.device.splice(indexOfTabDetails, 1);
  }

The order of keys in dictionaries

Although the order does not matter as the dictionary is hashmap. It depends on the order how it is pushed in:

s = 'abbc'
a = 'cbab'

def load_dict(s):
    dict_tmp = {}
    for ch in s:
        if ch in dict_tmp.keys():
            dict_tmp[ch]+=1
        else:
            dict_tmp[ch] = 1
    return dict_tmp

dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))

output:
for string abbc, the keys are dict_keys(['a', 'b', 'c'])
for string cbab, the keys are dict_keys(['c', 'b', 'a'])

How to get size of mysql database?

It can be determined by using following MySQL command

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema

Result

Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382

Get result in GB

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

How to handle notification when app in background in Firebase

1. Why is this happening?

There are two types of messages in FCM (Firebase Cloud Messaging):

  1. Display Messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
  2. Data Messages: Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed

NOTE: Firebase team have not developed a UI to send data-messages to your devices, yet. You should use your server for sending this type!



2. How to?

To achieve this, you have to perform a POST request to the following URL:

POST https://fcm.googleapis.com/fcm/send

Headers

  • Key: Content-Type, Value: application/json
  • Key: Authorization, Value: key=<your-server-key>

Body using topics

{
    "to": "/topics/my_topic",
    "data": {
        "my_custom_key": "my_custom_value",
        "my_custom_key2": true
     }
}

Or if you want to send it to specific devices

{
    "data": {
        "my_custom_key": "my_custom_value",
        "my_custom_key2": true
     },
    "registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
}


NOTE: Be sure you're not adding JSON key notification
NOTE: To get your server key, you can find it in the firebase console: Your project -> settings -> Project settings -> Cloud messaging -> Server Key

3. How to handle the push notification message?

This is how you handle the received message:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) { 
     Map<String, String> data = remoteMessage.getData();
     String myCustomKey = data.get("my_custom_key");

     // Manage data
}

Execute a file with arguments in Python shell

Actually, wouldn't we want to do this?

import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')

Get Cell Value from a DataTable in C#

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
{
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
        {
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();
        }
}

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

What is perm space?

  • JVM has an internal representation of Java objects and those internal representations are stored in the heap (in the young generation or the tenured generation).
  • JVM also has an internal representation of the Java classes and those are stored in the permanent generation

enter image description here

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

My WPF project referenced 3 custom dlls. I updated one of them, deleted the reference and added the reference to the new dll. It also showed the correct version number in the properties of the reference. It was rebuilding without an error.

But when the application was running, the failure "The located assembly's manifest .." occured, mentioning the old version.

After searching for a solution for hours and reading couple of threads like this, I remembered the other dlls. One of the other dlls was referencing the old version, and that's why the failure occured. After rebuilding the 2nd dll and recreating both references in my WPF project, the failure was gone.

Don't forget to check your other dlls!

How to run a function in jquery

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

How to keep footer at bottom of screen

use this style

min-height:250px;
height:auto;

Generate a random point within a circle (uniformly)

A programmer solution:

  • Create a bit map (a matrix of boolean values). It can be as large as you want.
  • Draw a circle in that bit map.
  • Create a lookup table of the circle's points.
  • Choose a random index in this lookup table.
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;

bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};

struct Point { int x; int y; };

Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];

void init()
{
  int numberOfOnBits = 0;

  for (int x = 0 ; x < MATRIX_SIZE ; ++x)
  {
    for (int y = 0 ; y < MATRIX_SIZE ; ++y)
    {
      if (x * x + y * y < RADIUS * RADIUS) 
      {
        matrix[x][y] = true;

        loopUpTable[numberOfOnBits].x = x;
        loopUpTable[numberOfOnBits].y = y;

        ++numberOfOnBits;

      } // if
    } // for
  } // for
} // ()

Point choose()
{
  int randomIndex = randomInt(numberOfBits);

  return loopUpTable[randomIndex];
} // ()

The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:

const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;

struct Point { int x; int y; };

Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];

void init()
{
  int numberOfOnBits = 0;

  for (int x = 0 ; x < MATRIX_SIZE ; ++x)
  {
    for (int y = 0 ; y < MATRIX_SIZE ; ++y)
    {
      if (x * x + y * y < RADIUS * RADIUS) 
      {
        loopUpTable[numberOfOnBits].x = x;
        loopUpTable[numberOfOnBits].y = y;

        ++numberOfOnBits;
      } // if
    } // for
  } // for
} // ()

Point choose()
{
  int randomIndex = randomInt(numberOfBits);

  return loopUpTable[randomIndex];
} // ()

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use cl scr on the Sql* command line tool to clear all the matter on the screen.

Taking multiple inputs from user in python

Or if you are collecting many numbers, use a loop

num = []
for i in xrange(1, 10):
    num.append(raw_input('Enter the %s number: '))

print num

Remove Top Line of Text File with PowerShell

While I really admire the answer from @hoge both for a very concise technique and a wrapper function to generalize it and I encourage upvotes for it, I am compelled to comment on the other two answers that use temp files (it gnaws at me like fingernails on a chalkboard!).

Assuming the file is not huge, you can force the pipeline to operate in discrete sections--thereby obviating the need for a temp file--with judicious use of parentheses:

(Get-Content $file | Select-Object -Skip 1) | Set-Content $file

... or in short form:

(gc $file | select -Skip 1) | sc $file

How to achieve pagination/table layout with Angular.js?

here i have solve my angularJS pagination issue with some more tweak in server side + view end you can check the code it will be more efficient. all i have to do is put two value start number and end number , it will represent index of the returned json array.

here is the angular

var refresh = function () {
    $('.loading').show();
    $http.get('http://put.php?OutputType=JSON&r=all&s=' + $scope.CountStart + '&l=' + $scope.CountEnd).success(function (response) {
        $scope.devices = response;


        $('.loading').hide();
    });
};

if you see carefully $scope.CountStart and $scope.CountStart are two argument i am passing with the api

here is the code for next button

$scope.nextPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();


    if ($scope.currentPage >= 0) {
        $scope.currentPage++;

        $scope.CountStart = $scope.CountStart + $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd + $scope.DevicePerPage;
        refresh();
    }
};

here is the code for previous button

$scope.prevPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();

    if ($scope.currentPage > 0) {
        $scope.currentPage--;

        $scope.CountStart = $scope.CountStart - $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd - $scope.DevicePerPage;

        refresh();

    }
};

if the page number is zero my previous button will be deactivated

   $scope.nextPageDisabled = function () {

    console.log($scope.currentPage);

    if ($scope.currentPage === 0) {
        return false;
    } else {
        return true;
    }
};

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

WordPress path url in js script file

According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>

How to convert a Bitmap to Drawable in android?

covert bit map to drawable in sketchware app using code

    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);

Create Hyperlink in Slack

In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:

  1. Copy a URL to the clipboard
  2. Select the text in a slack message you are writing that you want to be a link
  3. Press ?V on Mac or CtrlV

I couldn't find it documented anywhere, but it works, and seems very handy.

How to hide first section header in UITableView (grouped style)

The answer was very funny for me and my team, and worked like a charm

  • In the Interface Builder, Just move the tableview under another view in the view hierarchy.

REASON:

We observed that this happens only for the First View in the View Hierarchy, if this first view is a UITableView. So, all other similar UITableViews do not have this annoying section, except the first. We Tried moving the UITableView out of the first place in the view hierarchy, and everything was working as expected.

C# Copy a file to another location with a different name

The easiest method you can use is this:

System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);

This will take care of everything you requested.

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

How to center the text in PHPExcel merged cell

We can also set the vertical alignment with using this way

$style_cell = array(
   'alignment' => array(
       'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
       'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
   ) 
); 

with this cell set the vertically aligned into the middle.

Add & delete view from Layout

you can use addView or removeView

java:

// Root Layout
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setOrientation(LinearLayout.VERTICAL);

// TextView
TextView textView = new TextView(context);
textView.setText("Sample");

// Add TextView in LinearLayout
linearLayout.addView(textView);

// Remove TextView from LinearLayout
linearLayout.removeView(textView);

kotlin:

// Root Layout
val linearLayout = LinearLayout(context)
linearLayout.gravity = Gravity.CENTER
linearLayout.orientation = LinearLayout.VERTICAL

// TextView
val textView = TextView(context)
textView.text = "Sample"

// Add TextView in LinearLayout
linearLayout.addView(textView)

// Remove TextView from LinearLayout
linearLayout.removeView(textView)

Concatenate strings from several rows using Pandas groupby

If you want to concatenate your "text" in a list:

df.groupby(['name', 'month'], as_index = False).agg({'text': list})

How to remove all characters after a specific character in python?

Assuming your separator is '...', but it can be any string.

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

If the separator is not found, head will contain all of the original string.

The partition function was added in Python 2.5.

partition(...) S.partition(sep) -> (head, sep, tail)

Searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it.  If the separator is not
found, returns S and two empty strings.

javascript: using a condition in switch case

Notice that we don't pass score to the switch but true. The value we give to the switch is used as the basis to compare against.

The below example shows how we can add conditions in the case: without any if statements.

function getGrade(score) {
    let grade;
    // Write your code here
    switch(true) {
        case score >= 0 && score <= 5:
        grade = 'F';
        break;
        case score > 5 && score <= 10:
        grade = 'E';
        break;
        case score > 10 && score <= 15:
        grade = 'D';
        break;
        case score > 15 && score <= 20:
        grade = 'C';
        break;
        case score > 20 && score <= 25:
        grade = 'B';
        break;
        case score > 25 && score <= 30:
        grade = 'A';
        break;
    }

    return grade;
}

How to activate JMX on my JVM for access with jconsole?

I'm using WAS ND 7.0

My JVM need all the following arguments to be monitored in JConsole

    -Djavax.management.builder.initial= 
    -Dcom.sun.management.jmxremote 
    -Dcom.sun.management.jmxremote.port=8855 
    -Dcom.sun.management.jmxremote.authenticate=false 
    -Dcom.sun.management.jmxremote.ssl=false

If input value is blank, assign a value of "empty" with Javascript

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Package php5 have no installation candidate (Ubuntu 16.04)

I recently had this issue as well and solved it using the following command:

sudo apt install php7.2-cli

php is now installed. I'm using Ubuntu 18.04.

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

AngularJs $http.post() does not send data

Just updated from angular 1.2 to 1.3, have found a problem in the code. Transforming a resource will lead to an endless-loop because (I think) of the $promise holding again the same object. Maybe it will help someone...

I could fix that by:

[...]
  /**
 * The workhorse; converts an object to x-www-form-urlencoded serialization.
 * @param {Object} obj
 * @return {String}
 */
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

angular.forEach(obj, function(value, name) {
+    if(name.indexOf("$promise") != -1) {
+        return;
+    }

    value = obj[name];
    if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
[...]

Adding multiple class using ng-class

An incredibly powerful alternative to other answers here:

ng-class="[  { key: resulting-class-expression }[ key-matching-expression ], ..  ]"

Some examples:

1. Simply adds 'class1 class2 class3' to the div:

<div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>

2. Adds 'odd' or 'even' classes to div, depending on the $index:

<div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>

3. Dynamically creates a class for each div based on $index

<div ng-class="[{true:'index'+$index}[true]]"></div>

If $index=5 this will result in:

<div class="index5"></div>

Here's a code sample you can run:

_x000D_
_x000D_
var app = angular.module('app', []); _x000D_
app.controller('MyCtrl', function($scope){_x000D_
  $scope.items = 'abcdefg'.split('');_x000D_
}); 
_x000D_
.odd  { background-color: #eee; }_x000D_
.even { background-color: #fff; }_x000D_
.index5 {background-color: #0095ff; color: white; font-weight: bold; }_x000D_
* { font-family: "Courier New", Courier, monospace; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="app" ng-controller="MyCtrl">_x000D_
  <div ng-repeat="item in items"_x000D_
    ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">_x000D_
    index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to click a browser button with JavaScript automatically?

document.getElementById('youridhere').click()

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Move view with keyboard using Swift

Swift 5.0:

After 4-5 hours of fight i came with a simple extension of UIViewController with simple code which works like charm

*View should not move when TextField is above the keyboard

*No need to set constant value to NSLayoutConstraint

*No third party library required

*No animation code required

*Works on tableview as well

*This works on Auto layout / auto resize

extension UIViewController {
    func addKeyboardObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardNotifications(notification:)),
                                               name: UIResponder.keyboardWillChangeFrameNotification,
                                               object: nil)
    }

    func removeKeyboardObserver(){
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }

    // This method will notify when keyboard appears/ dissapears
    @objc func keyboardNotifications(notification: NSNotification) {

        var txtFieldY : CGFloat = 0.0  //Using this we will calculate the selected textFields Y Position
        let spaceBetweenTxtFieldAndKeyboard : CGFloat = 5.0 //Specify the space between textfield and keyboard


        var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        if let activeTextField = UIResponder.currentFirst() as? UITextField ?? UIResponder.currentFirst() as? UITextView {
            // Here we will get accurate frame of textField which is selected if there are multiple textfields
            frame = self.view.convert(activeTextField.frame, from:activeTextField.superview)
            txtFieldY = frame.origin.y + frame.size.height
        }

        if let userInfo = notification.userInfo {
            // here we will get frame of keyBoard (i.e. x, y, width, height)
            let keyBoardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
            let keyBoardFrameY = keyBoardFrame!.origin.y
            let keyBoardFrameHeight = keyBoardFrame!.size.height

            var viewOriginY: CGFloat = 0.0
            //Check keyboards Y position and according to that move view up and down
            if keyBoardFrameY >= UIScreen.main.bounds.size.height {
                viewOriginY = 0.0
            } else {
                // if textfields y is greater than keyboards y then only move View to up
                if txtFieldY >= keyBoardFrameY {

                    viewOriginY = (txtFieldY - keyBoardFrameY) + spaceBetweenTxtFieldAndKeyboard

                    //This condition is just to check viewOriginY should not be greator than keyboard height
                    // if its more than keyboard height then there will be black space on the top of keyboard.
                    if viewOriginY > keyBoardFrameHeight { viewOriginY = keyBoardFrameHeight }
                }
            }

            //set the Y position of view
            self.view.frame.origin.y = -viewOriginY
        }
    }
}

Add this Extension Of UIResponder to get which TextField is selected

extension UIResponder {

    static weak var responder: UIResponder?

    static func currentFirst() -> UIResponder? {
        responder = nil
        UIApplication.shared.sendAction(#selector(trap), to: nil, from: nil, for: nil)
        return responder
    }

    @objc private func trap() {
        UIResponder.responder = self
    }
}

Then use of this in your any ViewController

   override func viewWillAppear(_ animated: Bool) {
        self.addKeyboardObserver()
    }

    override func viewWillDisappear(_ animated: Bool) {
        self.removeKeyboardObserver()
    }

  • Register this Notification in func viewWillAppear(_ animated: Bool)

  • Deregister this Notification in func viewWillDisappear(_ animated:Bool)

    Download Demo Here

How to get equal width of input and select fields

Add this code in css:

 select, input[type="text"]{
      width:100%;
      box-sizing:border-box;
    }

Best way to disable button in Twitter's Bootstrap

You just need the $('button').prop('disabled', true); part, the button will automatically take the disabled class.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.

Python, remove all non-alphabet chars from string

The fastest method is regex

#Try with regex first
t0 = timeit.timeit("""
s = r2.sub('', st)

""", setup = """
import re
r2 = re.compile(r'[^a-zA-Z0-9]', re.MULTILINE)
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)

#Try with join method on filter
t0 = timeit.timeit("""
s = ''.join(filter(str.isalnum, st))

""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""",
number = 1000000)
print(t0)

#Try with only join
t0 = timeit.timeit("""
s = ''.join(c for c in st if c.isalnum())

""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)


2.6002226710006653 Method 1 Regex
5.739747313000407 Method 2 Filter + Join
6.540099570000166 Method 3 Join

Add image to layout in ruby on rails

It's working for me:

<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

MySQL vs MySQLi when using PHP

MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.

How can I get table names from an MS Access Database?

Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:

Dim db as Database
Dim td as TableDef
Set db = CurrentDb()
For Each td In db.TableDefs
  YourSubTakingTableName(td.Name)
Next td

Select something that has more/less than x character

Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

How to create an email form that can send email using html

Short answer, you can't.

HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

What's the correct way to communicate between controllers in AngularJS?

Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.

I would suggest to use a service. Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419.

Basic idea - register a pubsub/event bus as a service. Then inject that eventbus where ever you need to subscribe or publish events/topics.

How can I get the content of CKEditor using JQuery?

Now that jQuery adapter exists, this answer needs to be updated:

Say you initiated the editor with $('.ckeditor').ckeditor(opt) then you get the value with $('.ckeditor').val()

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

regex pattern to match the end of a string

Use following pattern:

/([^/]+)$

How many threads is too many?

I've written a number of heavily multi-threaded apps. I generally allow the number of potential threads to be specified by a configuration file. When I've tuned for specific customers, I've set the number high enough that my utilization of the all the CPU cores was pretty high, but not so high that I ran into memory problems (these were 32-bit operating systems at the time).

Put differently, once you reach some bottleneck be it CPU, database throughput, disk throughput, etc, adding more threads won't increase the overall performance. But until you hit that point, add more threads!

Note that this assumes the system(s) in question are dedicated to your app, and you don't have to play nicely (avoid starving) other apps.

Array from dictionary keys in swift

extension Array {
    public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
        var dict = [Key:Element]()
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

How to remove leading and trailing whitespace in a MySQL field?

A general answer that I composed from your answers and from other links and it worked for me and I wrote it in a comment is:

 UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));

etc.

Because trim() doesn't remove all the white spaces so it's better to replace all the white spaces u want and than trim it.

Hope I could help you with sharing my answer :)

Error: The type exists in both directories

In my case, I have to items with same name but different extensions in my project. One was accountRep.aspx and the other accountRep.rpt made by Crystal Report. Problem solved when I changed accountRep.rpt to accountReport.rpt

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
> 

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131

How to launch an EXE from Web page (asp.net)

Did you try a UNC share?

\\server\share\foo.exe

Have bash script answer interactive prompts

In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh

I was needing to answer some questions for a doctrine schema exporter so my file looked like this.

-- This is an example only --

php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format`                                     1
`#Would you like to change the setup configuration before exporting`        y
`#Log to console`                                                           y
`#Log file`                                                                 testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]`                                          y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF

The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).

to run the script simply be in the directory you want and run 'sh autocomplete.sh' in terminal.

In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.

My example just shows how this can be done with comments also using the ` character so you remember what each step is.

Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!

Hope this helps someone out.

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

Is it possible to find out the users who have checked out my project on GitHub?

Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

How do I assert my exception message with JUnit Test annotation?

I would prefer AssertJ for this.

        assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(() -> {
            // method call
        }).withMessage("My message");

How to use a BackgroundWorker?

You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

Read a HTML file into a string variable in memory

Use System.IO.File.ReadAllText(fileName)

Redirect using AngularJS

Don't forget to inject $location into controller.

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

How do you log content of a JSON object in Node.js?

console.dir() is the most direct way.

Compile to a stand-alone executable (.exe) in Visual Studio

I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.

But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.

Can I write or modify data on an RFID tag?

It depends on the type of chip you are using, but nowerdays most chips you can write. It also depends on how much power you give your RFID device. To read you dont need allot of power and very little line of sight. To right you need them full insight and longer insight

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

The IN clause describes a set of values, and sets do not have order.

Your solution with a join and then ordering on the display_order column is the most nearly correct solution; anything else is probably a DBMS-specific hack (or is doing some stuff with the OLAP functions in standard SQL). Certainly, the join is the most nearly portable solution (though generating the data with the display_order values may be problematic). Note that you may need to select the ordering columns; that used to be a requirement in standard SQL, though I believe it was relaxed as a rule a while ago (maybe as long ago as SQL-92).

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How to run shell script on host from docker container?

If you are not worried about security and you're simply looking to start a docker container on the host from within another docker container like the OP, you can share the docker server running on the host with the docker container by sharing it's listen socket.

Please see https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface and see if your personal risk tolerance allows this for this particular application.

You can do this by adding the following volume args to your start command

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

or by sharing /var/run/docker.sock within your docker compose file like this:

version: '3'

services:
   ci:
      command: ...
      image: ...
      volumes
         - /var/run/docker.sock:/var/run/docker.sock

When you run the docker start command within your docker container, the docker server running on your host will see the request and provision the sibling container.

credit: http://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

How do I filter query objects by date range in Django?

You can use django's filter with datetime.date objects:

import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
                                sampledate__lte=datetime.date(2011, 1, 31))

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Can I execute a function after setState is finished updating?

With hooks in React 16.8 onward, it's easy to do this with useEffect

I've created a CodeSandbox to demonstrate this.

useEffect(() => {
  // code to be run when state variables in
  // dependency array changes
}, [stateVariables, thatShould, triggerChange])

Basically, useEffect synchronises with state changes and this can be used to render the canvas

import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";

export default function App() {
  const [rows, setRows] = useState(10);
  const [columns, setColumns] = useState(10);
  let stage = useRef()

  useEffect(() => {
    stage.current = new Stage("canvas");
    var rectangles = [];
    var rectangle;
    //Rows
    for (var x = 0; x < rows; x++) {
      // Columns
      for (var y = 0; y < columns; y++) {
        var color = "Green";
        rectangle = new Shape();
        rectangle.graphics.beginFill(color);
        rectangle.graphics.drawRect(0, 0, 32, 44);
        rectangle.x = y * 33;
        rectangle.y = x * 45;

        stage.current.addChild(rectangle);

        var id = rectangle.x + "_" + rectangle.y;
        rectangles[id] = rectangle;
      }
    }
    stage.current.update();
  }, [rows, columns]);

  return (
    <div>
      <div className="canvas-wrapper">
        <canvas id="canvas" width="400" height="300"></canvas>
        <p>Rows: {rows}</p>
        <p>Columns: {columns}</p>
      </div>
      <div className="array-form">
        <form>
          <label>Number of Rows</label>
          <select
            id="numRows"
            value={rows}
            onChange={(e) => setRows(e.target.value)}
          >
            {getOptions()}
          </select>
          <label>Number of Columns</label>
          <select
            id="numCols"
            value={columns}
            onChange={(e) => setColumns(e.target.value)}
          >
            {getOptions()}
          </select>
        </form>
      </div>
    </div>
  );
}

const getOptions = () => {
  const options = [1, 2, 5, 10, 12, 15, 20];
  return (
    <>
      {options.map((option) => (
        <option key={option} value={option}>
          {option}
        </option>
      ))}
    </>
  );
};

how to add background image to activity?

You can set the "background image" to an activity by setting android:background xml attributes as followings:

(Here, for example, Take a LinearLayout for an activity and setting a background image for the layout(i.e. indirectly to an activity))

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" 
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:background="@drawable/icon">
 </LinearLayout>

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

Open File in Another Directory (Python)

from pathlib import Path

data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)
print(f.read())

compare differences between two tables in mysql

You can construct the intersection manually using UNION. It's easy if you have some unique field in both tables, e.g. ID:

SELECT * FROM T1
WHERE ID NOT IN (SELECT ID FROM T2)

UNION

SELECT * FROM T2
WHERE ID NOT IN (SELECT ID FROM T1)

If you don't have a unique value, you can still expand the above code to check for all fields instead of just the ID, and use AND to connect them (e.g. ID NOT IN(...) AND OTHER_FIELD NOT IN(...) etc)

Datatable date sorting dd/mm/yyyy issue

in php or js just pass an array and use orthogonal, like:

$var[0][0] = "like as u wish, 30/12/2015 or something else";
$var[0][1] = strtotime($your_date_variable);

and, in datatable...

$('#data-table-contas_pagar').dataTable({
    "columnDefs": [
        {"targets":[0],"data": [0],"render": {"_": [0],"sort": [1]}}
    ]
});

how to redirect to home page

maybe

var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];

is what you're looking for?

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Android update activity UI from service

Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        //process results or update UI
    }
}

Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);

What do multiple arrow functions mean in javascript?

A general tip , if you get confused by any of new JS syntax and how it will compile , you can check babel. For example copying your code in babel and selecting the es2015 preset will give an output like this

handleChange = function handleChange(field) {
 return function (e) {
 e.preventDefault();
  // Do something here
   };
 };

babel

What are some great online database modeling tools?

I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.

How do I set a checkbox in razor view?

<input type="checkbox" @( Model.Checked == true ? "checked" : "" ) />

Git: How to rebase to a specific commit?

I've used a mixture of solutions described above:

$ git branch temp <specific sha1>
$ git rebase --onto temp master topic
$ git branch -d temp

I found it much easier to read and understand. The accepted solution lead me to a merge conflict (too lazy to fix by hand):

$ git rebase temp
First, rewinding head to replay your work on top of it...
Applying: <git comment>
Using index info to reconstruct a base tree...
M       pom.xml
.git/rebase-apply/patch:10: trailing whitespace.
    <some code>
.git/rebase-apply/patch:17: trailing whitespace.
        <some other code>
warning: 2 lines add whitespace errors.
Falling back to patching base and 3-way merge...
Auto-merging pom.xml
CONFLICT (content): Merge conflict in pom.xml
error: Failed to merge in the changes.
Patch failed at 0001 <git comment>
The copy of the patch that failed is found in: .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

Typescript ReferenceError: exports is not defined

For some ASP.NET projects import and export may not be used at all in your Typescripts.

The question's error showed up when I attempted to do so and I only discovered later that I just needed to add the generated JS script to the View like so:

<script src="~/scripts/js/[GENERATED_FILE].Index.js" asp-append-version="true"></script>

Unsupported major.minor version 52.0

You need to upgrade your Java version to Java 8.

Download latest Java archive

Download latest Java SE Development Kit 8 release from its official download page or use following commands to download from the shell.

For 64 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-x64.tar.gz"

 # tar xzf jdk-8u51-linux-x64.tar.gz

For 32 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-i586.tar.gz"

  # tar xzf jdk-8u51-linux-i586.tar.gz

Note: If the above wget command doesn’t not work for you, watch this example video to download the Java source archive using the terminal.

Install Java with alternatives

After extracting the archive file, use the alternatives command to install it. The alternatives command is available in the chkconfig package.

 # cd /opt/jdk1.8.0_51/

 # alternatives --install /usr/bin/java java /opt/jdk1.8.0_51/bin/java 2

 # alternatives --config java

At this point Java 8 has been successfully installed on your system. We also recommend to setup javac and jar commands path using alternatives:

 # alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_51/bin/jar 2

 # alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_51/bin/javac 2

 # alternatives --set jar /opt/jdk1.8.0_51/bin/jar

 # alternatives --set javac /opt/jdk1.8.0_51/bin/javac

Check installed Java version

Check the installed version of Java using the following command.

root@tecadmin ~# java -version

java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

Configuring Environment Variables

Most of Java-based applications use environment variables to work. Set the Java environment variables using the following commands:

Setup JAVA_HOME Variable

# export JAVA_HOME=/opt/jdk1.8.0_51
Setup JRE_HOME Variable

# export JRE_HOME=$JAVA_HOME/jre
Setup PATH Variable

# export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

Note that the change to the PATH variable put the new Java bin folders first so that they override any existing java/bins in the path. It is a bit sloppy to leave two java/bin folders in your path so you should be advised to clean those up as a separate task.

Also, put all above environment variables in the /etc/environment file for auto loading on system boot.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

SQL update query using joins

You can specify additional tables used in determining how and what to update with the "FROM " clause in the UPDATE statement, like this:

update item_master
set mf_item_number = (some value)
from 
   group_master as gm
   join Manufacturar_Master as mm ON ........
where
 .... (your conditions here)

In the WHERE clause, you need to provide the conditions and join operations to bind these tables together.

Marc

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

I've seen these particular exceptions related to Complex DataType issues, see the following post if you're passing around collections or enums:

Complex Data Types

How to list all users in a Linux group?

Zed's implementation should probably be expanded to work on some of the other major UNIX.

Someone have access to Solaris or HP-UX hardware?; did not test those cases.

#!/usr/bin/perl
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Date:         12/30/2013
# Author:       William H. McCloskey, Jr.
# Changes:      Added logic to detect host type & tailor subset of getent (OSX)
# Attribution:
#   The logic for this script was directly lifted from Zed Pobre's work.
#     See below for Copyright notice.
#   The idea to use dscl to emulate a subset of the now defunct getent on OSX
#     came from
#       http://zzamboni.org/\
#         brt/2008/01/21/how-to-emulate-unix-getent-with-macosxs-dscl/
#     with an example implementation lifted from
#       https://github.com/petere/getent-osx/blob/master/getent
#
# Copyright © 2010-2013 by Zed Pobre ([email protected] or [email protected])
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#

use strict; use warnings;

$ENV{"PATH"} = "/usr/bin:/bin";

# Only run on supported $os:
my $os;
($os)=(`uname -a` =~ /^([\w-]+)/);
unless ($os =~ /(HU-UX|SunOS|Linux|Darwin)/)
    {die "\$getent or equiv. does not exist:  Cannot run on $os\n";}

my $wantedgroup = shift;

my %groupmembers;

my @users;

# Acquire the list of @users based on what is available on this OS:
if ($os =~ /(SunOS|Linux|HP-UX)/) {
    #HP-UX & Solaris assumed to be like Linux; they have not been tested.
    my $usertext = `getent passwd`;
    @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
};
if ($os =~ /Darwin/) {
    @users = `dscl . -ls /Users`;
    chop @users;
}

# Now just do what Zed did - thanks Zed.
foreach my $userid (@users)
{
    my $usergrouptext = `id -Gn $userid`;
    my @grouplist = split(' ',$usergrouptext);

    foreach my $group (@grouplist)
    {
        $groupmembers{$group}->{$userid} = 1;
    }
}

if($wantedgroup)
{
    print_group_members($wantedgroup);
}
else
{
    foreach my $group (sort keys %groupmembers)
    {
        print "Group ",$group," has the following members:\n";
        print_group_members($group);
        print "\n";
    }
}

sub print_group_members
{
    my ($group) = @_;
    return unless $group;

    foreach my $member (sort keys %{$groupmembers{$group}})
    {
        print $member,"\n";
    }
}

If there is a better way to share this suggestion, please let me know; I considered many ways, and this is what I came up with.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

No need to do the loop, and using just standard Java library classes:

protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
  if (length > 0) {
    char[] array = new char[length];
    Arrays.fill(array, charToFill);
    return new String(array);
  }
  return "";
}

As you can see, I also added suitable code for the length == 0 case.

NavigationBar bar, tint, and title text color in iOS 8

Swift up through Swift 3.2 (not Swift 4.0)

    self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationController?.navigationBar.largeTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

    // unconfirmed but I assume this works:
    self.navigationController?.navigationBar.barTintColor = UIColor.white
    self.navigationController?.navigationBar.barStyle = UIBarStyle.black

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Used to face the same problem. The reason was in incorrect context passing to AlertDialog.Builder(here). use like AlertDialog.Builder(Homeactivity.this)

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

Is there any way to set environment variables in Visual Studio Code?

For more advanced Go language scenarios, you can load an environment file, like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch", 
      "mode": "debug",
      "remotePath": "",
      "port": 2345,
      "host": "127.0.0.1",
      "program": "${workspaceFolder}",
      "envFile": "${workspaceFolder}/.env",
      "args": [], 
      "showLog": true
    }
  ]
}

Place the .env file in your folder and add vars like this:

KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'

Details: https://medium.com/@reuvenharrison/using-visual-studio-code-to-debug-a-go-program-with-environment-variables-523fea268271

how to refresh Select2 dropdown menu after ajax loading different content?

It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.

$('#state').trigger('change.select2'); // Notify only Select2 of changes

How to add jQuery to an HTML page?

You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

Parse usable Street Address, City, State, Zip from a string

using google API

$d=str_replace(" ", "+", $address_url);
$completeurl ="http://maps.googleapis.com/maps/api/geocode/xml?address=".$d."&sensor=true"; 
$phpobject = simplexml_load_file($completeurl);
print_r($phpobject);

Run / Open VSCode from Mac Terminal

To set it up, launch VS Code. Then open the Command Palette (??P) and type shell command to find the Shell Command: Install 'code' command in PATH command.enter image description here

https://code.visualstudio.com/docs/setup/mac

Zoom to fit all markers in Mapbox or Leaflet

You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!

_x000D_
_x000D_
//Group1_x000D_
m1=L.marker([7.11, -70.11]);_x000D_
m2=L.marker([7.33, -70.33]);_x000D_
m3=L.marker([7.55, -70.55]);_x000D_
fg1=L.featureGroup([m1,m2,m3]);_x000D_
_x000D_
//Group2_x000D_
m4=L.marker([3.11, -75.11]);_x000D_
m5=L.marker([3.33, -75.33]);_x000D_
m6=L.marker([3.55, -75.55]);_x000D_
fg2=L.featureGroup([m4,m5,m6]);_x000D_
_x000D_
//BaseMap_x000D_
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');_x000D_
var map = L.map('map', {_x000D_
  center: [3, -70],_x000D_
  zoom: 4,_x000D_
  layers: [baseLayer, fg1, fg2]_x000D_
});_x000D_
_x000D_
//locate group 1_x000D_
function LocateOne() {_x000D_
    LocateAllFeatures(map, fg1);_x000D_
}_x000D_
_x000D_
function LocateAll() {_x000D_
    LocateAllFeatures(map, [fg1,fg2]);_x000D_
}_x000D_
_x000D_
//Locate the features_x000D_
function LocateAllFeatures(iobMap, iobFeatureGroup) {_x000D_
  if(Array.isArray(iobFeatureGroup)){   _x000D_
   var obBounds = L.latLngBounds();_x000D_
   for (var i = 0; i < iobFeatureGroup.length; i++) {_x000D_
    obBounds.extend(iobFeatureGroup[i].getBounds());_x000D_
   }_x000D_
   iobMap.fitBounds(obBounds);   _x000D_
  } else {_x000D_
   iobMap.fitBounds(iobFeatureGroup.getBounds());_x000D_
  }_x000D_
}
_x000D_
.mymap{_x000D_
  height: 300px;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>_x000D_
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="map" class="mymap"></div>_x000D_
<button onclick="LocateOne()">locate group 1</button>_x000D_
<button onclick="LocateAll()">locate All</button>
_x000D_
_x000D_
_x000D_

Bootstrap Collapse not Collapsing

You need jQuery see bootstrap's basic template

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

@Autowired and static method

What you can do is @Autowired a setter method and have it set a new static field.

public class Boo {
    @Autowired
    Foo foo;

    static Foo staticFoo;   

    @Autowired
    public void setStaticFoo(Foo foo) {
        Boo.staticFoo = foo;
    }

    public static void randomMethod() {
         staticFoo.doStuff();
    }
}

When the bean gets processed, Spring will inject a Foo implementation instance into the instance field foo. It will then also inject the same Foo instance into the setStaticFoo() argument list, which will be used to set the static field.

This is a terrible workaround and will fail if you try to use randomMethod() before Spring has processed an instance of Boo.

ASP.NET Setting width of DataBound column in GridView

This is going to work for all situations while working with width.

`<asp:TemplateField HeaderText="DATE">
   <ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# Bind("date") %>' Width="100px"></asp:Label>
   </ItemTemplate>
  </asp:TemplateField>`

Java: how do I check if a Date is within a certain range?

That's the correct way. Calendars work the same way. The best I could offer you (based on your example) is this:

boolean isWithinRange(Date testDate) {
    return testDate.getTime() >= startDate.getTime() &&
             testDate.getTime() <= endDate.getTime();
}

Date.getTime() returns the number of milliseconds since 1/1/1970 00:00:00 GMT, and is a long so it's easily comparable.

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

How to set a default row for a query that returns no rows?

One table scan method using a left join from defaults to actuals:

CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))

INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-2')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-3')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-2')

DECLARE @k AS int
SET @k = 0

WHILE @k < 3
    BEGIN
        SELECT  @k AS k
               ,COALESCE(ActualValue, DefaultValue) AS [Value]
        FROM    (
                 SELECT 'DefaultValue' AS DefaultValue
                ) AS Defaults
        LEFT JOIN (
                   SELECT   val AS ActualValue
                   FROM     [stackoverflow-285666]
                   WHERE    k = @k
                  ) AS [Values]
                ON 1 = 1

        SET @k = @k + 1
    END

DROP TABLE [stackoverflow-285666]

Gives output:

k           Value
----------- ------------
0           DefaultValue

k           Value
----------- ------------
1           1-1
1           1-2
1           1-3

k           Value
----------- ------------
2           2-1
2           2-2

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

Regex lookahead, lookbehind and atomic groups

Examples

Given the string foobarbarfoo:

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)

You can also combine them:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

  • (foo|foot)s applied to foots will:

    1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
    2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

Some resources

Online testers

Android : How to read file in bytes?

here it's a simple:

File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Add permission in manifest.xml:

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

Maven Unable to locate the Javac Compiler in:

If you we are doing all above steps that may be confused and our problem is just missing tools.jre so just add tools.jre by the following steps and problem is solved.

Step 1 : In eclipse go to Windows -> preferences

Step 2 : Java -> Installed JREs (Double click on it)

Step 3 : Click Edit button -> Click Add External JARs

Step 4 : Now select tools.jar path

now apply changes and it works fine.

Here is screenshoot

C# Regex for Guid

This one is quite simple and does not require a delegate as you say.

resultString = Regex.Replace(subjectString, 
     @"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$", 
     "'$0'");

This matches the following styles, which are all equivalent and acceptable formats for a GUID.

ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)

Update 1

@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.

This can be avoided by regex conditionals which are broadly supported.

Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)

The regex that follows Will match

{123}
(123)
123

And will not match

{123)
(123}
{123
(123
123}
123)

Regex:

^({)?(\()?\d+(?(1)})(?(2)\))$

The solutions is simplified to match only numbers to show in a more clear way what is required if needed.

Calculating how many days are between two dates in DB2?

values timestampdiff (16, char( 
    timestamp(current timestamp + 1 year + 2 month - 3 day)- 
    timestamp(current timestamp)))
1
=
422



values timestampdiff (16, char( 
    timestamp('2012-03-08-00.00.00')- 
    timestamp('2011-12-08-00.00.00')))
1
=
90

---------- EDIT BY galador

SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'

EDIT

As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:

SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00 
WHERE CHSTAT = '05';

Root password inside a Docker container

To create/change a root password in a running container

docker exec -itu root {containerName} passwd

Postman - How to see request with headers and body data with variables substituted

Update 2018-12-12 - Chrome App v Chrome Plugin - Most recent updates at top

With the deprecation of the Postman Chrome App, assuming that you are now using the Postman Native App, the options are now:

  1. Hover over variables with mouse
  2. Generate "Code" button/link
  3. Postman Console

See below for full details on each option.

Personally, I still go for 2) Generate "Code" button/link as it allows me to see the variables without actually having to send.

Demo Request Demo Request

Demo Environment Demo Environment

1) Hover over variables with mouse Hover over variables with mouse

2) Generate "Code" button/link Generate "Code" button/link

3) Postman Console enter image description here

Update: 2016-06-03

Whilst the method described above does work, in practice, I now normally use the "Generate Code" link on the Postman Request screen. The generated code, no matter what code language you choose, contains the substituted variables. Hitting the "Generate Code" link is just faster, additionally, you can see the substituted variables without actually making the request.

Original Answer below

To see the substituted variables in the Headers and Body, you need to use Chrome Developer tools. To enable Chrome Developer Tools from within Postman do the following, as per http://blog.getpostman.com/2015/06/13/debugging-postman-requests/.

I have copied the instructions from the link above in case the link gets broken in the future:

  1. Type chrome://flags inside your Chrome URL window

  2. Search for “packed” or try to find the “Enable debugging for packed apps”

  3. Enable the setting

  4. Restart Chrome

You can access the Developer Tools window by right clicking anywhere inside Postman and selecting “inspect element”. You can also go to chrome://inspect/#apps and then click “inspect” just below requester.html under the Postman heading.

Once enabled, you can use the Network Tools tab for even more information on your requests or the console while writing test scripts. If something goes wrong with your test scripts, it’ll show up here.

Are there any standard exit status codes in Linux?

8 bits of the return code and 8 bits of the number of the killing signal are mixed into a single value on the return from wait(2) & co..

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>

int main() {
    int status;

    pid_t child = fork();
    if (child <= 0)
        exit(42);
    waitpid(child, &status, 0);
    if (WIFEXITED(status))
        printf("first child exited with %u\n", WEXITSTATUS(status));
    /* prints: "first child exited with 42" */

    child = fork();
    if (child <= 0)
        kill(getpid(), SIGSEGV);
    waitpid(child, &status, 0);
    if (WIFSIGNALED(status))
        printf("second child died with %u\n", WTERMSIG(status));
    /* prints: "second child died with 11" */
}

How are you determining the exit status? Traditionally, the shell only stores an 8-bit return code, but sets the high bit if the process was abnormally terminated.

$ sh -c 'exit 42'; echo $?
42
$ sh -c 'kill -SEGV $$'; echo $?
Segmentation fault
139
$ expr 139 - 128
11

If you're seeing anything other than this, then the program probably has a SIGSEGV signal handler which then calls exit normally, so it isn't actually getting killed by the signal. (Programs can chose to handle any signals aside from SIGKILL and SIGSTOP.)

Closing a Userform with Unload Me doesn't work

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

Soft Edges using CSS?

Another option is to use one of my personal favorite CSS tools: box-shadow.

A box shadow is really a drop-shadow on the node. It looks like this:

-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);

The arguments are:

1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect.  0 means no blur.
color: The color of the shadow.

So, you could leave your current design, and add a box-shadow like:

box-shadow: 0px -2px 2px rgba(34,34,34,0.6);

This should give you a 'blurry' top-edge.

This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Adding data attribute to DOM

to get the text from a

<option value="1" data-sigla="AC">Acre</option>

uf = $("#selectestado option:selected").attr('data-sigla');

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

Spring Data JPA findOne() change to Optional how to use this?

Optional api provides methods for getting the values. You can check isPresent() for the presence of the value and then make a call to get() or you can make a call to get() chained with orElse() and provide a default value.

The last thing you can try doing is using @Query() over a custom method.

Prepend text to beginning of string

You can use

var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)

Remove Style on Element

You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).

var element = document.getElementById('sample_id');

element.style.width = null;
element.style.height = null;

For more information, you can refer to HTMLElement.style documentation on MDN.

Node.js - Maximum call stack size exceeded

Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.

Though V8 makes available the --max_old_space_size option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.

It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.

Getting the Facebook like/share count for a given URL

Your question is quite old and Facebook has depreciated FQL now but what you want can still be done using this utility: Facebook Analytics. However you will find that if you want details about who is liking or commenting it will take a long time to get. This is because Facebook only gives a very small chunk of data at a time and a lot of paging is required in order to get everything.

How to convert std::string to LPCWSTR in C++ (Unicode)

The solution is actually a lot easier than any of the other suggestions:

std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();

Best of all, it's platform independent.

Get total number of items on Json object?

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

TypeScript error TS1005: ';' expected (II)

If you're getting error TS1005: 'finally' expected., it means you forgot to implement catch after try. Generally, it means the syntax you attempted to use was incorrect.

android: how to use getApplication and getApplicationContext from non activity / service class

Either pass in a Context (so you can access resources), or make the helper methods static.

Pointers, smart pointers or shared pointers?

To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.

VARCHAR to DECIMAL

In case you need to ROUND the result, not truncate, can use this:

select convert(decimal(38,4), round(convert(decimal(38,10), '123456789.1234567'),4))

This will return the following:

'123456789.1235' for '123456789.1234567'
'123456789.1234' for '123456789.1234467'

Incrementing a variable inside a Bash loop

USCOUNTER=$(grep -c "^US " "$FILE")

(HTML) Download a PDF file instead of opening them in browser when clicked

As the html5 way (my previous answer) is not available in all browsers, heres another slightly hack way.

This solution requires you are serving the intended file from same domain, OR has CORS permission.

  1. First download the content of the file via XMLHttpRequest(Ajax).
  2. Then make a data URI by base64 encoding the content of the file and set media-type to application/octet-stream. Result should look like

data:application/octet-stream;base64,SGVsbG8sIFdvcmxkIQ%3D%3D

Now set location.href = data. This will cause the browser to download the file. Unfortunately you can't set file name or extension this way. Fiddling with the media-type could yield something.

See details: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

"elseif" syntax in JavaScript

if ( 100 < 500 ) {
   //any action
}
else if ( 100 > 500 ){
   //any another action
}

Easy, use space

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

Open youtube video in Fancybox jquery

I started by using the answers here, but modified it to use YouTube's new iframe embedding...

$('a.more').on('click', function(event) {
    event.preventDefault();
    $.fancybox({
        'type' : 'iframe',
        // hide the related video suggestions and autoplay the video
        'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
        'overlayShow' : true,
        'centerOnScroll' : true,
        'speedIn' : 100,
        'speedOut' : 50,
        'width' : 640,
        'height' : 480
    });
});

Rails: How do I create a default value for attributes in Rails activerecord's model?

You can do it without writing any code at all :) You just need to set the default value for the column in the database. You can do this in your migrations. For example:

create_table :projects do |t|
  t.string :status, :null => false, :default => 'P'
  ...
  t.timestamps
end

Hope that helps.

In an array of objects, fastest way to find the index of an object whose attributes match a search

var indices = [];
var IDs = [0, 1, 2, 3, 4];

for(var i = 0, len = array.length; i < len; i++) {
    for(var j = 0; j < IDs.length; j++) {
        if(array[i].id == ID) indices.push(i);
    }
}

How to stop asynctask thread in android?

You can't just kill asynctask immediately. In order it to stop you should first cancel it:

task.cancel(true);

and than in asynctask's doInBackground() method check if it's already cancelled:

isCancelled()

and if it is, stop executing it manually.

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

Select Tag Helper in ASP.NET Core MVC

You can use below code for multiple select:

<select asp-for="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

You can also use:

<select id="EmployeeId" name="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.