Programs & Examples On #Calibration

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

You just need to keep Program Files in double quote & rest of the command don't need any quote.

C:\"Program Files"\IAR Systems\Embedded Workbench 7.0\430\bin\icc430.exe F:\CP00 .....

Store a closure as a variable in Swift

I've provide an example not sure if this is what you're after.

var completionHandler: (_ value: Float) -> ()

func printFloat(value: Float) {
    print(value)
}

completionHandler = printFloat

completionHandler(5)

It simply prints 5 using the completionHandler variable declared.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Opening PDF String in new window with javascript

I realize this is a pretty old question, but I had the same thing come up today and came up with the following solution:

doSomethingToRequestData().then(function(downloadedFile) {
  // create a download anchor tag
  var downloadLink      = document.createElement('a');
  downloadLink.target   = '_blank';
  downloadLink.download = 'name_to_give_saved_file.pdf';

  // convert downloaded data to a Blob
  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });

  // create an object URL from the Blob
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(blob);

  // set object URL as the anchor's href
  downloadLink.href = downloadUrl;

  // append the anchor to document body
  document.body.appendChild(downloadLink);

  // fire a click event on the anchor
  downloadLink.click();

  // cleanup: remove element and revoke object URL
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
});

best practice to generate random token for forgot password

You can also use DEV_RANDOM, where 128 = 1/2 the generated token length. Code below generates 256 token.

$token = bin2hex(mcrypt_create_iv(128, MCRYPT_DEV_RANDOM));

jQuery checkbox checked state changed event

This is the solution to find is the checkbox is checked or not. Use the #prop() function//

$("#c_checkbox").on('change', function () {
                    if ($(this).prop('checked')) {
                        // do stuff//
                    }
                });

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

Resource u'tokenizers/punkt/english.pickle' not found

From the shell you can execute:

sudo python -m nltk.downloader punkt 

If you want to install the popular NLTK corpora/models:

sudo python -m nltk.downloader popular

If you want to install all NLTK corpora/models:

sudo python -m nltk.downloader all

To list the resources you have downloaded:

python -c 'import os; import nltk; print os.listdir(nltk.data.find("corpora"))'
python -c 'import os; import nltk; print os.listdir(nltk.data.find("tokenizers"))'

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

<img>: Unsafe value used in a resource URL context

Use Safe Pipe to fix it.

  • Create a safe pipe if u haven't any.

    ng g pipe safe

  • add Safe pipe in app.module.ts

    declarations: [SafePipe]

  • declare safe pipe in your ts

Import Dom Sanitizer and Safe Pipe to access url safely

import { Pipe, PipeTransform} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
  • Add safe with src url

    <img width="900" height="500" [src]="link | safe"/>

array filter in python?

>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])

Passing bash variable to jq

Little unrelated but I will still put it here, For other practical purposes shell variables can be used as -

value=10
jq  '."key" = "'"$value"'"' file.json

How can I create a product key for my C# application?

I'm going to piggyback a bit on @frankodwyer's great answer and dig a little deeper into online-based licensing. I'm the founder of Keygen, a licensing REST API built for developers.

Since you mentioned wanting 2 "types" of licenses for your application, i.e. a "full version" and a "trial version", we can simplify that and use a feature license model where you license specific features of your application (in this case, there's a "full" feature-set and a "trial" feature-set).

To start off, we could create 2 license types (called policies in Keygen) and whenever a user registers an account you can generate a "trial" license for them to start out (the "trial" license implements our "trial" feature policy), which you can use to do various checks within the app e.g. can user use Trial-Feature-A and Trial-Feature-B.

And building on that, whenever a user purchases your app (whether you're using PayPal, Stripe, etc.), you can generate a license implementing the "full" feature policy and associate it with the user's account. Now within your app you can check if the user has a "full" license that can do Pro-Feature-X and Pro-Feature-Y (by doing something like user.HasLicenseFor(FEATURE_POLICY_ID)).

I mentioned allowing your users to create user accounts—what do I mean by that? I've gone into this in detail in a couple other answers, but a quick rundown as to why I think this is a superior way to authenticate and identify your users:

  1. User accounts let you associate multiple licenses and multiple machines to a single user, giving you insight into your customer's behavior and to prompt them for "in-app purchases" i.e. purchasing your "full" version (kind of like mobile apps).
  2. We shouldn't require our customers to input long license keys, which are both tedious to input and hard to keep track of i.e. they get lost easily. (Try searching "lost license key" on Twitter!)
  3. Customers are accustomed to using an email/password; I think we should do what people are used to doing so that we can provide a good user experience (UX).

Of course, if you don't want to handle user accounts and you want your users to input license keys, that's completely fine (and Keygen supports doing that as well). I'm just offering another way to go about handling that aspect of licensing and hopefully provide a nice UX for your customers.

Finally since you also mentioned that you want to update these licenses annually, you can set a duration on your policies so that "full" licenses will expire after a year and "trial" licenses last say 2 weeks, requiring that your users purchase a new license after expiration.

I could dig in more, getting into associating machines with users and things like that, but I thought I'd try to keep this answer short and focus on simply licensing features to your users.

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I had this issue while working at the local Starbucks and I remembered that when I initially set up my database through Mongo Atlas. I set my IP address to be able to access the database. After looking through several threads, I changed my IP address on Atlas and the issue went away. Hope this helps someone.

Delegation: EventEmitter or Observable in Angular

I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.

What I think you are looking for is for a broadcast. Just that. And I found out this solution:

<app>
  <app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
       // This component bellow wants to know when a tab is selected
       // broadcast here is a property of app component
  <app-interested [broadcast]="broadcast"></app-interested>
</app>

 @Component class App {
   broadcast: EventEmitter<tab>;

   constructor() {
     this.broadcast = new EventEmitter<tab>();
   }

   onSelectedTab(tab) {
     this.broadcast.emit(tab)
   }    
 }

 @Component class AppInterestedComponent implements OnInit {
   broadcast: EventEmitter<Tab>();

   doSomethingWhenTab(tab){ 
      ...
    }     

   ngOnInit() {
     this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))
   }
 }

This is a full working example: https://plnkr.co/edit/xGVuFBOpk2GP0pRBImsE

C# catch a stack overflow exception

You can't. The CLR won't let you. A stack overflow is a fatal error and can't be recovered from.

DISTINCT for only one column

Try this:

SELECT ID, Email, ProductName, ProductModel FROM Products WHERE ID IN (SELECT MAX(ID) FROM Products GROUP BY Email)

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

All other answers may answer your query, but I faced same issue which was due to stray , which I added at the end of my json string like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf",
}

I finally got it working when I removed extra , like this:

{
 "key":"123sdf",
 "bus_number":"asd234sdf"
}

Hope this help! cheers.

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

From the help (if /?):

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following would NOT work because the del command needs to be terminated
by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

For people who have this problem today(to example to switch from 2.8.0 to 2.10.0), move to file gradle-wrapper.properties and set distributionUrl with the value you need. distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and dont forget to Sync after

Rename a dictionary key

In case of renaming all dictionary keys:

target_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
new_keys = ['k4','k5','k6']

for key,n_key in zip(target_dict.keys(), new_keys):
    target_dict[n_key] = target_dict.pop(key)

Reference an Element in a List of Tuples

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

Converting an int into a 4 byte char array (C)

Why would you need an intermediate cast to void * in C++ Because cpp doesn't allow direct conversion between pointers, you need to use reinterpret_cast or casting to void* does the thing.

How do I disable the security certificate check in Python requests

From the documentation:

requests can also ignore verifying the SSL certificate if you set verify to False.

>>> requests.get('https://kennethreitz.com', verify=False)
<Response [200]>

If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches requests and changes it so that verify=False is the default and suppresses the warning.

import warnings
import contextlib

import requests
from urllib3.exceptions import InsecureRequestWarning


old_merge_environment_settings = requests.Session.merge_environment_settings

@contextlib.contextmanager
def no_ssl_verification():
    opened_adapters = set()

    def merge_environment_settings(self, url, proxies, stream, verify, cert):
        # Verification happens only once per connection so we need to close
        # all the opened adapters once we're done. Otherwise, the effects of
        # verify=False persist beyond the end of this context manager.
        opened_adapters.add(self.get_adapter(url))

        settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
        settings['verify'] = False

        return settings

    requests.Session.merge_environment_settings = merge_environment_settings

    try:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', InsecureRequestWarning)
            yield
    finally:
        requests.Session.merge_environment_settings = old_merge_environment_settings

        for adapter in opened_adapters:
            try:
                adapter.close()
            except:
                pass

Here's how you use it:

with no_ssl_verification():
    requests.get('https://wrong.host.badssl.com/')
    print('It works')

    requests.get('https://wrong.host.badssl.com/', verify=True)
    print('Even if you try to force it to')

requests.get('https://wrong.host.badssl.com/', verify=False)
print('It resets back')

session = requests.Session()
session.verify = True

with no_ssl_verification():
    session.get('https://wrong.host.badssl.com/', verify=True)
    print('Works even here')

try:
    requests.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
    print('It breaks')

try:
    session.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
    print('It breaks here again')

Note that this code closes all open adapters that handled a patched request once you leave the context manager. This is because requests maintains a per-session connection pool and certificate validation happens only once per connection so unexpected things like this will happen:

>>> import requests
>>> session = requests.Session()
>>> session.get('https://wrong.host.badssl.com/', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>
>>> session.get('https://wrong.host.badssl.com/', verify=True)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>

AngularJS access parent scope from child controller

From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:

Parent:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

How to compare strings in Bash

The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

Space in Bash is so much important. So the following will work:

[ "$LINE" != "table_name" ] 

But the following won't:

["$LINE" != "table_name"] 

So please use as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

How can I stop Chrome from going into debug mode?

You've accidentally set "Pause on Exceptions" to all/uncaught exceptions.

Go to the "Sources" tab. At the bottom toolbar, toggle the button that looks like the pause symbol surrounded by a circle (4th button from the left) until the color of the circle turns black to turn it off.

How do you return the column names of a table?

I'm not sure if the syscolumns.colid value is the same as the 'ORDINAL_POSITION' value returned as part of sp_columns, but in what follows I am using it that way - hope I'm not misinforming...

Here's a slight variation on some of the other answers I've found - I use this because the 'position' or order of the column in the table is important in my application - I basically need to know 'What is column (n) called?'

sp_columns returns a whole bunch of extraneous stuff, and I'm handier with a select than T-SQL functions, so I went this route:

select    
  syscolumns.name, 
  syscolumns.colid    
from     
  sysobjects, syscolumns  
where 
  sysobjects.id = syscolumns.id and   
  sysobjects.xtype = 'u' and   
  sysobjects.name = '<YOUR_TABLE>' 
order by syscolumns.colid 

Integrating MySQL with Python in Windows

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.

JSON Post with Customized HTTPHeader Field

I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined. I am passing JSONWebToken as part of header.

.ajax({
    url: 'api/outletadd',
    type: 'post',
    data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
    headers: {
        authorization: storedJWT
    },
    dataType: 'json',
    success: function (data){
        alert("Outlet Created");
    },
    error: function (data){
        alert("Outlet Creation Failed, please try again.");        
    }

    });

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

Try this:

Declare @dt NVARCHAR(20)

Select 
    @dt = REPLACE(CONVERT(CHAR(15), SalesDate, 106),' ',' - ') 
FROM SalesTable

Pass a list to a function to act as multiple arguments

Yes, you can use the *args (splat) syntax:

function_that_needs_strings(*my_list)

where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

See the call expression documentation.

There is a keyword-parameter equivalent as well, using two stars:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments

Disabling contextual LOB creation as createClob() method threw error

Remove @Temporal annotations if you use it with java.sql.* classes.

Access denied for user 'homestead'@'localhost' (using password: YES)

i have find solution

  1. Go to your application root directory and open .env file (In ubuntu may be it’s hidden so press ctrl+h to show hidden files) in your editor and change database configuration setting. then save your .env file

  2. then restart your apache server/web server. and refresh your page and you have done

  3. If still issue try to run below command to clear the old configuration cache file.

This worked for me gl ...

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

What is the purpose of "pip install --user ..."?

Best way to is install virtualenv and not require the --user confusion. You will get more flexibility and not worry about clobbering the different python versions and projects everytime you pip install a package.

https://virtualenv.pypa.io/en/stable/

Multiline strings in VB.NET

You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with

 Dim a = My.Resources.Whatever_you_chose

How do I pull my project from github?

Git clone is the command you're looking for:

git clone [email protected]:username/repo.git

Update: And this is the official guide: https://help.github.com/articles/fork-a-repo

Take a look at: https://help.github.com/

It has really useful content

Returning an array using C

You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:

char* returnArrayPointer() 
{
static char array[SIZE];

// do something in your array here

return array; 
}

You can than use it without worrying about memory management.

int main() 
{
char* myArray = returnArrayPointer();
/* use your array here */
/* don't worry to free memory here */
}

In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!

DLL References in Visual C++

The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.

If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

Storage permission error in Marshmallow

if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Log.d(TAG, "Permission granted");
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    100);
        }

        fab.setOnClickListener(v -> {
            Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/*");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
                    b, "Title", null);
            Uri imageUri = Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            share.putExtra(Intent.EXTRA_TEXT, "Here is text");
            startActivity(Intent.createChooser(share, "Share via"));
        });

How to parse JSON in Kotlin?

Download the source of deme from here(Json parsing in android kotlin)

Add this dependency:

compile 'com.squareup.okhttp3:okhttp:3.8.1'

Call api function:

 fun run(url: String) {
    dialog.show()
    val request = Request.Builder()
            .url(url)
            .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            dialog.dismiss()

        }

        override fun onResponse(call: Call, response: Response) {
            var str_response = response.body()!!.string()
            val json_contact:JSONObject = JSONObject(str_response)

            var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")

            var i:Int = 0
            var size:Int = jsonarray_contacts.length()

            al_details= ArrayList();

            for (i in 0.. size-1) {
                var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)


                var model:Model= Model();
                model.id=json_objectdetail.getString("id")
                model.name=json_objectdetail.getString("name")
                model.email=json_objectdetail.getString("email")
                model.address=json_objectdetail.getString("address")
                model.gender=json_objectdetail.getString("gender")

                al_details.add(model)


            }

            runOnUiThread {
                //stuff that updates ui
                val obj_adapter : CustomAdapter
                obj_adapter = CustomAdapter(applicationContext,al_details)
                lv_details.adapter=obj_adapter
            }

            dialog.dismiss()

        }

    })

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

I know this is an older question, but I thought I would also post my solution:

  • Update your Chrome on your phone and on your PC.
  • Even if it says you have the latest driver for your device inside Device Manager, you may need an alternative. Google latest Samsung drivers and try updating your drivers.

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

How do I read a text file of about 2 GB?

Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools

node.js - request - How to "emitter.setMaxListeners()"?

This is how I solved the problem:

In main.js of the 'request' module I added one line:

Request.prototype.request = function () {
  var self = this
  self.setMaxListeners(0); // Added line

This defines unlimited listeners http://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners

In my code I set the 'maxRedirects' value explicitly:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};

Inserting code in this LaTeX document with indentation

You could also use the verbatim environment

\begin{verbatim}
your
code
example
\end{verbatim}

Nested lists python

Try this setup:

a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]

The first brackets reference which nested list you're accessing, the second pair references the item in that list.

What is the difference between require() and library()?

Here seems to be the difference on an already loaded package. While it is true that both require and library do not load the package. Library does a lot of other things before it checks and exits.

I would recommend removing "require" from the beginning of a function running 2mil times anyway, but if, for some reason I needed to keep it. require is technically a faster check.

microbenchmark(req = require(microbenchmark), lib = library(microbenchmark),times = 100000)
Unit: microseconds
 expr    min     lq      mean median     uq        max neval
  req  3.676  5.181  6.596968  5.655  6.177   9456.006 1e+05
  lib 17.192 19.887 27.302907 20.852 22.490 255665.881 1e+05

Hibernate Error executing DDL via JDBC Statement

I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.

What's the difference between abstraction and encapsulation?

Abstraction is one of the many benefits of Data Encapsulation. We can also say Data Encapsulation is one way to implement Abstraction.

what is right way to do API call in react js?

This discussion has been for a while and @Alexander T.'s answer provided a good guide to follow for newer of React like me. And I'm gonna share some additional know-hows about calling the same API multiple times to refresh the component, I think it's probably a common problem that newbie may face at the beginning.

componentWillReceiveProps(nextProps), from official documentation :

If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

We could conclude that here is the place we handle props from the parent component, have API calls, and update state.

Base on @Alexander T.'s example:

export default class UserList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {person: []};
  }

  componentDidMount() {
   //For our first load. 
   this.UserList(this.props.group); //maybe something like "groupOne"
  }

  componentWillReceiveProps(nextProps) {
    // Assuming parameter comes from url.
    // let group = window.location.toString().split("/")[*indexParameterLocated*];
    // this.UserList(group);

    // Assuming parameter comes from props that from parent component.
    let group = nextProps.group; // Maybe something like "groupTwo" 
    this.UserList(group);
  }

  UserList(group) {
    $.getJSON('https://randomuser.me/api/' + group)
      .then(({ results }) => this.setState({ person: results }));
  }

  render() {
    return (...)
  }
}

Update

componentWillReceiveProps() would be deprecated.

Here are only some methods (all of them in Doc) in the life cycle which I think would be related to deploying API in general case: enter image description here

By referring the diagram above:

  • Deploy API in componentDidMount()

    The proper scenario to have API call here is that the content (from the response of API) of this component will be static, componentDidMount() only fire once while the component is mounting, even new props are passed from parent component or have actions to lead re-rendering.
    The component do check difference to re-render but not re-mount.
    Quote from doc:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.


  • Deploy API in static getDerivedStateFromProps(nextProps, prevState)

We should notice that there are two kinds of component updating, setState() in current component would not lead this method to trigger, but re-rendering or new props from parent component do. We could found out that this method also fires while mounting.

This is a proper place to deploy API if we want to use the current component like a template, and the new parameters for API are props coming from parent component.
We receive a different response from API and return a new state here to change the content of this component.

For example:
We have a dropdown list for different Cars in the parent component, this component needs to show the details of the selected one.


  • Deploy API in componentDidUpdate(prevProps, prevState)

Differ from static getDerivedStateFromProps(), this method is invoked immediately after every rendering except the initial rendering. We could have API calling and render difference in one component.

Extend the previous example:
The component to show Car's details may contain a list of series of this car, if we want to check the 2013 production one, we may click or select or ... the list item to lead a first setState() to reflect this behavior (such as highlighting the list item) in this component, and in the following componentDidUpdate() we send our request with new parameters (state). After getting the response, we setState() again for rendering the different content of the Car details. To prevent the following componentDidUpdate() from causing the infinity loop, we need to compare the state by utilizing prevState at the beginning of this method to decide if we send the API and render the new content.

This method really could be utilized just like static getDerivedStateFromProps() with props, but need to handle the changes of props by utilizing prevProps. And we need to cooperate with componentDidMount() to handle the initial API call.

Quote from doc:

... This is also a good place to do network requests as long as you compare the current props to previous props ...

How do I append to a table in Lua

I'd personally make use of the table.insert function:

table.insert(a,"b");

This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

How to unapply a migration in ASP.NET Core with EF Core

To revert all the migrations which are applied to DB simply run:

update-database 0

It should be followed with running Remove-Migration as many times as there are migration files visible in the Migration directory. The command deletes the latest migration and also updates the snapshot.

XML parsing of a variable string in JavaScript

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

How to pass a value to razor variable from javascript variable?

here is my solution that works:

in my form i use:

@using (Html.BeginForm("RegisterOrder", "Account", FormMethod.Post, new { @class = "form", role = "form" }))
  {

   @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

   @Html.HiddenFor(m => m.quantity, new { id = "quantity", Value = 0 })

  }

in my file.js I get the quantity from a GET request and pass the variable as follows to the form:

    $http({
        method: 'Get',
        url: "https://xxxxxxx.azurewebsites.net/api/quantity/" + usr
    })
        .success(function (data){

            setQuantity(data.number);

            function setQuantity(number) {
                $('#quantity').val(number);
            }

        });

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

ascending/descending in LINQ - can one change the order via parameter?

In addition to the beautiful solution given by @Jon Skeet, I also needed ThenBy and ThenByDescending, so I am adding it based on his solution:

    public static IOrderedEnumerable<TSource> ThenByWithDirection<TSource, TKey>(
         this IOrderedEnumerable<TSource> source, 
         Func<TSource, TKey> keySelector,  
         bool descending)
    {
        return descending ? 
               source.ThenByDescending(keySelector) :
               source.ThenBy(keySelector);
    }

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Please follow the procedure to get rid of this problem:

$.ajax({
   url: 'https://your-api-endpoint',
   type: 'post',
   data: new formData(this),
   processData: false,
   contentType: false,
   success: function(response) {
      console.log(response)
   }
})

You have to use processData: false and contentType: false, these two lines. Your problem will be solved.

How to copy a char array in C?

As others have noted, strings are copied with strcpy() or its variants. In certain cases, you could use snprintf() as well.

You can only assign arrays the way you want as part of a structure assignment:

typedef struct { char a[18]; } array;
array array1 = { "abcdefg" };
array array2;

array2 = array1;

If your arrays are passed to a function, it will appear that you are allowed to assign them, but this is just an accident of the semantics. In C, an array will decay to a pointer type with the value of the address of the first member of the array, and this pointer is what gets passed. So, your array parameter in your function is really just a pointer. The assignment is just a pointer assignment:

void foo (char x[10], char y[10]) {
    x = y;    /* pointer assignment! */
    puts(x);
}

The array itself remains unchanged after returning from the function.

This "decay to pointer value" semantic for arrays is the reason that the assignment doesn't work. The l-value has the array type, but the r-value is the decayed pointer type, so the assignment is between incompatible types.

char array1[18] = "abcdefg";
char array2[18];
array2 = array1; /* fails because array1 becomes a pointer type,
                    but array2 is still an array type */

As to why the "decay to pointer value" semantic was introduced, this was to achieve a source code compatibility with the predecessor of C. You can read The Development of the C Language for details.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

To install PDT (PHP Development Tools) for PHP development environment is better in Eclipse. The following are the steps to install PDT in Eclipse (I'm considering version 3.7 (Indigo)):

  1. Open Eclipse (in my case Eclipse Indigo).
  2. Go to Help --> Install New Software...
  3. Expand the "Work with" drop down and select "Indigo - http://download.eclipse.org/releases/indigo".
  4. Expand "Programming Languages" from the list.
  5. Check PHP Development Tools (PDT) SDK Feature.
  6. Click "Next >" at the bottom and follow the further instruction of Eclipse.
  7. After successful installation of PDT: Go to Window --> Preferences and see the list as PHP at left panel.

What is the hamburger menu icon called and the three vertical dots icon called?

We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.

makefile:4: *** missing separator. Stop

Its pretty old question but still I would like say about one more option using vi/vim editor to visualize the tabs. If you have vi/vim installed then open a Makefile (e.g. vim Makefile) and enter :set list. This will show number of tabs inserted as below,

 %-linux: force$
^I@if [ "$(GCC_VERSION)" = "2.96" ] ; then \$
^I^Iecho ===== Generating build tree for legacy $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@ legacy; \$
^Ielse \$
^I^Iecho ===== Generating build tree for $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@; \$
^Ifi$
^Icd build-$@;make$

Replace "\\" with "\" in a string in C#

I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from

text2 = text1.Replace(@"\\", @"/");

to

text2 = text1.Replace(@"\", @"/");

and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.

ImportError: No module named pip

I downloaded pip binaries from here and it resolved the issue.

How do I round to the nearest 0.5?

I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:

The solution I came up with is the following:

//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10;  // NUMBER - Input Your Number here
var n:int = r * 10;   // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; //  NUMBER - Re-assemble the number

trace("ORG No: " + r);
trace("NEW No: " + d);

Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.

Good Luck!

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

How to get key names from JSON using jq

To get the keys on a deeper node in an JSON:

echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Should work in all cases:

SELECT regexp_replace(0.1234, '^(-?)([.,])', '\10\2') FROM dual

socket.emit() vs. socket.send()

With socket.emit you can register custom event like that:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

Socket.send does the same, but you don't register to 'news' but to message:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.send('hi');
});

client:

var socket = io.connect('http://localhost');
socket.on('message', function (message) {
  console.log(message);
});

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

You can see how iTunes does it by using Fiddler to follow the action when using the link: http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=80028216

  1. It downloads a js file
  2. On windows: the js file determines if iTunes was installed on the computer or not: looks for an activeX browser component if IE, or a browser plugin if FF
  3. If iTunes is installed then the browser is redirected to an URL with a special transport: itms://...
  4. The browser invokes the handler (provided by the iTunes exe). This includes starting up the exe if it is not already running.
  5. iTunes exe uses the rest of the special url to show a specific page to the user.

Note that the exe, when installed, installed URL protocol handlers for "itms" transport with the browsers.

Not a simple engineering project to duplicate, but definitely do-able. If you go ahead with this, please consider making the relevant software open source.

Good font for code presentations?

I'm personally very fond of Inconsolata

mysqldump data only

Best to dump to a compressed file

mysqldump --no-create-info -u username -hhostname -p dbname | gzip > /backupsql.gz

and to restore using pv apt-get install pv to monitor progress

pv backupsql.gz | gunzip | mysql -uusername -hhostip -p dbname

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

What is JSONP, and why was it created?

Before understanding JSONP, you need to know JSON format and XML. Currently the most frequently used data format on the web is XML, but XML is very complicated. It makes users inconvenient to process embedded in Web pages.

To make JavaScript can easily exchange data, even as the data processing program, we use the wording according to JavaScript objects and developed a simple data exchange format, which is JSON. JSON can be used as data, or as a JavaScript program.

JSON can be directly embedded in JavaScript, using them you can directly execute certain JSON program, but due to security constraints, the browser Sandbox mechanism disables cross-domain JSON code execution.

To make JSON can be passed after the execution, we developed a JSONP. JSONP bypass the security limits of the browser with JavaScript Callback functionality and the < script > tag.

So in short it explains what JSONP is, what problem it solves (when to use it).

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final").

When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.

Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.

libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)

This is for play 2.2.x. In previous versions there were some differences in the build files.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Programmatically go back to the previous fragment in the backstack

To elaborate on the other answers provided, this is my solution (placed in an Activity):

@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}

What is the proper REST response code for a valid request but an empty data?

TL;DR: Use 404

See This Blog. It explains it very well.

Summary of the blog's comments on 204:

  1. 204 No Content is not terribly useful as a response code for a browser (although according to the HTTP spec browsers do need to understand it as a 'don't change the view' response code).
  2. 204 No Content is however, very useful for ajax web services which may want to indicate success without having to return something. (Especially in cases like DELETE or POSTs that don't require feedback).

The answer, therefore, to your question is use 404 in your case. 204 is a specialized reponse code that you shouldn't often return to a browser in response to a GET.

The other response codes that are even less appropriate than 204 and 404:

  1. 200 should be returned with the body of whatever you successfully fetched. Not appropriate when the entity you're fetching doesn't exist.
  2. 202 is used when the server has begun work on an object but the object isn't fully ready yet. Certainly not the case here. You haven't begun, nor will you begin, construction of user 9 in response to a GET request. That breaks all sorts of rules.
  3. 400 is used in response to a poorly formatted HTTP request (for instance malformed http headers, incorrectly ordered segments, etc). This will almost certainly be handled by whatever framework you're using. You shouldn't have to deal with this unless you're writing your own server from scratch. Edit: Newer RFCs now allow for 400 to be used for semantically invalid requests.

Wikipedia's description of the HTTP status codes are particularly helpful. You can also see the definitions in the HTTP/1.1 RFC2616 document at www.w3.org

nodejs module.js:340 error: cannot find module

Try typing this into the Node command-line environment:

.load c:/users/laura/desktop/nodeTest.js.

It should work for what you're trying to do.

If you want to call the file directly, you'd have to have it in the root directory where your Node installation resides.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Try this:

tar -czf my.tar.gz dir/

But are you sure you are not compressing some .exe file or something? Maybe the problem is not with te compression, but with the files you are compressing?

How to search in an array with preg_match?

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

importing pyspark in python shell

To get rid of ImportError: No module named py4j.java_gateway, you need to add following lines:

import os
import sys


os.environ['SPARK_HOME'] = "D:\python\spark-1.4.1-bin-hadoop2.4"


sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python")
sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python\lib\py4j-0.8.2.1-src.zip")

try:
    from pyspark import SparkContext
    from pyspark import SparkConf

    print ("success")

except ImportError as e:
    print ("error importing spark modules", e)
    sys.exit(1)

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Get content of a DIV using JavaScript

simply you can use jquery plugin to get/set the content of the div.

var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );

for this you need to include jquery library.

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Twitter Bootstrap Responsive Background-Image inside Div

The way to do this is by using background-size so in your case:

background-size: 50% 50%;

or

You can set the width and the height of the elements to percentages as well

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Open fancybox from function

Make argument object extends from <a> , and use open function of fancybox in click event via delegate.

    var paramsFancy={
         'autoScale': true,
         'transitionIn': 'elastic',
         'transitionOut': 'elastic',
         'speedIn': 500,
         'speedOut': 300,
         'autoDimensions': true,
         'centerOnScroll': true,
         'href' : '#contentdiv'
      };

    $(document).delegate('a[href=#modalMine]','click',function(){
               /*Now you can call your function ,
   you can change fields of paramsFancy via this function */
                 myfunction(this);

                paramsFancy.href=$(this).attr('href');
                $.fancybox.open(paramsFancy);

    });

How do I request and receive user input in a .bat and use it to run a certain program?

i just do :

set /p input= yes or no
if %input%==yes echo you clicked yes
if %input%==no echo you clicked no
pause

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

Just do

openssl x509 -req -days 365 -in server.cer -signkey server.key -out server.crt

What is the opposite of evt.preventDefault();

function(evt) {evt.preventDefault();}

and its opposite

function(evt) {return true;}

cheers!

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

tl;dr Set the editor to something nicer, like Sublime or Atom

Here nice is used in the meaning of an editor you like or find more user friendly.

The underlying problem is that Git by default uses an editor that is too unintuitive to use for most people: Vim. Now, don't get me wrong, I love Vim, and while you could set some time aside (like a month) to learn Vim and try to understand why some people think Vim is the greatest editor in existence, there is a quicker way of fixing this problem :-)

The fix is not to memorize cryptic commands, like in the accepted answer, but configuring Git to use an editor that you like and understand! It's really as simple as configuring either of these options

  1. the git config setting core.editor (per project, or globally)
  2. the VISUAL or EDITOR environment variable (this works for other programs as well)

I'll cover the first option for a couple of popular editors, but GitHub has an excellent guide on this for many editors as well.

To use Atom

Straight from its docs, enter this in a terminal: git config --global core.editor "atom --wait"

Git normally wait for the editor command to finish, but since Atom forks to a background process immediately, this won't work, unless you give it the --wait option.

To use Sublime Text

For the same reasons as in the Atom case, you need a special flag to signal to the process that it shouldn't fork to the background:

git config --global core.editor "subl -n -w"

Detect if PHP session exists

Which method is used to check if SESSION exists or not? Answer:

isset($_SESSION['variable_name'])

Example:

isset($_SESSION['id'])

How to customize <input type="file">?

Something like that maybe?

<form>
  <input id="fileinput" type="file" style="display:none;"/>
</form>
<button id="falseinput">El Cucaratcha, for example</button>
<span id="selected_filename">No file selected</span>

<script>
$(document).ready( function() {
  $('#falseinput').click(function(){
    $("#fileinput").click();
  });
});
$('#fileinput').change(function() {
  $('#selected_filename').text($('#fileinput')[0].files[0].name);
});

</script>

What does "xmlns" in XML mean?

I think the biggest confusion is that xml namespace is pointing to some kind of URL that doesn't have any information. But the truth is that the person who invented below namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

could also call it like that:

xmlns:android="asjkl;fhgaslifujhaslkfjhliuqwhrqwjlrknqwljk.rho;il"

This is just a unique identifier. However it is established that you should put there URL that is unique and can potentially point to the specification of used tags/attributes in that namespace. It's not required tho.

Why it should be unique? Because namespaces purpose is to have them unique so the attribute for example called background from your namespace can be distinguished from the background from another namespace.

Because of that uniqueness you do not need to worry that if you create your custom attribute you gonna have name collision.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

The good folks at HubSpot have a resource where you can find pure Javascript methodologies for achieving a lot of jQuery goodness - including ready

http://youmightnotneedjquery.com/#ready

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}

example inline usage:

ready(function() { alert('hello'); });

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

How to define an empty object in PHP

You can also get an empty object by parsing JSON:

$blankObject= json_decode('{}');

What is JavaScript garbage collection?

garbage collection (GC) is a form of automatic memory management by removing the objects that no needed anymore.

any process deal with memory follow these steps:

1 - allocate your memory space you need

2 - do some processing

3 - free this memory space

there are two main algorithm used to detect which objects no needed anymore.

Reference-counting garbage collection: this algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it", the object will removed if no reference point to it

Mark-and-sweep algorithm: connect each objects to root source. any object doesn't connect to root or other object. this object will be removed.

currently most modern browsers using the second algorithm.

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

git - remote add origin vs remote set-url origin

  • When you run git remote add origin [email protected]:User/UserRepo.git, then a new remote created named origin.
  • When you run git remote set-url origin [email protected]:User/UserRepo.git,git searches for existing remote having name origin and change it's remote repository url. If git unable to find any remote having name origin, It raise an error fatal: No such remote 'origin'.

If you are going to create a new repository then use git remote add origin [email protected]:User/UserRepo.git to add remote.

How to add Google Maps Autocomplete search box?

To get latitude and longitude too, you can use this simple code:

<html>
<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('city2').value = place.name;
                document.getElementById('cityLat').value = place.geometry.location.lat();
                document.getElementById('cityLng').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
    <input type="hidden" id="city2" name="city2" />
    <input type="hidden" id="cityLat" name="cityLat" />
    <input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>

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

Here's something I found:

:pingtheserver
ping %input% | find "Reply" > nul
if not errorlevel 1 (
    echo server is online, up and running.
) else (
    echo host has been taken down wait 3 seconds to refresh
    ping 1.1.1.1 -n 1 -w 3000 >NUL
    goto :pingtheserver
) 

Note that ping 1.1.1.1 -n -w 1000 >NUL will wait 1 second but only works when connected to a network

Setting a PHP $_SESSION['var'] using jQuery

You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:

HTML:

<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />

Javascript:

$("img.foo").onclick(function()
{
    // Get the src of the image
    var src = $(this).attr("src");

    // Send Ajax request to backend.php, with src set as "img" in the POST data
    $.post("/backend.php", {"img": src});
});

PHP (backend.php):

<?php
    // do any authentication first, then add POST variable to session
    $_SESSION['imgsrc'] = $_POST['img'];
?>

How to declare or mark a Java method as deprecated?

Use the annotation @Deprecated for your method, and you should also mention it in your javadocs.

Getting attributes of a class

Another simple solution:

class Color(const):
    BLUE = 0
    RED = 1
    GREEN = 2

    @classmethod
    def get_all(cls):
        return [cls.BLUE, cls.RED, cls.GREEN]

Usage: Color.get_all()

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

In Android, the structure is different from .NET:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Hello!")
       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // Handle Ok
           }
       })
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // Handle Cancel
           }
       })
       .create();

Will get you a dialog with two buttons and you handle the button clicks with callbacks. You might be able to write some code to make the syntax more closely resemble .NET, but the dialog lifecycle is pretty intertwined with Activity, so in the end, it might be more trouble than it's worth. Additional dialog references are here.

Does Android keep the .apk files? if so where?

There is no standard location, however you can use the PackageManager to find out about packages and the ApplicationInfo class you can get from there has various information about a particular package: the path to its .apk, the path to its data directory, the path to a resource-only .apk (for forward locked apps), etc. Note that you may or may not have permission to read these directories depending on your relationship with the other app; however, all apps are able to read the resource .apk (which is also the real .apk for non-forward-locked app).

If you are just poking around in the shell, currently non-forward-locked apps are located in /data/app/.apk. The shell user can read a specific .apk, though it can't list the directory. In a future release the naming convention will be changed slightly, so don't count on it remaining the same, but if you get the path of the .apk from the package manager then you can use it in the shell.

Extract / Identify Tables from PDF python

I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py

This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.

How can JavaScript save to a local file?

While most despise Flash, it is a viable option for providing "save" and "save as" functionality in your html/javascript environment.

I've created a widget called "OpenSave" that provides this functionality available here:

http://www.gieson.com/Library/projects/utilities/opensave/

-mike

Convert character to ASCII numeric value in java

I know this has already been answered in several forms but here is my bit of code with a look to go through all the characters.

Here is the code, started with the class

public class CheckChValue {  // Class name
public static void main(String[] args) { // class main

    String name = "admin"; // String to check it's value
    int nameLenght = name.length(); // length of the string used for the loop

    for(int i = 0; i < nameLenght ; i++){   // while counting characters if less than the length add one        
        char character = name.charAt(i); // start on the first character
        int ascii = (int) character; //convert the first character
        System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
    }
}

}

How to find patterns across multiple lines using grep?

With silver searcher:

ag 'abc.*(\n|.)*efg'

similar to ring bearer's answer, but with ag instead. Speed advantages of silver searcher could possibly shine here.

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

Importing a CSV file into a sqlite3 database table using Python

Many thanks for bernie's answer! Had to tweak it a bit - here's what worked for me:

import csv, sqlite3
conn = sqlite3.connect("pcfc.sl3")
curs = conn.cursor()
curs.execute("CREATE TABLE PCFC (id INTEGER PRIMARY KEY, type INTEGER, term TEXT, definition TEXT);")
reader = csv.reader(open('PC.txt', 'r'), delimiter='|')
for row in reader:
    to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8"), unicode(row[2], "utf8")]
    curs.execute("INSERT INTO PCFC (type, term, definition) VALUES (?, ?, ?);", to_db)
conn.commit()

My text file (PC.txt) looks like this:

1 | Term 1 | Definition 1
2 | Term 2 | Definition 2
3 | Term 3 | Definition 3

Rotate label text in seaborn factorplot

Any seaborn plots suported by facetgrid won't work with (e.g. catplot)

g.set_xticklabels(rotation=30) 

however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.

g.set_xticklabels(g.get_xticklabels(), rotation=30)

Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

ResourceDictionary in a separate assembly

For UWP:

<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Tracing the root cause, i finally found that the public key of type dsa is not added to the authorized keys on remote server. Appending the same worked for me.

The ssh was working with rsa key, causing me to look back in my code.

thanks everyone.

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

How to check if C string is empty

You can check the return value from scanf. This code will just sit there until it receives a string.

int a;

do {
  // other code
  a = scanf("%s", url);

} while (a <= 0);

How to discard local changes and pull latest from GitHub repository

Run the below commands

git log

From this you will get your last push commit hash key

git reset --hard <your commit hash key>

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Disable building workspace process in Eclipse

You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

Does java.util.List.isEmpty() check if the list itself is null?

You can use your own isEmpty (for multiple collection) method too. Add this your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}

Date difference in minutes in Python

In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:

from datetime import datetime
import time

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)

diff = d2 -d1
diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)

print(diff_minutes)
> 3043

How to extract this specific substring in SQL Server?

An alternative to the answer provided by @Marc

SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
    CHARINDEX(';', YOUR_FIELD) > 0;

This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.

JAX-WS client : what's the correct path to access the local WSDL?

Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix

  1. Make your wsdl local location reference as wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
  2. Create a META-INF folder right under the src. Put your wsdl file/s in a folder under META-INF, say META-INF/wsdl
  3. Create an xml file jax-ws-catalog.xml under META-INF as below

    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system"> <system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" /> </catalog>

Now package your jar. No more reference to the local directory, it's all packaged and referenced within

How to define a preprocessor symbol in Xcode

You can use the *_Prefix.pch file to declare project wide macros. That file is usually in you Other Sources group.

Save text file UTF-8 encoded with VBA

You can use CreateTextFile or OpenTextFile method, both have an attribute "unicode" usefull for encoding settings.

object.CreateTextFile(filename[, overwrite[, unicode]])        
object.OpenTextFile(filename[, iomode[, create[, format]]])

Example: Overwrite:

CreateTextFile:
 fileName = "filename"
 Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.CreateTextFile(fileName, True, True)
 out.WriteLine ("Hello world!")
 ...
 out.close

Example: Append:

 OpenTextFile Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.OpenTextFile("filename", ForAppending, True, 1)
 out.Write "Hello world!"
 ...
 out.Close

See more on MSDN docs

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

Partly cherry-picking a commit with Git

If you want to specify a list of files on the command line, and get the whole thing done in a single atomic command, try:

git apply --3way <(git show -- list-of-files)

--3way: If a patch does not apply cleanly, Git will create a merge conflict so you can run git mergetool. Omitting --3way will make Git give up on patches which don't apply cleanly.

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

Mongoose's find method with $or condition does not work properly

async() => {
let body = await model.find().or([
  { name: 'something'},
  { nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */

Convert between UIImage and Base64 string

In Swift 3.0

func decodeBase64(toImage strEncodeData: String) -> UIImage {

    let dataDecoded  = NSData(base64Encoded: strEncodeData, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
    let image = UIImage(data: dataDecoded as Data)
    return image!

}

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

How to call a method function from another class?

For calling the method of one class within the second class, you have to first create the object of that class which method you want to call than with the object reference you can call the method.

class A {
   public void fun(){
     //do something
   }
}

class B {
   public static void main(String args[]){
     A obj = new A();
     obj.fun();
   }
}

But in your case you have the static method in Date and TemperatureRange class. You can call your static method by using the class name directly like below code or by creating the object of that class like above code but static method ,mostly we use for creating the utility classes, so best way to call the method by using class name. Like in your case -

public static void main (String[] args){
  String dateVal = Date.date("01","11,"12"); // calling the date function by passing some parameter.

  String tempRangeVal = TemperatureRange.TempRange("80","20"); 
}

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

This is due to adding an image in drawable which has some extension like (.jpg), and you have changed or saved that to a .png format (this error will occur while changing the image format manually without using an editor tool).

Android Studio will throws an error while compiling the resource package using AAPT (Android Asset Packaging Tool), so all you need to do is use some image editor tools like GIMP or Paint to save the extension accordingly. Rebuild your project once everything is done.

For example: open your image in Paint (drag and drop your image to open it) ? menu File ? Save As ? Save as Type ? select your required type from the dropdown like I have shown in the below pictures:

Enter image description here

Enter image description here

click() event is calling twice in jquery

please try this

$('#ddlSupervisor').live('change', function (e) {
    if (e.handled !== true) { //this makes event to fire only once
    getEmployeesbySupervisor();
    e.handled = true;
   }
});

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

saving a file (from stream) to disk using c#

if the data is already valid and already contains a pdf, word or image, then you could use a StreamWriter and save it.

Java Pass Method as Parameter

Here is a basic example:

public class TestMethodPassing
{
    private static void println()
    {
        System.out.println("Do println");
    }

    private static void print()
    {
        System.out.print("Do print");
    }

    private static void performTask(BasicFunctionalInterface functionalInterface)
    {
        functionalInterface.performTask();
    }

    @FunctionalInterface
    interface BasicFunctionalInterface
    {
        void performTask();
    }

    public static void main(String[] arguments)
    {
        performTask(TestMethodPassing::println);
        performTask(TestMethodPassing::print);
    }
}

Output:

Do println
Do print

Copying a local file from Windows to a remote server using scp

I have found it easiest to use a graphical interface on windows (I recommend mobaXTerm it has ssh, scp, ftp, remote desktop, and many more) but if you are set on command line I would recommend cd'ing into the directory with the source folder then
scp -r yourFolder username@server:/path/to/dir
the -r indicates recursive to be used on directories

How to use putExtra() and getExtra() for string data

You can Simply use static variable to store the string of your edittext and then use that variable in the other class. Hope this will solve your problem

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

JavaScript OOP in NodeJS: how?

I suggest to use the inherits helper that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on the linked page.

Deny direct access to all .php files except index.php

An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.

A direct answer is to include the following in .htaccess:

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.

How to append to a file in Node?

My approach is rather special. I basically use the WriteStream solution but without actually 'closing' the fd by using stream.end(). Instead I use cork/uncork. This got the benefit of low RAM usage (if that matters to anyone) and I believe it's more safe to use for logging/recording (my original use case).

Following is a pretty simple example. Notice I just added a pseudo for loop for showcase -- in production code I am waiting for websocket messages.

var stream = fs.createWriteStream("log.txt", {flags:'a'});
for(true) {
  stream.cork();
  stream.write("some content to log");
  process.nextTick(() => stream.uncork());
}

uncork will flush the data to the file in the next tick.

In my scenario there are peaks of up to ~200 writes per second in various sizes. During night time however only a handful writes per minute are needed. The code is working super reliable even during peak times.

Turn off deprecated errors in PHP 5.3

I tend to use this method

$errorlevel=error_reporting();
$errorlevel=error_reporting($errorlevel & ~E_DEPRECATED);

In this way I do not turn off accidentally something I need

Can one class extend two classes?

I can think of a workaround that can help if the classes you want to extend include only methods.

Write these classes as interfaces. In Java, you can implements any number of interfaces, and implement the methods as default methods in the interfaces.

https://www.geeksforgeeks.org/default-methods-java/

How to turn off magic quotes on shared hosting?

If you're running PHP 5.3+ this will do the trick, place it at the topmost of your page:

if (get_magic_quotes_gpc() === 1)
{
    $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
    $_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
    $_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
    $_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}

Handles keys, values and multi-dimensional arrays.

How to connect a Windows Mobile PDA to Windows 10

I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

How to update/modify an XML file in python?

The quick and easy way, which you definitely should not do (see below), is to read the whole file into a list of strings using readlines(). I write this in case the quick and easy solution is what you're looking for.

Just open the file using open(), then call the readlines() method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines().

An example might help:

my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)

The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parser. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand.

Tim's answer mentioned checking out xml.dom.minidom for this purpose, which I think would be a great idea.

Laravel: Get base url

This:

echo url('/');

And this:

echo asset('/');

both displayed the home url in my case :)

React navigation goBack() and update parent state

I was facing a similar issue, so here is how I solved it by going more into details.

Option one is to navigate back to parent with parameters, just define a callback function in it like this in parent component:

updateData = data => {
  console.log(data);
  alert("come back status: " + data);
  // some other stuff
};

and navigate to the child:

onPress = () => {
  this.props.navigation.navigate("ParentScreen", {
    name: "from parent",
    updateData: this.updateData
  });
};

Now in the child it can be called:

 this.props.navigation.state.params.updateData(status);
 this.props.navigation.goBack();

Option two. In order to get data from any component, as the other answer explained, AsyncStorage can be used either synchronously or not.

Once data is saved it can be used anywhere.

// to get
AsyncStorage.getItem("@item")
  .then(item => {
    item = JSON.parse(item);
    this.setState({ mystate: item });
  })
  .done();
// to set
AsyncStorage.setItem("@item", JSON.stringify(someData));

or either use an async function to make it self-update when it gets new value doing like so.

this.state = { item: this.dataUpdate() };
async function dataUpdate() {
  try {
    let item = await AsyncStorage.getItem("@item");
    return item;
  } catch (e) {
    console.log(e.message);
  }
}

See the AsyncStorage docs for more details.

How to get jQuery dropdown value onchange event

Try like this

 $("#drop").change(function () {
        var end = this.value;
        var firstDropVal = $('#pick').val();
    });

Response to preflight request doesn't pass access control check

My "API Server" is an PHP Application so to solve this problem I found the below solution to work:

Place the lines in index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Remove blue border from css custom-styled button in Chrome

For anyone using Bootstrap and having this problem, they use :active:focus as well as just :active and :focus so you'll need:

element:active:focus {
    outline: 0;
}

Hopefully saved someone some time figuring that one out, banged my head for bit wondering why such a simple thing wasn't working.

If hasClass then addClass to parent

You can't use $(this) since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide(). There's no reason to test to see if the class exists.

Vertical align text in block element

li a {
width: 300px;
height: 100px;
display: table-cell;
vertical-align: middle;
margin: auto 0;
background: red;

}

importing jar libraries into android-studio

Android Studio 1.0.1 doesn't make it any clearer, but it does make it somehow easier. Here's what worked for me:

1) Using explorer, create an 'external_libs' folder (any other name is fine) inside the Project/app/src folder, where 'Project' is the name of your project

2) Copy your jar file into this 'external_libs' folder

3) In Android Studio, go to File -> Project Structure -> Dependencies -> Add -> File Dependency and navigate to your jar file, which should be under 'src/external_libs'

3) Select your jar file and click 'Ok'

Now, check your build.gradle (Module.app) script, where you'll see the jar already added under 'dependencies'

Creating SolidColorBrush from hex color value

If you don't want to deal with the pain of the conversion every time simply create an extension method.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Then use like this: BackColor = "#FFADD8E6".ToBrush()

Alternately if you could provide a method to do the same thing.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

Why is my element value not getting changed? Am I using the wrong function?

It's document.getElementById, not document.getElementsByID

I'm assuming you have <input id="Tue" ...> somewhere in your markup.

Codeigniter how to create PDF

I've used dompdf with some success before. Although it can be a bit fussy about malformed HTML and there are still some CSS methods that aren't supported (e.g. css float does not work).

Download the package from github, and place it into a folder called dompdf in your application/thirdparty directory.

You can then create a helper with some functions to use the dompdf library, here is an example:

dompdf_helper.php :

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function pdf_create($html, $filename='', $stream=TRUE) 
{
    include APPPATH.'thirdparty/dompdf/dompdf_config.inc.php';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    if ($stream) {
        $dompdf->stream($filename.".pdf", array("Attachment" => 0));
    } else {
        return $dompdf->output();
    }
}

You simply pass the pdf_create method your HTML as a string, the filename for the pdf file it will generate, and then an optional thirdparameter. The third parameter is a true/false flag to determine if it should save the file to your server before prompting the user to download it or not.

Getting Lat/Lng from Google marker

try this

var latlng = new google.maps.LatLng(51.4975941, -0.0803232);
var map = new google.maps.Map(document.getElementById('map'), {
    center: latlng,
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Set lat/lon values for this property',
    draggable: true
});

google.maps.event.addListener(marker, 'dragend', function (event) {
    document.getElementById("latbox").value = this.getPosition().lat();
    document.getElementById("lngbox").value = this.getPosition().lng();
});

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

How to detect the screen resolution with JavaScript?

You can also get the WINDOW width and height, avoiding browser toolbars and... (not just screen size).

To do this, use: window.innerWidth and window.innerHeight properties. See it at w3schools.

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.

Add x and y labels to a pandas plot

The df.plot() function returns a matplotlib.axes.AxesSubplot object. You can set the labels on that object.

ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")

enter image description here

Or, more succinctly: ax.set(xlabel="x label", ylabel="y label").

Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label' would work too.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Make the id parameter be a nullable int:

public ActionResult Edit(int? id, User collection)

And then add the validation:

if (Id == null) ...

What is the size of a pointer?

To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.

Evaluating string "3*(4+2)" yield int 18

You could fairly easily run this through the CSharpCodeProvider with suitable fluff wrapping it (a type and a method, basically). Likewise you could go through VB etc - or JavaScript, as another answer has suggested. I don't know of anything else built into the framework at this point.

I'd expect that .NET 4.0 with its support for dynamic languages may well have better capabilities on this front.

How to round up integer division and have int result in Java?

(message.length() + 152) / 153

This will give a "rounded up" integer.

how can I display tooltip or item information on mouse over?

The title attribute works on most HTML tags and is widely supported by modern browsers.

Including JavaScript class definition from another file in Node.js

Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

Simple pagination in javascript

I'll address any questions you have... but here is an improved pattern you should follow to reduce code duplication.

As a sidenote though, you should consider not doing pagination on client-side. Since if you have a huge dataset, it would mean you need to download all the data before your page loads. Better to implement server-side pagination instead.

Fiddle: http://jsfiddle.net/Lzp0dw83/

HTML

<div id="listingTable"></div>
<a href="javascript:prevPage()" id="btn_prev">Prev</a>
<a href="javascript:nextPage()" id="btn_next">Next</a>
page: <span id="page"></span>

Javascript (put anywhere):

var current_page = 1;
var records_per_page = 2;

var objJson = [
    { adName: "AdName 1"},
    { adName: "AdName 2"},
    { adName: "AdName 3"},
    { adName: "AdName 4"},
    { adName: "AdName 5"},
    { adName: "AdName 6"},
    { adName: "AdName 7"},
    { adName: "AdName 8"},
    { adName: "AdName 9"},
    { adName: "AdName 10"}
]; // Can be obtained from another source, such as your objJson variable

function prevPage()
{
    if (current_page > 1) {
        current_page--;
        changePage(current_page);
    }
}

function nextPage()
{
    if (current_page < numPages()) {
        current_page++;
        changePage(current_page);
    }
}

function changePage(page)
{
    var btn_next = document.getElementById("btn_next");
    var btn_prev = document.getElementById("btn_prev");
    var listing_table = document.getElementById("listingTable");
    var page_span = document.getElementById("page");

    // Validate page
    if (page < 1) page = 1;
    if (page > numPages()) page = numPages();

    listing_table.innerHTML = "";

    for (var i = (page-1) * records_per_page; i < (page * records_per_page); i++) {
        listing_table.innerHTML += objJson[i].adName + "<br>";
    }
    page_span.innerHTML = page;

    if (page == 1) {
        btn_prev.style.visibility = "hidden";
    } else {
        btn_prev.style.visibility = "visible";
    }

    if (page == numPages()) {
        btn_next.style.visibility = "hidden";
    } else {
        btn_next.style.visibility = "visible";
    }
}

function numPages()
{
    return Math.ceil(objJson.length / records_per_page);
}

window.onload = function() {
    changePage(1);
};

UPDATE 2014/08/27

There is a bug above, where the for loop errors out when a particular page (the last page usually) does not contain records_per_page number of records, as it tries to access a non-existent index.

The fix is simple enough, by adding an extra checking condition into the for loop to account for the size of objJson:

Updated fiddle: http://jsfiddle.net/Lzp0dw83/1/

for (var i = (page-1) * records_per_page; i < (page * records_per_page) && i < objJson.length; i++)

Stash only one file out of multiple files that have changed with Git?

In this situation I git add -p (interactive), git commit -m blah and then stash what's left if necessary.

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

Map<String, String>, how to print both the "key string" and "value string" together

Inside of your loop, you have the key, which you can use to retrieve the value from the Map:

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}

How do you easily horizontally center a <div> using CSS?

.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

.divclass {
   min-width: 200px;
}

Then you can set your div to be

<div class="center divclass">stuff in here</div>

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

The easiest and the correct way to do it - use Spacer()

Example:

Column(
    children: [
      SomeWidgetOnTheTop(),
      Spacer(),
      SomeCenterredBottomWidget(),
    ],
);

Why is my Button text forced to ALL CAPS on Lollipop?

Set android:textAllCaps="false". If you are using an appcompat style, make sure textAllCaps comes before the style. Otherwise the style will override it. For example:

android:textAllCaps="false"
style="@style/Base.TextAppearance.AppCompat"

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String